简体   繁体   中英

Base Constructor Call in Derived Class

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.

 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) {}

In addition to:

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

In other words,

MyThickHorizontalLine::MyThickHorizontalLine(int a, int b, int c)
{
     MyLine(a, b, c, b); // <<<< This is temporary local object creation, like that one:
     MyLine tmp = MyLine(a, b, c, b);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM