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;
}
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.
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