private inheritance in C++ - 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.

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
}
};

Protected constructor to make base class not instantiable

Is it good practice to make a base class constructor protected if I want to avoid instances of it? I know that I could as well have a pure virtual dummy method, but that seems odd...
Please consider the following code:
#include <iostream>
using std::cout;
using std::endl;
class A
{
protected:
A(){};
public:
virtual void foo(){cout << "A\n";};
};
class B : public A
{
public:
void foo(){cout << "B\n";}
};
int main()
{
B b;
b.foo();
A *pa = new B;
pa->foo();
// this does (and should) not compile:
//A a;
//a.foo();
return 0;
}
Is there a disadvantage or side-effect, that I don't see?
It is common practice to make base class constructors protected. When you have a pure-virtual function in your base class, this is not required, as you wouldn't be able to instantiate it.
However, defining a non-pure virtual function in a base class is not considered good practice, but heavily depends on your use case and does not harm.
There isn't any disadvantage or side-effect. With a protected constructor you just tell other developers that your class is only intended to be used as a base.
What you want to achieve is normally done via the destructor, instead of the constructors, just beacause you can steer the behavior you need with that one function instead of having to deal with it with every new constructor you write. It's a common coding style/guideline, to
make the destructor public, if you want to allow instances of the class. Often those classes are not meant to be inherited from.
make the destructor pure virtual and public, if you want to use and delete the class in a polymorphic context but don't want to allow instances of the class. In other words, for base classes that are deleted polymorphcally.
make the destructor nonvirtual and protected, if you don't want to allow instances of the class and don't want to delete its derivates polymorphically. Normally, you then don't want to use them polymorphically at all, i.e. they have no virtual functions.
Which of the latter two you chose is a design decision and cannot be answered from your question.
It does what you're asking.
However I'm not sure what you are gaining with it. Someone could just write
struct B : A {
// Just to workaround limitation imposed by A's author
};
Normally it's not that one adds nonsense pure-virtual functions to the base class... it's that there are pure virtual functions for which no meaningful implementation can be provided at the base level and that's why they end up being pure virtual.
Not being able to instantiate that class comes as a nice extra property.
Make the destructor pure virtual. Every class has a destructor, and a base class should usually have a virtual destructor, so you are not adding a useless dummy function.
Take note that a pure virtual destructor must have a function body.
class AbstractBase
{
public:
virtual ~AbstractBase() = 0;
};
inline AbstractBase::~AbstractBase() {}
If you don't wish to put the destructor body in the header file, put it in the source file and remove inline keyword.

Why Inheritance influences Exception handling?

While finding answer for this query with writing test code, I got to know that private/protected inheritance changes the way exceptions are received from various classes, which was very surprising. To find the answer I referred earlier forum questions and I came across this similar question.
For me it's quite obvious to use protected inheritance for a base class with virtual methods. Keeping the standard aside, I wanted to know why in C++ exception handling is restricted by inheritance when virtual method calls are Not ?
Following snippet explains it:
struct Base { virtual void printError () = 0; };
class Derived : protected Base { void printError () { } };
int main ()
{
try {
throw new Derived;
}
catch(Base *p) { p->printError(); } // Ideal; but not invoked
catch(void *p) { ((Base*)p)->printError(); } // Ugly; but only way to invoke
}
Edit:
If we consider the privacy regard as an answer; accepted. But then why it's applicable only for catch() receiving base pointers, while it's not applicable for functions receiving base pointers ?
The meaning of private and protected inheritance is that no one outside of the class or class hierarchy can know about the inheritance. This is the same way as no one outside the class can know about a private member.
Catching a derived class by its base class revealed to the catcher that the derived class is infact derived from the base class and is a breach of the privacy of the inheritance.
protected inheritance means only Derived and its subclasses "knows" it also is-a Base. main, and the catch statement, doesn't "know" this. This is the point of inheriting with a specific access.
Virtual dispatch doesn't care about this - if you have access to call a virtual function, then virtual dispatch is used.
In your sample, you cannot use a Derived as if it was a Base anywhere else in the scope of main - so it makes sense that you can't do it in the catch either

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

A method which can only be invoked when referring to base class? C++

Say I have an abstract class
class NecessaryDanger
{
public:
virtual void doSomethingDangerous() =0;
}
and a class that is derived from this class:
class DoesOtherStuff : public NecessaryDanger
{
//stuff
void otherMethod();
void doSomethingDangerous();
}
is there a way I can only allow access of doSomethingDangerous() like
DoesOtherStuff d;
d = DoesOtherStuff();
d.otherMethod(); //OK
d.doSomethingDangerous(); //error
NecessaryDanger* n = &d;
n->doSomethingDangerous(); //OK
I am not very good at C++ yet, so the code above may not be quite right, but you maybe get the idea. I have a set of classes that need to have the ability to do "something dangerous" (in their own special way) that could cause problems if more than one object of these classes does this dangerous thing. I would like to have a manager class that has a NecessaryDanger pointer to only one object. If the method doSomethingDangerous could only be called by a NecessaryDanger object, then it would be more difficult for an accidental call to doSomethingDangerous to happen and cause me headaches down the road.
Thanks in advance for the help. Sorry in advance if this is a dumb question!
Sure. Just make it private in the derived class and public in the base.
Of course, if NecessaryDanger is a public base, then anyone can cast and call. You might want to make it a private base and use friend.
class DoesOtherStuff : private NecessaryDanger
{
//stuff
void otherMethod();
private:
void doSomethingDangerous();
friend class DangerManager;
}
Remove the virtual classifier in the superclass so that the compiler does compile-time binding based on the variable type instead of run-time binding based on the object type.
Building on Potatswatter's response :)
Here is Herb's advice: (especially 1 and 2) applicable in this context.
Guideline #1: Prefer to make
interfaces nonvirtual, using Template
Method.
Guideline #2: Prefer to make
virtual functions private.
Guideline #3: Only if derived classes need to invoke the base implementation of a
virtual function, make the virtual
function protected.
For the special case of the destructor
only:
Guideline #4: A base class destructor
should be either public and virtual,
or protected and nonvirtual.