I am using private inheritance, and I am surprised to see that in the derived class use of any base object is not allowed.
class A;
class B : private A;
class C : public B;
C::method_1()
{
A* a; // Temporary "A" object for local computation
}
This has nothing to do with inheritance. I don't want to access any this->base method
!
This configuration provide a C2247 error in Visual Studio (" 'A' not accessible, because 'B' use 'private' to inherit from 'A' ").
With private inheritance, public and protected member of the base class become private members of the derived class. That means the methods of the base class do not become the public interface of the derived object.
Instead, private inheritance refers to the idea of being "implemented in terms of a". The key difference is that whereas public inheritance provides a common interface between two classes, private inheritance does not--rather, it makes all of the public functions of the parent class private in the child class.
A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
The private members of a class can be inherited but cannot be accessed directly by its derived classes. They can be accessed using public or protected methods of the base class. The inheritance mode specifies how the protected and public data members are accessible by the derived classes.
Change this:
A* a;
to this:
::A* a;
since C
inherits from B
, and B
from A
, thus you need the scope resolution operator to do the trick.
Instead of starting at the local scope which includes the class parents, ::A
starts looking at the global scope because of the ::
.
From the Standard:
11.1.5 Acess Specifiers
In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared.
ISO C++: 11.1 Access Specifiers
5 [Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared. —end note]
And the example from the standard:
class A { };
class B : private A { };
class C : public B {
A* p; // error: injected-class-name A is inaccessible
::A* q; // OK
};
N3797 Working Draft, Standard for Programming Language C++
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