C++ Inheritance – Base Constructor Call in Derived Class

c++constructorinheritance

I have got the following problem in a homework for university, the task is as follows:

Derive a class MyThickHorizontalLine from MyLine. One requirement is that the constructor of the derived class MyThickHorizontalLine does not set the values itself, instead its obligated to call the base constructor.

Which currently looks like this in my cpp file:

MyThickHorizontalLine::MyThickHorizontalLine(int a, int b, int c)
{
    MyLine(a, b, c, b);
}

This is my Base constructor:

MyLine::MyLine(int x1, int y1, int x2, int y2)
{
    set(x1, y1, x2, y2);
}

Header Definition of MyLine:

public:
    MyLine(int = 0, int = 0, int = 0, int = 0);

Current problem is that when I debug this I step into the constructor of MyThickHorizontalLine my values for a b c are for example 1 2 3 they are set there and when I then step further and it gets into the Base constructor all my values are Zero.

I am probably missing a crucial part about inheritance here, but I can't get my mind on it.

Best Answer

MyThickHorizontalLine::MyThickHorizontalLine(int a, int b, int c)
{
     MyLine(a, b, c, b); // <<<< That's wrong
}

You cannot initialize your base class inside the constructor's body. Simply use the member initializer list to call the base class constructor:

MyThickHorizontalLine::MyThickHorizontalLine(int a, int b, int c) : MyLine(a, b, c, b) {}