Constructor in Inheritance

Why we use constructor in inheritance?

In C++, when a class is derived from another class (i.e., it inherits from a base class), the constructors in both the base class and the derived class play a crucial role in initializing objects. Here’s a breakdown of how constructors work in the context of inheritance:

Let us see the example:

In this given code, we have two classes: Appliance and WashingMachine. WashingMachine is a derived class that inherits from the base class Appliance. The code demonstrates the concept of constructors in inheritance.

Code

#include <iostream>
using namespace std;

class Appliance {
public:
    Appliance() {
        cout << "Default of Appliance" << endl;
    }
    Appliance(int power) {
        cout << "Appliance power: " << power << " watts" << endl;
    }
};

class WashingMachine : public Appliance {
public:
    WashingMachine() {
        cout << "Default of WashingMachine" << endl;
    }
    WashingMachine(int power, int capacity) : Appliance(power) {
        cout << "Washing Machine capacity: " << capacity << " kg" << endl;
    }
};

int main() {
    WashingMachine wm(2000, 7);

    return 0;
}

Output:

Appliance power: 2000 watts
Washing Machine capacity: 7 kg

Explanation

Step 1: Class Definitions:

1.Appliance Class:

class Appliance {
public:
    Appliance() {
        cout << "Default of Appliance" << endl;
    }
    Appliance(int power) {
        cout << "Appliance power: " << power << " watts" << endl;
    }
};
  • Default Constructor: Appliance() prints a message when an Appliance object is created with no arguments.
  • Parameterized Constructor: Appliance(int power) prints the power of the appliance when an Appliance object is created with a power value.

2. WashingMachine Class:

class WashingMachine : public Appliance {
public:
    WashingMachine() {
        cout << "Default of WashingMachine" << endl;
    }
    WashingMachine(int power, int capacity) : Appliance(power) {
        cout << "Washing Machine capacity: " << capacity << " kg" << endl;
    }
};
  • Default Constructor: WashingMachine() prints a message when a WashingMachine object is created with no arguments.
  • Parameterized Constructor: WashingMachine(int power, int capacity) initializes the base class Appliance with the power value and then prints the capacity of the washing machine.

Step 2: Main function

int main() {
    WashingMachine wm(2000, 7);
    return 0;
}
  • Creates an instance of WashingMachine with a power of 2000 watts and a capacity of 7 kg.

    Leave a Reply

    Your email address will not be published.

    Need Help?