Base Constructor Call in Derived Class

戏子无情 提交于 2019-12-20 05:35:15

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/34866676/base-constructor-call-in-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!