Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private inheritance causing problem in c++ [duplicate]

Tags:

c++

Why would the following code run into error of ‘A’ is an inaccessible base of ‘B’? Here's my thoughts:

  • whenever we call function foo(), it will execute new B(5), which will first call the constructor of its base struct A.

  • struct A's constructor function is a public method, hence it should be accessible by its derived struct B (as protected if i'm not wrong).

  • then struct B's constructor function will be call to create a vector with five 0s.

  • then deleting object a will call destructor B, then destructor A.

Is there anything wrong with my logic? Your answer will be greatly appreciated

#include <iostream>
#include <vector>

using namespace std;

struct A 
{ 
    A() { cout << "Constructor A called"<< endl;} 
    virtual ~A() { cout << "Denstructor A called"<< endl;}
};

struct B : private A
{
    vector<double> v;
    B(int n) : v(n) { cout << "Constructor B called"<< endl;}
    ~ B() { cout << "Denstructor B called"<< endl;}
};

int main()
{
    const A *a = new B(5);
    delete a;

    return 0;
}
like image 414
Jeremy Avatar asked Feb 03 '23 16:02

Jeremy


1 Answers

There's nothing wrong with your logic, except that it's missing one point:

private inheritance basically means that only the inheriting class (B in this case) knows that it inherits from the base A. That in turn means that only B can make use of all the privileges that come with this inheritance. One of these privileges is to be able to cast B* to A*. The function foo() doesn't know about B's inheritance, so it cannot perform that cast.

like image 119
sebrockm Avatar answered Feb 15 '23 11:02

sebrockm