How do I access privately inherited class members in C++? - 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)

Related

C++ Classes Importance of Public and Private Domains

I'm fairly new to C++ and just recently learned about classes. When you define something in the private domain of a class, such as a class function, how exactly is it limited to that class? For example:
class Example {
void dosomething(param1, param2);
};
Would that mean that you can't access the class function in the main function? If so, what's the point of doing that, wouldn't that mean you can't use it at all?
One final thing, I've always seen class attributes defined under the private section of the class. What would happen if you put it under public?
Would that mean that you can't access the class function in the main function?
Yes.
If so, what's the point of doing that, wouldn't that mean you can't use it at all?
Of course you can use it. From within other functions of this class:
class Example {
void dosomething(int a, int b) {
std::cout << "dosomething(a=" << a << ",b=" << b <<")\n";
public:
void callDoSomething(int b) {
dosomething(13, b);
}
};
//main
Example e;
e.callDoSomething(5);
One final thing, I've always seen class attributes defined under the private section of the class. What would happen if you put it under public?
Nothing would happen. They would be visible to everyone (just like private vs. public functions) and anyone can access them.
In general, to keep encapsulation alright you want data members to be private, but it strongly depends on use case. I suggest getting some books on OOP and encapsulation to learn more about the topic.

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.

Why does private inheritance increase the probability, as compared to composition, that someone will break my code?

The author of this article states that
"Normally you don't want to have access to the internals of too many other classes, and private inheritance gives you some of this extra power (and responsibility). But private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code."
Assume the following code where Car inherits from Engine privately :
#include <iostream>
using namespace std;
class Engine
{
int numCylinders;
public:
class exception{};
Engine(int i) { if( i < 4 ) throw exception(); numCylinders = i; }
void start() { cout << "Engine started " << numCylinders << " cylinders" << endl; }
};
class Car : private Engine
{
public:
Car(int i) : Engine(i) {}
using Engine::start;
};
int main()
{
try
{
Car c(4);
c.start();
}
catch( Engine::exception& )
{
cout << "A Car cannot have less than 4 cylinders" << endl;
}
}
My question is : how a Car can break this code, by setting up, for example, its Engine with less than 4 cylinders, using private inheritance and without protected members in the base class ?
I think the issue isn't that Car can break your Engine code, but rather that by changing Engine, someone can break your Car code. Inheritance represents a much tighter coupling than composition, so that changes in Engine are more likely to break a class that inherits from it rather than contains it. In the case of C++, an even looser coupling is achieved by having Car contain an Engine pointer or smart pointer.
One way in which inheritance introduces a much tighter coupling than membership is that the name space of the derived and the base class is mixed. Thus the meaning of a name in the context of the derived class depends on which names the base class introduces, and there are the usual overriding/hiding effects. A change in the base class can have effects on code in the derived class that is not necessarily clearly locatable or that would immediately produce a useful diagnostic. By contrast, if the interface of a member object changes, then the most that can break will be code that actually mentions the member object.
I don't see that Car can set Engine::numCylinders (at least not without dirty tricks like accessing the raw memory). The example in the article uses a protected method, you use a private member.
BTW: The article starts with "Use composition when you can" - and a Car has an Engine, but it is not an engine. When A is derived from B then this usually expresses A is a B.
The author of the article, in the previous point, refers to some of the "drawbacks" of using private inheritance, here:
The simple-composition variant is needed if you want to contain several Engines per Car
The private-inheritance variant can introduce unnecessary multiple inheritance
The private-inheritance variant allows members of Car to convert a Car* to an Engine*
The private-inheritance variant allows access to the protected members of the base class
The private-inheritance variant allows Car to override Engine's virtual functions
The private-inheritance variant makes it slightly simpler (20 characters compared to 28 characters) to give Car a start() method that simply calls through to the Engine's start() method

C++ subclassing access modifier?

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).