askque
askque

Reputation: 319

inheritance constructor output

#include <iomanip>
#include <iostream>
#include <string>
using namespace std;

class Box
{
protected:
    double length;
    double width;
    double height;
public:
    // Constructors
    Box(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv}
    { std::cout << "Box(double, double, double) called.\n"; }

    Box(double side) : Box {side, side, side}
    { std::cout << "Box(double) called.\n"; }

    Box() { std::cout << "Box() called.\n"; }

    double volume() const
    { return length * width * height; }

    double getLength() const { return length; }
    double getWidth() const { return width; }
    double getHeight() const { return height; }
    ~Box()
    { cout << "box destructor" << endl; }
};


class Carton : public Box
{
private:
    string material {"Cardboard"};
public:
    Carton(double lv, double wv, double hv, const string desc) : Box {lv, wv, hv}, material {desc}
    { std::cout << "Carton(double,double,double,string) called.\n"; }

    Carton(const string desc) : material {desc}
    { std::cout << "Carton(string) called.\n"; }

    Carton(double side, const string desc) : Box {side},material {desc}
    { std::cout << "Carton(double,string) called.\n"; }

    Carton() { std::cout << "Carton() called.\n"; }

    ~Carton()
    { cout << "carton destructor" << endl; }
};

int main()
{
      Carton carton3 {4.0, "Plastic"};
}

In this code, I expect as output

Box(double) called.
Carton(double,string) called.
cartoon destructor
box destructor

But it shows as output

Box(double, double, double) called.
Box(double) called.
Carton(double,string) called.
cartoon destructor
box destructor

I don't understand that how Box(double, double, double) called. is shown on screen. I have traced the code step-by-step but it mustn't be on the output. Can someone explain the issue? Thanks.

Upvotes: 1

Views: 71

Answers (1)

Marko Popovic
Marko Popovic

Reputation: 4153

This line

Carton(double side, const string desc) : Box {side},material {desc}

indicates that constructor Box::Box(double side) will be called. However, that constructor is defined as:

Box(double side) : Box {side, side, side} // HERE is the call to second constructor
{ std::cout << "Box(double) called.\n"; }

which means that it will in turn call constructor Box::Box(double lv, double wv, double hv). The behavior you are describing is expected. Put a breakpoint on line:

{ std::cout << "Carton(double,double,double,string) called.\n"; }

and you will see that it will be hit when you run the program.

Upvotes: 1

Related Questions