C++ subclassing access modifier? - c++

I'm C++ newbie, and I have many years of experience about OO languages such as C/C#/Objective-C. Now, I'm learning C++.
I saw this C++ code:
class World : public State
{
};
It seems class World inherits the class State publicly.
Public subclassing? It's hard to understand.
What's the concept of this feature?
And when is this useful or required?

The need for the public keyword there is just that for classes defined with the keyword class, the default access modifier (for everything - data members, member functions, and base classes) is private. So
class World : State {};
is the same as:
class World : private State {};
and that's probably not what you want - it means that the base class is only accessible within the class World. Outsiders "don't know" that the inheritance is there at all.
For classes defined with the keyword struct, the default access modifier is public, so you could write:
struct World : State {};
and get something that both looks and behaves a bit like every other language with inheritance. But the struct keyword, and the fact that it defines a class, is really only there for compatibility with C. You won't find many C++ style guides that recommend using it just in order to get the default public accessibility - generally it's used only for classes which are POD, or perhaps only for classes with no member functions at all.
As for why C++ has private inheritance in the first place: for most purposes, private inheritance is a form of composition. Normal composition:
class World {
State state;
public:
void foo() {
state.bar();
state.baz();
and so on
}
};
That is, the class World knows that it's implemented using a State, and the outside world doesn't know how World is implemented.
vs.
class World : private State {
public:
void foo() {
bar();
baz();
and so on
}
};
That is, the class World knows that it's implemented by being a State, and the outside world doesn't know how it's implemented. But you can selectively expose parts of the interface of State by for example putting using State::bar; in the public part of World's definition. The effect is as if you'd laboriously written a function (or several overloads) in World, each of which delegates to the same function on State.
Other than avoiding typing, though, one common use of private inheritance is when the class State is empty, i.e. has no data members. Then if it's a member of World it must occupy some space (admittedly, depending on the object layout this might be space that otherwise would just be padding, so it doesn't necessarily increase the size of World), but if it's a base class then a thing called the "empty base class optimization" kicks in, and it can be zero-size. If you're creating a lot of objects, this might matter. Private inheritance enables the optimization, but the outside world won't infer an "is-a" relationship, because it doesn't see the inheritance.
It's a pretty fine difference - if in doubt just use explicit composition. Introducing inheritance to save typing is all very well until it has some unexpected consequence.

In case
class World: private State
{
};
private inheritance means that all public and protected members of State would be inherited by World and would become private. This seals State inside World. No class that inherits from World will be able access any features of State.

What makes you think that it's private? It says public right there, which means it is publically subclassing.
That aside, what private and protected inheritance do is the same as public inheritance, except that all the member variables are functions are inherited with at least private or protected accessibility. For example, if State had a public member function 'foo()', it would be private in 'World'.
This is rarely used in practice, but it does have purpose. The most common use that I've seen is composition through inheritance. i.e. you want a "has a" relationship rather than an "is a" (that you usually get with public inheritance). By privately inheriting the class, you get all its variables and methods, but you don't expose them to the outside world.
One advantage of using private inheritance for composition comes from the empty base class optimisation (EBCO). Using normal composition, having a member object of an empty class would still use at least 1 byte because all variables must have a unique address. If you privately inherit the object you want to be composed of then that doesn't apply and you won't suffer memory loss.
e.g.
class Empty { };
class Foo
{
int foo;
Empty e;
};
class Bar : private Empty
{
int foo;
};
Here, sizeof(Foo) will probably be 5, but sizeof(Bar) will be 4 because of the empty base class.

The public/protected/private keyword before the name of the ancestor class indicates the desired visibility of members from the ancestor. With private inheritance, the descendant inherits only the implementation from the ancestor, but not the interface.
class A {
public:
void foo();
};
class B : private A {
public:
void bar();
};
void B::bar()
{
foo(); // can access foo()
}
B b;
b.foo(); // forbidden
b.bar(); // allowed
In general, you should use public inheritance because inheritance shouldn't be used for implementation re-use only (which is what private inheritance does).

Related

C++: Creating derived class that has access to private variables of base?

I have an abstract class base with private member variable base_var. I want to create a derived class, which also has base_var as a private member.
To me, this seems like an obvious thing you would want to do. base is abstract so it will never be instantiated. The only time I will create a base-object is if it is actually a derived object, so obviously when I give ´base´ a private member variable, what I am really trying to do is give that variable to all of its derived objects.
However, the below diagram seems to suggest that this is not doable with inheritance?
Why not? What would then even be the point of having private stuff in an abstract class? That class will never be instantiated, so all that private stuff is essentially useless?
However, the below diagram seems to suggest that this is not doable with inheritance?
Correct, private members of a class can not be accessed by derived classes. If You want a member of a class to be accessible by its derived classes but not by the outside, then You have to make it protected.
Why not? What would then even be the point of having private stuff in an abstract class? That class will never be instantiated, so all that private stuff is essentially useless?
Even an abstract class can have member functions which act on a (private) member variable. Consider (somewhat silly example, but well):
class MaxCached
{
private:
int cache = std::numeric_limits<int>::min();
public:
bool put(int value)
{
if (value > cache)
{
cache = value;
return true;
}
return false;
}
int get() const
{
return cache;
}
virtual void someInterface() const = 0;
};
Deriving from this class gives You the functionality of the base class (put and get) without the danger of breaking it (by for example writing a wrong value to cache).
Side note: Above is a purely made up example! You shouldn't add such a cache (which is independent of Your interface) into the abstract base class. As it stands the example breaks with the "Single Responsibility Principle"!
Just because a class is abstract doesn't mean there cannot be code implemented in that class that might access that variable. When you declare an item in a class to be private, the compiler assumes you had a good reason and will not change the access just because it there is a pure virtual function in the class.
If you want your derived classes to have access to a base class member declare the member as protected.
I have an abstract class base with private member variable base_var
class foo {
public:
virtual void a_pure_virtual_method() = 0;
int get_var() { base_var; }
virtual ~foo(){}
private:
int base_var;
};
Note that a class is said to be abstract when it has at least one pure virtual (aka abstract) method. There is nothing that forbids an abstract class to have non-pure virtual or even non-virtual methods.
I want to create a derived class, which also has base_var as a private member.
class derived : public foo {};
To me, this seems like an obvious thing you would want to do.
Sure, no problem so far.
The only time I will create a base-object is if it is actually a derived object, so obviously when I give ´base´ a private member variable, what I am really trying to do is give that variable to all of its derived objects.
Still fine.
Why not?
You are confusing access rights that are display in the image you included with the mere presence of the members in the derived. The derived class has no access to members that are private in the base class. Period. This is just according to the definition of what is private.
What would then even be the point of having private stuff in an abstract class? That class will never be instantiated, so all that private stuff is essentially useless?
It is not useless at all. Derived classes inherit all members, they just cannot access all of them. The private stuff is there you just cannot access it directly. Thats the whole point of encapsulation. Consider this example:
class bar : public foo {
void test() {
std::cout << base_var; // error base_var is private in foo
std::cout << get_var(); // fine
}
};

How do I access privately inherited class members in C++?

I'm trying to understand the private inheritance concept.
So far everywhere I see they write that private inheritance makes its members inaccessible from the derived class.
Doesn't this make it sort of useless? If I can't access the class inherited, what is the purpose of deriving in the first place?
Now I know private classes are actually used and helpful. I'm just having trouble in understanding how.
Your question reads as if private members would be useless altogether. I mean you could as well ask, what is a private member good for if it cannot be accessed from outside. However, a class (usually) has more than what a subclass can use.
Consider this simple example:
struct foo {
void print();
};
struct bar : private foo {
void print_bar() {
std::cout << " blablabla \n";
print();
std::cout << " bblablabla \n";
}
};
A class inheriting from bar wont even notice that bar inherits from foo. Nevertheless, it does make sense for bar to inherit from foo, because it uses its functionality.
Note that private inheritance is actually closer to composition rather than public inheritance, and the above could also be
struct bar {
foo f;
void print_bar() {
std::cout << " blablabla \n";
print();
std::cout << " bblablabla \n";
}
};
How do I access privately inherited class members in C++?
Outside of the class: You dont, thats what the private is for. It's not different for private members or private methods in general, they are there for a reason, you just cannot access them from outside.
It is indeed rare to want private inheritance, but sometimes you do want users of your class to not be able to reach members of the base class.
For example, I use Boost (www.boost.org) for my date class, but I don't want that exposed to users of my date class, since one day I might want to switch out Boost for something else.
Private inheritance is a way to model a has-a relationship. The usual alternative to model this is composition, which should be used when possible. Private inheritance is useful to model the has-a relationship when protected members of a class are involved.
A different way of framing it is "we want to use the implementation of this class, but ignore its interface".
(My experience with this is limited and this is what I recall from Scotty Meyers Effective C++, as there never arose a case where I would have prefered private inheritance over composition)

Private inheritance usage as described in "The C++ Programming Language"

In The C++ Programming Language, 4th Edition, at §20.5.2 "Access to Base Class" (page 605), it says (regarding private inheritance):
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, B is an implementation detail of Z .The Vector
of pointers template that adds type checking to its Vector base
from §25.3 is a good example.
It's not clear what Bjarne Stroustrup is trying to say here. How can be a class be defined by restricting "the interface" to a base? What does he mean by "stronger guarantees"?
Lets take a very simple example:
// A simple class with a *public* member
class A
{
public:
int a;
};
// Use private inheritance
class B : private A
{
public:
int b;
};
// Use public inheritance
class C : public A
{
public:
int c;
};
// ...
B my_b;
my_b.a = 0; // Invalid, the member a is private due to the private inhericance
C my_c;
my_c.a = 0; // Valid, because the inheritance is public
The private inheritance restricts access to the members of the base class. Even if the A::a member variable is public, due to the private inheritance it becomes private in the sub-class B.
Let's stay with the example of the vector. A vector is just a container of Ts. Now let's say you want to build a type that behaves just like a vector, but adds some additional runtime checks. I don't have my copy of TC++PL at hand right now, so let's just make up a constraint: For example, let's say your vector is only allowed to hold even numbers. Attempting to insert an odd number will result in a runtime error. Let's call this new class even_vector and the version without the runtime checks base_vector.
even_vector provides stronger runtime guarantees than base_vector: It is guaranteed that all of its elements are even.
Assuming that your base_vector is designed to work nice as a base class (which std::vector typically does not), you might now be tempted to use public inheritance to implement even_vector in terms of base_vector. After all, the functionality is the same, you simply have some additional runtime checks in the even_vector case on top of the functionality provided by base_vector. However, if you were to use public inheritance here, you would violate the Liskov Substitution Principle: You cannot use an even_vector wherever you use a base_vector. In particular, the even_vector will break in cases where you are inserting odd numbers into a base_vector. This is bad, as now all code that is written for base_vector must account for the fact that some of the base_vectors cannot deal with odd numbers.
With private inheritance you do not have this problem: Here the fact that even_vector inherits from base_vector is a detail of the implementation. Clients cannot use even_vector where a base_vector is expected, so the problem from above does not occur, but we still get the benefits of code reuse.
That being said, using private inheritance for code reuse is a practice that is discouraged by many. An arguably better way would be to use composition here instead, that is, add a private base_vector member to even_vector instead. The advantage of that approach is that it severely reduces coupling between the two classes, as even_vector is no longer able to access any non-public parts of base_vector.
how can be a class be defined by restricting "the interface" to a base?
By making the inheritance private. When the inheritance is private, the interface of the base class is restricted to the member functions and not available outside. The access specifier can be given in the list of bases:
class A : private B
// ^^^^^^^
What does he mean by "stronger guarantees"?
Any guarantee that is not given by the base, or is a superset of a guarantee given by the base.
For example, the guarantee that "behaviour is always well defined" is stronger than "Behaviour is well defined only if input is not null". Another example: "The function does not throw" is stronger than "The function will not throw unless the copy constructor throws".
Allow us to look at a possible situation with interfaces to help build up the picture.
class poison {
public:
virtual void used() = 0;
};
class food {
public:
virtual void eat();
protected:
void poisonConsumed(poison& p);
}
class cheese : public food, private poison {
public:
virtual void eat() override {
poisonConsumed(*this);
}
private:
void used() override;
}
This presents cheese to the outside world as 'not a poison' - ie nothing outside the class can know that it's a poison, and it could be made 'not a poison' to no impact on anything using it.
The cheese however, can pass itself to anything expecting a poison which is then free to call used(); even though it's private in cheese.

private inheritance in C++

I am learning the concepts of OOPS, and came across private inheritance. From what I've learnt - When a class derives from a base class and letter when the derived class is instantiated, the constructor of the Base class is called first, followed by the constructor of the derived class. So, in the code "A created" would be printed first.
The problem is since the inheritance is private, all the members of A would be private inside B, so how can the constructor of A be called when B is instantiated. Going by this logic, the following code should generate errors, but when I run it, it compiles fine, and gives the output "A created" followed by "B created".
How is this happening? Or am I making some mistake in understanding the concept?
#include <iostream>
using namespace std;
class A{
public:
A(void)
{
cout<<"A created"<<endl;
}
~A()
{
//do nothing
}
void doSomething(void)
{
cout<<"hi";
}
};
class B:private A
{
public:
B(void)
{
cout<<"B created"<<endl;
}
~B()
{
//do nothing
}
};
int main() {
B* myptr = new B();
//myptr->doSomething();
delete myptr;
return 0;
}
B can call public (and protected) methods of A, since A constructor is public B can call it.
Please see following link to better understand c++ private inheritance:
Difference between private, public, and protected inheritance
The access specifier for inheritance limits access to code outside the derived class; think to the base class A as if it were a normal private field:" the outside" can't see it, but B can use it freely from "the inside".
As for the constructor, it's implicitly called by B's constructor, so there's no problem (and, besides, otherwise private inheritance would be unusable).
Still, don't worry too much about private inheritance, it's useful in extremely rare cases (I've never seem it actually used in real life, and for this reason many languages don't even support it), normally composition (using a normal private field) is a better and simpler way.
Here is good short article about private inheritance which illustrates in details what is private inheritance, when it is useful and when it should be avoided in favour of inclusion.
In short:
Inheritance access modifier limits access to basic class properties and methods not for derived class but for code which uses derived class.
This is useful to 'replace' (not 'extend') basic class interface for users of inherited class.
In general it's considered better to include basic class member rather than use private inheritance.
If you need to reuse some methods of basic class which rely on virtual functions and you need to override virtual functions (but you still want to hide part of basic class interface from external code), this is more appropriate case for private inheritance.
Hope this will help.

Private method in a C++ interface?

Why would I want to define a C++ interface that contains private methods?
Even in the case where the methods in the public scope will technically suppose to act like template methods that use the private methods upon the interface implementation, even so, we're telling the technical specs. right from the interface.
Isn't this a deviation from the original usage of an interface, ie a public contract between the outside and the interior?
You could also define a friend class, which will make use of some private methods from our class, and so force implementation through the interface. This could be an argument.
What other arguments are for defining a private methods within an interface in C++?
The common OO view is that an interface establishes a single contract that defines how objects that conform to that interface are used and how they behave. The NVI idiom or pattern, I never know when one becomes the other, proposes a change in that mentality by dividing the interface into two separate contracts:
how the interface is to be used
what deriving classes must offer
This is in some sense particular to C++ (in fact to any language with multiple inheritance), where the interface can in fact contain code that adapts from the outer interface --how users see me-- and the inner interface --how I am implemented.
This can be useful in different cases, first when the behavior is common but can be parametrized in only specific ways, with a common algorithm skeleton. Then the algorithm can be implemented in the base class and the extension points in derived elements. In languages without multiple inheritance this has to be implemented by splitting into a class that implements the algorithm based in some parameters that comply with a different 'private' interface. I am using here 'private' in the sense that only your class will use that interface.
The second common usage is that by using the NVI idiom, it is simple to instrument the code by only modifying at the base level:
class Base {
public:
void foo() {
foo_impl();
}
private:
virtual void foo_impl() = 0;
};
The extra cost of having to write the dispatcher foo() { foo_impl(); } is rather small and it allows you to later add a locking mechanism if you convert the code into a multithreaded application, add logging to each call, or a timer to verify how much different implementations take in each function... Since the actual method that is implemented in derived classes is private at this level, you are guaranteed that all polymorphic calls can be instrumented at a single point: the base (this does not block extending classes from making foo_impl public thought)
void Base::foo() {
scoped_log log( "calling foo" ); // we can add traces
lock l(mutex); // thread safety
foo_impl();
}
If the virtual methods were public, then you could not intercept all calls to the methods and would have to add that logging and thread safety to all the derived classes that implement the interface.
You can declare a private virtual method whose purpose is to be derivated. Example :
class CharacterDrawer {
public:
virtual ~CharacterDrawer() = 0;
// draws the character after calling getPosition(), getAnimation(), etc.
void draw(GraphicsContext&);
// other methods
void setLightPosition(const Vector&);
enum Animation {
...
};
private:
virtual Vector getPosition() = 0;
virtual Quaternion getRotation() = 0;
virtual Animation getAnimation() = 0;
virtual float getAnimationPercent() = 0;
};
This object can provide drawing utility for a character, but has to be derivated by an object which provides movement, animation handling, etc.
The advantage of doing like this instead of provinding "setPosition", "setAnimation", etc. is that you don't have to "push" the value at each frame, instead you "pull" it.
I think this can be considered as an interface since these methods have nothing to do with actual implementation of all the drawing-related stuff.
Why would I want to define a C++
interface that contains private
methods?
The question is a bit ambiguous/contradictory: if you define (purely) an interface, that means you define the public access of anything that connects to it. In that sense, you do not define an interface that contains private methods.
I think your question comes from confusing an abstract base class with an interface (please correct me if I'm wrong).
An abstract base class can be a partial (or even complete) functionality implementation, that has at least an abstract member. In this case, it makes as much sense to have private members as it makes for any other class.
In practice it is rarely needed to have pure virtual base classes with no implementation at all (i.e. base classes that only define a list of pure virtual functions and nothing else). One case where that is required is COM/DCOM/XPCOM programming (and there are others). In most cases though it makes sense to add some private implementation to your abstract base class.
In a template method implementation, it can be used to add a specialization constraint: you can't call the virtual method of the base class from the derived class (otherwise, the method would be declared as protected in the base class):
class Base
{
private:
virtual void V() { /*some logic here, not accessible directly from Derived*/}
};
class Derived: public Base
{
private:
virtual void V()
{
Base::V(); // Not allowed: Base::V is not visible from Derived
}
};