C++ Language



Admission Enquiry Form

  

Single Inheritance in C++:

Same name function in Derived class in C++


Same name function in Derived class in C++

Program :

//Single Inheritance in C++
#include<iostream>
using namespace std;
class Base1
{
public:
Base1()//default constructor
{
cout<<endl<<"I am default constructor of Base1";
}
void fun1()
{
cout<<endl<<"I am fun1 of Base1 class";
}
void fun2()
{
cout<<endl<<"I am fun2 of Base1 class";
}
void display()//same name function in Base1
{
cout<<endl<<"I am display of Base1 class";
}
};//end of Base class

class Derived : public Base1//Single inheritance
{
public:
Derived()//default constructor
{
cout<<endl<<"default constructor of Derived";
}
void fun3()
{
cout<<endl<<"I am fun3 of derived class";
}
void fun4()
{
cout<<endl<<"I am fun4 of derived class";
}
void display()//same name function in derived class
{
cout<<endl<<"I am display of Derived class";
}

};//end of Derived class

int main()
{
Derived d;//object of Derived class
d.fun1();//function of Base1 class
d.fun2();//function of Base2 class

d.fun3();//function of Derived Class
d.fun4();//function of Derived class

d.display();//display of derived class will be invoked

}//end of main


Note:- In the above example the display function of Derived class in invoked.So preference goes to own function,because we have created the object of the derived class

Output:

I am default constructor of Base1
default constructor of Derived
I am fun1 of Base1 class
I am fun2 of Base1 class
I am fun3 of derived class
I am fun4 of derived class
I am display of Derived class


Code to call Base function :

int main()
{
Derived d;//object of Derived class
d.fun1();//function of Base1 class
d.fun2();//function of Base2 class
d.Base1::display();//display of Base1 class will be invoked

d.fun3();//function of Derived Class
d.fun4();//function of Derived class

d.display();//display of derived class will be invoked

}//end of main


Output:

I am default constructor of Base1
default constructor of Derived
I am fun1 of Base1 class
I am fun2 of Base1 class
I am display of Base1 class
I am fun3 of derived class
I am fun4 of derived class
I am display of Derived class