Constructor Inheritance

Jul 9, 2011 at 8:45pm
I've been using classes for a while now, but I have never encountered a problem such as this. It is probably something very stupid (as it always with me). Haha.

I have two classes. Class A and Class B. Class B inherits Class A, but the constructors don't cooperate with each other. I have parameters in the parent constructor and I'm assuming that I'm supposed to make the child class' parameters the same as the parent's.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class A
{
    ResourceManager ResMan;
    std::string Name;

    public:
    A(ResourceManager RM, std::string N) // ResourceManager is my image manager. Its irrelevant.
    {
        ResMan = RM; // In the Class A constructor I have transferred the 
        Name = N;    // parameters to values in the class itself.
    }
};

class B : public A
{
    B(ResourceManager RM, std::string N)
    {
        // What would I put in the child constructor?
        // The values are already transferred over.
    }
};


I'm pretty I'm just approaching this all wrong in my head, but could somebody please clarify this for me? :)
Last edited on Jul 9, 2011 at 8:46pm
Jul 9, 2011 at 8:50pm
B needs to call the appropriate A constructor. For this, you will need an initializer list:

1
2
3
4
5
6
7
class B : public A
{
    B(ResourceManager RM, std::string N)
      : A(RM,N)  // pass RM and N to A's constructor
    {
    }
};
Jul 9, 2011 at 8:52pm
The reason is because when you provide an explicit constructor the other ones go away, so the default B() constructor does not exist. So, as Disch said, you need to call the B(RM, N) constructor in the initializer list.
Jul 10, 2011 at 1:11am
OH! I see. Thanks guys!
Topic archived. No new replies allowed.