How we can solve ambiguity in inheritance?
What is inheritance?
Inheritance is a mechanism to build a new class
from an existing class. This existing class is called base class/parent
class/super class. New creating class is called derived class/child class/sub
class.
Base/Super/Parent
Derived/Sub/Child
Here,
child class acquires all the properties from the parent class, means all the
data members and functions from the parent class to child class.
This
inheritance have types depend on no of base class and sub class.
If one
super class and one child class then it’s called single inheritance. As
described in above figure.
If
child class derived from more than one base class then it’s called multiple
inheritance.
In this
multiple inheritance class c is inherited from class A and Class B both. So,
there is possibility of use of function overriding, so, ambiguities arise.
Let us
see how we can solve this ambiguities?
Class A class B
Class
C
Here,
class C inherited from Class A and Class B both.
Suppose
class A and class B both have same function name , then class c have multiple
times that function inherited because it has been inherited from class A and
class B. So, when we call that function at runtime compiler has confusion which
function is going to be run from class A or class B?
Class A
{
Void display()
{
Cout<<”this is class
A:”<<endl;
}
};
Class B
{
Void disply()
{
Cout<<”this is class
B:”<<endl;
}
};
Class c
: public class A, public class B
{
Void displayc()
{
cout<<”this is class c”<<endl;}
}
Void
main()
{
C
c1;
Clrscr();
C1.display();
//compile time Error, ambiguity in A and B class , so, which function is goidg to be run?
C1.displayc();
// this give output from class c.
Getch();
}
}
Here,
same function name display() is used in both base class A and B. so, which
function is going to be run ?
So,
alternate solution is that we can use following syntax like:
C1.A
:: display();// this will execute function from class A
C1.B
:: display();// this will execute function from class B.
If
we use same function name void display () in all class (here class c also),
then which function is going to be run?
Then
function from class c is going to be executed.
If you
like this post then please share and like this post.
Call us
@ 98256 18292.
Visit
us @ tccicomputercoaching.com
To know
more about Computer Course In Ahmedabad,
Computer Class in Ahmedabad,
Computer
Course, Computer
Class
For
more information about Click
Here
No comments:
Post a Comment