#include<iostream> using namespace std; class A { public: void f(){cout<<"A"<<endl;} }; class B : private A { public: void f(){cout<<"B"<<endl;} }; int main (){
As Class B is inheriting Class A privately, this upcasting is not supposed to work:
A* a = new B;
But explicit typecasting is allowing it. Why?
A* a1 = (A*)new B; a1->f(); return 0; }
Clarification: The upcasting concept in inheritance is always applied upward the inheritance tree. The derived class objects can be type casted to any of its parent class type. Since is a relationship applies in general inheritance.
No Explicit casting required for the above mentioned sequence. We all know that when we are assigning smaller type to a larger type, there is no need for a casting required. Same applies to the class type as well.
Parent p = new Child (): This type of initialization is used to access only the members present in the parent class and the methods which are overridden in the child class. This is because the parent class is upcasted to the child class. What is upcasting? Upcasting is the typecasting of a child object to a parent object.
This is because the parent class is upcasted to the child class. What is upcasting? Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature.
The cast in
A* a1 = (A*)new B;
is a cast to inaccessible base class.
It can only be expressed as a C style cast. It is equivalent to what a static_cast
would do if a static_cast
could be used in this situation, and it is not equivalent to a reinterpret_cast
. In particular the result address is not necessarily the same as the argument address.
” The same semantic restrictions and behaviors [as for a
static_cast
] apply [for a C style cast], with the exception that in performing astatic_cast
in the following situations the conversion is valid even if the base class is inaccessible:— a pointer to an object of derived class type or an lvalue or rvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With