Inheritance Example in C++


This code defines two classes Base and Derived where Derived is derived from Base class publicly. The Base class has two constructors, a default constructor and a parameterized constructor which takes an integer as input. The Derived class also has two constructors, a default constructor and a parameterized constructor which takes an integer as input. Additionally, the Derived class has another parameterized constructor that takes two integers as input, one for Base class constructor and one for Derived class constructor.

In the main function, three objects of Derived class are created using different constructors. d1 is created using the default constructor of Derived class, d2 is created using the parameterized constructor of Derived class which takes an integer as input, and d3 is created using the parameterized constructor of Derived class which takes two integers as input.

Source Code

#include <iostream>
using namespace std;
class Base
{
public:
    Base()
    {
        cout<<"Non-param Base"<<endl;
    }
    Base(int x)
    {
        cout<<"Param of Base "<<x<<endl;
    }
};
class Derived:public Base
{
public:
    Derived()
    {
        cout<<"Non-Param Derived"<<endl;
    }
    Derived(int y)
    {
        cout<<"Param of Derived "<<y<<endl;
    }
    Derived(int x,int y):Base(x)
    {
        cout<<"Param of Derived "<<y<<endl;
    }
};
int main()
{
    Derived d1,d2(5),d3(10,50);
}
To download raw file Click Here

Output

Non-param BaseNon-Param DerivedNon-param BaseParam of Derived 5Param of Base 10Param of Derived 50

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples