Upcasting is using the Super class's reference or pointer to refer to a Sub class's object. Or we can say that, the act of converting a Sub class's reference or pointer into its Super class's reference or pointer is called Upcasting.
class Super
{
int x;
public:
void funBase()
{
cout << "Super function";
}
};
class Sub:public Super
{
int y;
};
int main()
{
Super* ptr; // Super class pointer
Sub obj;
ptr = &obj;
Super &ref; // Super class's reference
ref=obj;
}
The opposite of Upcasting is Downcasting, in which we convert Super class's reference or pointer into derived class's reference or pointer. We will study more about Downcasting later
=
is never inherited. It can be overloaded but can't be inherited by sub class.In Multiple Inheritance, the derived class inherits from more than one base class. Hence, in Multiple Inheritance there are a lot chances of ambiguity.
class A
{
void show();
};
class B:public A
{
// class definition
};
class C:public A
{
// class defintion
};
class D:public B, public C
{
// class definition
};
int main()
{
D obj;
obj.show();
}
In this case both class B and C inherits function show()
from class A. Hence class D has two inherited copies of function show()
. In main() function when we call function show()
, then ambiguity arises, because compiler doesn't know which show()
function to call. Hence we use Virtual keyword while inheriting class.
class B : virtual public A
{
// class definition
};
class C : virtual public A
{
// class definition
};
class D : public B, public C
{
// class definition
};
Now by adding virtual keyword, we tell compiler to call any one out of the two show()
funtions.
As we all know that whenever a derived class object is instantiated, the base class constructor is always called. But in case of Hybrid Inheritance, as discussed in above example, if we create an instance of class D, then following constructors will be called :
This will result in multiple calls to the constructor of class A, which is undesirable. As there is a single instance of virtual base class which is shared by multiple classes that inherit from it, hence the constructor of the base class is only called once by the constructor of concrete class, which in our case is class D.
If there is any call for initializing the constructor of class A in class B or class C, while creating object of class D, all such calls will be skipped.