[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]



  • Have you tried the code for what you where thinking?
    I don't know about anything that stops you to code a class with private or protected constructor.

    And if you give more details about what are you trying to accomplish, maybe some of us come with more appropriate solutions.



  • Hi,

    If you put definition of class A inside private section of class B, it will be visible only inside calss B.



  • I agree with Zlatomir: the constructor CAN be private and there are many reasonable use-cases (i.e. singletons)
    Just remember to also make the copy constructor private because otherwise it will be auto-generated as public, so class C could then make a copy of an A that was created in B.



  • 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!


  • Moderators

    Don't forget what Tannin wrote:

    bq. Just remember to also make the copy constructor private because otherwise it will be auto-generated as public, so class C could then make a copy of an A that was created in B.



  • [quote author="mlong" date="1338822657"]Don't forget what Tannin wrote:

    bq. Just remember to also make the copy constructor private because otherwise it will be auto-generated as public, so class C could then make a copy of an A that was created in B.[/quote]

    Thanks mlong, I will keep it in mind.

    (I have edited my previous code example.)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.