Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does explicit typecasting allow upcasting for private inheritance?

Tags:

#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; } 
like image 238
Dblaze47 Avatar asked Mar 31 '16 08:03

Dblaze47


People also ask

What is upcasting in inheritance?

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.

Do we need explicit casting for a class type?

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.

What is the use of upcast in parent child initialization?

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.

Why the parent class is upcasted to 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. 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.


1 Answers

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.

C++11 §5.4/4:

The same semantic restrictions and behaviors [as for a static_cast] apply [for a C style cast], with the exception that in performing a static_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;

like image 54
Cheers and hth. - Alf Avatar answered Oct 03 '22 19:10

Cheers and hth. - Alf