class a
{
public:
int var;
};
class b : a
{
};
int main()
{
a* p = new b();
return 0;
}
I know its caused by private inheritance but i wanna know why is it so?
class a
{
public:
int var;
};
class b : a
{
};
int main()
{
a* p = new b();
return 0;
}
I know its caused by private inheritance but i wanna know why is it so?
You explicitly specified that the base class is inherited as a private sub-object of the derived class. So it is inaccessible outside the class definition.
From the C++ 17 Standard(14.2 Accessibility of base classes and base class members)
- ...If a class is declared to be a base class for another class using the private access specifier, the public and protected members of the base class are accessible as private members of the derived class.
In this declaration
a* p = new b();
there is an attempt to access the private sub-object of the type a
of an object of the type b
because the static type of the pointer p
is a *
.
In fact this statement
a* p = new b();
has the same semantic as for example
class A
{
private:
int x = 10;
};
A a;
int *p = &a.x;
If this was allowed then using a pointer you could change a private subobject of an object.
This is just what "private" means in private inheritance. The fact that b
inherits from a
is an implementation detail and not visible from outside.
I'm not trying to access any private member outside the class, or any protected one outside class hierarchy, I'm just trying to create a dynamic object with a base class pointer and it raises an error
You are trying to access a conversion from a b*
to a a*
but you cannot, because from outside, the base class is not accessible. Private inheritance is closer to composition rather than public inheritance. Your example could be rewritten as
class b {
a a_instance;
};
The implementation of b
will be slightly different (because call to a
member functions is via a_instance
instead of this
), but the effect is the same: We compose b
of a
and users have no knowledge of that (aka private
).