Why is this part repeated three times?

  c++, constructor, destructor

Here is my code:

#include  <iostream>
using namespace std;

class motor
{
public:
    motor();
    ~motor();

private:

};

motor::motor()
{
    cout << "I'm the motor of this car." << endl;
}

motor::~motor()
{
    cout << "the motor of this car is removed." << endl;
}

class doors
{
public:
    doors();
    ~doors();

private:

};

doors::doors()
{
    cout << "I'm the doors of this car." << endl;
}

doors::~doors()
{
    cout << "the doors of this car are removed." << endl;
}

class wheels
{
public:
    wheels();
    ~wheels();

private:

};

wheels::wheels()
{
    cout << "I'm the wheels of this car." << endl;
}

wheels::~wheels()
{
    cout << "the wheels of this car are removed." << endl;
}

class car
{
public:
    car(motor m,doors d,wheels w):m(m),d(d),w(w) {
        cout << "This car is assembled" << endl;
    }
    //car() {
    //  cout << "This car is assembled" << endl;
    //}
    ~car() {
        cout << "This car is removed." << endl;
    }

private:
    motor m;doors d;
    wheels w;
};


int main() {
    motor m;
    doors d;
    wheels w;
    car(m, d, w);
    //car();
    return 0;
}

Here is the result:

**I’m the motor of this car.

I’m the doors of this car.

I’m the wheels of this car.

This car is assembled

the motor of this car is removed.

the doors of this car are removed.

the wheels of this car are removed.

This car is removed.

the wheels of this car are removed.

the doors of this car are removed.

the motor of this car is removed.

the wheels of this car are removed.

the doors of this car are removed.

the motor of this car is removed.**

I am not fully understand the true nature of constructor and destructor in c++, please have someone enlighten me!

Source: Windows Questions C++

LEAVE A COMMENT