I have a base/parent class A and two child classes B and C.
And I would like to create new objects of B or C in a function in A (I only know in that function which object I need to create). Or is this a just a badly designed code (which I suspect)?
If it is possible then how do I should work it out with the headers (the child classes and the parent class are in seperate files)?
I mean the child class already includes the parent's header file so I can't simply include the child's header file in the parent class...
So if A inherits B, why are you including the header file for A into B? I wouldn't be calling a function defined in A in a function defined in B. You can instead create a virtual function that A would override.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class B
{
public:
virtualvoid foo() = 0;
};
class A : public B
{
public:
virtualvoid foo();
};
I need to include the header of the parent class in every child class or not? Otherwise the compiler would not know what class it is I am talking about to inherit.
And maybe I better give an example here what it is I am trying to do:
//of course there are also some functions and variables in the classes besides the constructors
class A{
private:
int whichObject; // this is 1 when I need to use class B and 2 when I need class C
B objectB;
C objectC;
public:
A(){
whichObject = 0;
}
void decideWhichObject(){
if(whichObject == 1)
objectB = new B();
elseif(whichObject == 2)
objectC = new C();
}
};
class B : public A{
public:
B();
};
class C : public A{
public:
C();
};
@aquaz: that would be a solution but I need to have the child object in other functions of A too