there are three types of inheritance:
- public
- protected
- private
the dafult mode for class is private, and for struct it is public:
In the absence of an access-specifier for a base class, public is
assumed when the derived class is defined with the class-key struct
and private is assumed when the class is defined with the class-key
class.
[From C++ standard, 11.2.2]
So, when you say:
class B: A
this is private inheritance and thus all public and protected members of a base class will be inherited as private. What you need is
class B: public A
or
class B: protected A
Private and protected inheritance is used more often where defining implementation details. Private bases are most useful when defining a class by restricting the interface to a base so that stronger guarantees can be provided. For example, Vec
adds
range checking to its private base vector
(§3.7.1) and the list
of pointers template adds type checking to its list<void*>
base -> see Stroustrup ("C++..." §13.5).
Example:
//Class A
class A
{
public:
int getX(){return _x;};
protected:
int getX2(){return _x;}
private:
int _x;
};
//Class B
class B : protected A //A::getX and A::getX2 are not visible in B interface,
^^^^^^^^^ // but still we can use it inside B class: inherited
// members are always there, the inheritance mode
// affects only how they are accessible outside the class
// in particular for a children
{
public:
int method(){ return this->getX();}
int method2(){ return this->getX2();}
};
int main(int argc, char** argv) {
B b=B();
printf("b.getX(): %d",b.method()); // OK
printf("b.getX(): %d",b.method2()); // OK
return 0;
}
Further effects to inheritance
Additionally, when you declare class as
class B: A
being the same as class B: private A
further inheritance becomes unavailable: only class that derives from A
and its friends can use A
public and protected members. Only friends and members of B
can convert B*
to A*
.
If A
is a protected base then its public and protected members can be used by class B
and its friends and by classes derived from B
and their friends. Only friends and members of B
and friends and members of class derived from B
can convert B*
to A*
.
If A
is a public base finally, then its public members can be used by any class and its protected members can be used by derived classes and their friends and by classes derived from B
and their friends. Any function can convert B*
to A*
.
Note also that you cannot cast constness with dynamic_cast
or static_cast
, it is said that they both respect constness. They both respect access controls also (it is not possible to cast to a private base [because only derived class methods might do Derived* -> Base*
and methods of classes being friends to this {friend declaration is in Base}])
more in Stroustrup ("C++", 15.3.2)