How to Call Constructor in Inheritance in C++

Free C++ course with real-time projects Start Now!!

Program 1

// Program for Role of Constructor in Inheritance
#include<iostream>
#define clrscr() system("cls")
using namespace std;

class First
{
        protected:
          int a,b;
       public:   
        First(int a,int b)  
        {
            cout<<"\nConstructor of First Class Parameterized"; 
            this->a=a;
            this->b=b;
        }
        First()
        {
            cout<<"\nConstructor of First Class Non Parameterized"; 
        }
        void addition();
};
class Second:public First
{
       public:
       Second(int x,int y):First(x,y)
       {
           cout<<"\nConstructor of Second Class Parameterized"; 
       }
       Second()
       {
           cout<<"\nConstructor of Second Class Non Parameterized"; 
       }
       void sub();
       void div();
};
void First::addition()
{
    int c;
    c=a+b;
    cout<<"\n"<<c;
}
void Second::sub()
{
    int c;
    c=a-b;
    cout<<"\n"<<c;
}
void Second::div()
{
    int c;
    c=a/b;
    cout<<"\n"<<c;
}
int  main()
{
      clrscr();
      Second S(50,10);
      S.addition();
      S.div();
      S.sub();

      return 0;
}



// class Base
// {
//     public:
//     Base(int a)
//     {
//         cout<<"\nThis is a constructor of Base class";
//     }
//     Base(){}
// };


// class First:public Base
// {
//     public:
//     First(int a)
//     {
//         cout<<"\nThis is a constructor of First class";
//     }
//     First()
//     {

//     }
// };
// class Second:public First
// {
//     public:
//     Second(int a)
//     {
//         cout<<"\nThis is a constructor of Second class";
//     }
    
// };
// int  main()
// {
//       clrscr();
//       Second S(10);
//       return 0;
// }

 

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *