I want to create a parent class Base
which has factories for its subclasses Derived1
, Derived2
etc. The constructor of Base
and all its derived classes should be private. I try to do it this way:
base.h:
class Derived1;
class Base
{
protected:
Base ();
public:
Base *createDerived1 ();
}
#include "derived1.h"
derived1.h:
#include "base.h"
class Derived1 : public Base
{
friend class Base;
private:
Derived1 ();
}
derived1.cpp:
Derived1::Derived1 ()
: Base ()
{
}
base.cpp:
Base *Base::createDerived1 ()
{
return new Derived1 (); // error C2248: 'Derived1::Derived1' : cannot access private member declared in class 'Derived1'
}
However, I cannot access the private constructor inside the factory, despite declaring Base
a friend class of Derived1
. Am I doing something wrong, or there is no possibility to have the parent class as friend and I should make constructors of Derived
classes public?
Following code works for me:
//B.h
class D;
class B{
protected:
B(){}
public:
static B* f();
};
//D.h
class D: public B{
friend class B;
private:
D():B(){}
};
//B.cpp
B* B::f(){
D *d=new D;
return d;
}
Your one bug is identified by the other reply. Another is the factory methods should be static
, since you will not be able to create Base
objects due to the fact that it has private constructor.