[Solved] How to create a class that only can be instantiated from another?
Hi,
I would like to create a class ( ClassA ) with the following property:
ClassA only can be instantiated from ClassB.
For example, if another class called ClassC tries to instantiate ClassA, compiler must launch an error:
- ClassC::someMethod {
- ClassA *objectA = new ClassA();
- }
ERROR: ClassC can’t instantiate ClassA.
It is possible?
I was thinking about private constructor and friend class (ClassA and ClassB in my example), but constructor can’t be private by definition.
Thank you in advance.
[Edit: Moved to C++ Gurus forum, as this is not Qt-related; mlong]
6 replies
Thanks to Zlatomir, task_struct and Tannin, it works!
I read in a C++ manual that constructors cannot be private, so I didn’t try.
Finally, I used private constructors and friends class to achieve my first objective as follow:
Class A definition:
- class ClassA {
- public:
- friend class ClassB;
- private:
- ClassA();
- //(edited) Copy constructor added
- ClassA(const ClassA &classAsource);
- };
Class B definition:
- class ClassB
- {
- public:
- ClassB();
- };
Now, only ClassB can create objects from ClassA class, because only ClassB can access to constructor.
In this way I ensure that nobody will use ClassA on my code except ClassB.
Thank you!
You must log in to post a reply. Not a member yet? Register here!




