Is it unusual/not recommended to call constructor of child in parent class?

Hi, title is my question.

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...
Last edited on
closed account (o1vk4iN6)
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:
     virtual void foo() = 0;
};

class A : public B
{
public:
     virtual void foo();

};
Last edited on
You must include B.h and C.h in A.cpp
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//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();
		else if(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
Last edited on
Ok sorry guys, once again I thought way too complicated and overlooked the obvious.

Actually the "child classes" I wanted to make dont even need to be child classes...

Anyway, thanks for taking the time to read and reply here, I'll take a break so I hopefully won't do some more stupid things ;)
Last edited on
Topic archived. No new replies allowed.