can derived class use base constructor c++ code example

Example 1: passing the value to base class constructor from derived class c++

#include <iostream>
#include<string>

using namespace std;

class Father{
protected:
    int height;
public:
    Father(){
    cout << "constructor of father is called"<<endl;

    }

};
class Mother{
protected:
    string skincolor;
public:
    Mother(){
    cout << "constructor of mother is called"<<endl;

    }

};

class Child : public Father,public Mother{
public:
    Child(int x,string color) : Father(),Mother(){
    height = x;
    skincolor = color;
    cout << "child classs constructor"<<endl;
    }
void display(){
cout << "height is "<<height<<" skin color is "<<skincolor<<endl;
}
};


int main()
{
    Child anil(24,"while");
    anil.display();
    return 0;
}

Example 2: constructor derived class c++

#include <iostream>
using namespace std;

class Complex
{
    int a, b;
    
public:

    Complex(int x, int y)
    {
        a = x;
        b = y;
    }

    Complex(int x)
    {
        a = x;
        b = 0;
    }

    Complex()
    {
        a = 0;
        b = 0;
    }

    void printNumber()
    {
        cout << "Your number is " << a << " + " << b << "i" << endl;
    }

};

int main()
{
    Complex c1(4, 6), c2(4), c3;

    c1.printNumber();
    c2.printNumber();
    c3.printNumber();

    return 0;
}

Tags:

Cpp Example