I want to implement the class with the following properties:
class A { ... };
const A a; // ok - should work.
A b; // compilation error - shouldn't work!
Also, it would be better, if the const
ness of an object depends on the constructors signature:
const A c(1); // ok - should work.
A d("a"); // ok - should work.
A e(2); // compilation error - shouldn't work!
Usage of C++11 is allowed, if required.
Since I don't know the answer, it's not required to strictly follow the code above - any C++ pattern providing similar semantics is welcome.
1.You can create class with only const methods and private members.
2.You can create "normal" class but declare its constructor as private. Then you will need a friend-class with following method (or something similar)
class ConstClassProvider{
public:
static const A* getA(/* you can have params here*/)
{
return new A();
}
}
so
A a1;//error
const A a2;//error
A *a3 = ConstClassProvider::getA(); //error
const A *a4 = ConstClassProvider::getA(); //ok!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With