Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to construct only const objects of specific type in C++?

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 constness 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.


Update #1

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.

like image 860
abyss.7 Avatar asked Feb 13 '23 18:02

abyss.7


1 Answers

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!
like image 163
Avt Avatar answered May 17 '23 11:05

Avt