Why does a base pointer point to a derived object only under common inheritance?

I think this is because the data elements and methods of the base class will not be available, but I would like to get more clear information about this. In addition, is this the reason that polymorphism (using virtual functions) is possible only under open inheritance?

+6
source share
3 answers

In fact, a pointer to a base can point to a derived class, even if the base is private. The fact is that such a transformation is impossible outside the class. However, it is still possible to implement such a conversion in the context of database availability.

Example:

#include <iostream> using namespace std; struct Base { void foo() const { cout << "Base::foo()\n"; } }; struct Derived : private Base { const Base* get() const { return this; // This is fine } }; int main() { Derived d; const Base *b = &d; // This is illegal const Base *b = d.get(); //This is fine b->foo(); } 

Living example

Virtual call example

+12
source

If I'm right, you are asking about the visibility of elements inside the class. As you stated, public / protected / private will affect the accessibility of your members / member functions / methods. (see The distinction between private, public, and protected inheritance ) However, polymorphism is not limited to public inheritance.

Example:

 class B { protected: virtual void do_B() = 0; }; class A : protected B { virtual void do_B() {}; }; 
+1
source

Here is an example to help you better understand

 class Base{ public: int foo; }; class Derived: private Base{ public: int bar; }; 

Now in this program you can see what an object of a derived class can do. A derived class object may

  • Access the panel with integer variables publicly.
  • Access to the integer variable foo is confidential (only inside the Derived class), because the inheritance relation is private.

Now let's see what happens if the base pointer can do, if it is made to point to such an object. For a base class pointer

  • The base pointer cannot access the variable bar, because it only points to the base section of the derived class object.
  • And according to the base class pointer, the variable foo is public. As defined in the base class, it is publicly available.

So, now you can see the ambiguity that a base pointer would encounter if it points to a class object inherited in a particular respect.

Ambiguity: according to the derived class, the foo object is private, but the base pointer considers it public.

Thus, the morale of private or protected inheritance is lost if such things are permitted. Hope this clears your doubts.

+1
source

Source: https://habr.com/ru/post/945481/


All Articles