mercredi 25 avril 2018

How to restrict object creation only through parent class object?

Consider the following example.

class Parent
{
public:
    Child createChild();

// some member data and functions can go here.
}

class Child: public Parent
{
// some member data and functions can go here.
}

I would like to allow creation of "Child" class only through the method provided in the Parent class. That is I would like to deny the options to the user to instantiate an object of the Child class. I would also like avoid all the other default constructions of the Child class. How is it possible?

Parent p;
Child c = p.createChild(); // should be possible
Child d; //should not be allowed
Child e = c; // may not be allowed

Aucun commentaire:

Enregistrer un commentaire