A private inheritance in C++ [duplicate] - c++

This question already has answers here:
private inheritance
(6 answers)
Closed 9 years ago.
In C++: assume I have a class X. Is there any difference between private inheritance like this:
class Deriv : private X
{
public:
//constructor etc
void method()
{
usageOfMethodFromX();
}
};
and this:
class Deriv
{
private:
X * m_xinstance;
public:
//constructor etc
void method()
{
m_xinstance->usageOfMethodFromX();
}
};
Is there any difference that does not allow substitute private inheritance with having a member of derived class and vice versa? Is this the same?
Thanks!

There is a subtle difference in case your base class has a virtual function: even if the base class is inherited privately, it can be overridden:
#include <iostream>
class Base {
virtual int do_f() { return 1; }
public:
int f() { return this->do_f(); }
};
class Derived: Base {
int do_f() { return 2; }
public:
int g() { return this->f(); }
};
class Final: public Derived {
int do_f() { return 3; }
};
int main() {
Final final;
std::cout << final.g() << '\n';
}
The above code will print 3 (live example).
Another difference in your code is that the approach allocating memory, well, allocates memory on heap. You can avoid this heap allocation by embedding the object into your derived object.

There is a very significant and clear-cut difference: Consider this X:
class X {
protected:
void doSmth();
};
Only classes inheriting from X will have access to any and all protected members (here X::doSmth()).

Yes.
In the inheritance model, the lifetime of the two objects is intertwined. A number of methods are automatically connected by default (operator=, constructors, destructors) and others may be in the future (operator swap aka :=:, =default other operators like < or ==). On top of this, virtual method overriding and calling can route calls to pointers to your parent interface (which you can provide others, or can be invoked by calling your parent methods) back to you.
If you replace your X * m_xinstance with X m_xinstance things get closer to being the same. Lifetime is now tied, and many (all?) of the hooked up methods are now hooked up similarly. virtual behavior is also very different.
A final difference is that if your base class is empty, the empty base class optimization can occur in one case, but not the member instance. As different objects must have different addresses, a member of your class has a minimum size of 1, while an empty base class can take up zero memory.

Related

If base class pointer cannot access derived class member function, then what is so convenient about polymorphism?

To realize Polymorphism, we need to use a base class pointer to a derived class instance. Everything about polymorphism is good except, what if every derived class has one or several its own member function? If the base class pointer cannot access these derived class member function, then what is so convenient about polymorphism?
Below is an example. "shape" is a base class. "square" and "circle" are two derived classes.
class shape {
public:
virtual void getArea()=0;
};
class square: public shape {
private:
int edge;
public:
square(){edge = 1;}
virtual void getArea(){ //polymorphism
cout << edge*edge << "\n";
}
void getNumberOfEdge(){ //a new member function
cout << "4\n";
}
};
class circle: public shape {
private:
int radius;
public:
circle(){radius = 1;}
virtual void getArea(){ //polymorphism
cout << 3*radius*radius << "\n";
}
void getCurvature(){ //a new member function
cout << 1/radius << "\n";
}
};
int main(){
shape* arr[2] = {
new square(),
new circle()
};
arr[0]->getArea();
arr[1]->getArea();
arr[0]->getNumberOfEdge(); //compiler error
}
getArea() is a good example of realizing polymorphism. However accessing derived class member function gives me compiler error, which I understand why perfectly. But from a designing point of view, we do not want to add a bunch of virtual functions to the base class just for the sake of each derived class, right?
Functionality in the base class should be in the base class. Functionality that's specific to specific derived classes should be in those derived classes. The virtual functions let code manipulate shapes and perform operations that are valid for any shape without having to understand how to perform those functions on every possible type of shape that may exist now and in the future.
But from a designing point of view, we do not want to add a bunch of virtual functions to the base class just for the sake of each derived class, right?
If those operations make sense on the base class, then they should probably go there. If they are shape-specific, then they belong in the specific classes for which that functionality makes sense.
Say you have a system that uses shapes but has no derived class for octagon. The point of polymorphism is that code can be written today that will work perfectly on octagons later should someone add them.
With the proper types you can work the number of edge problems quite well, taking polymorphism to the edge!
Let's add a class:
// a base interface for all Edged shapes
struct HasEdges {
virtual void getNumberOfEdges() const = 0;
// side note: I'd prefer this getter to return an int
// but keeping it as in the example
};
Now for Square (but not for Circle!) we can do:
class Square: public Shape, public HasEdges {
// ...
public:
void getNumberOfEdges() const override { /* implement */ }
// ...
};
And the main would go like this:
int main(){
shape* arr[2] = {
new square(),
new circle()
};
arr[0]->getArea();
arr[1]->getArea();
// some edgy thing below
HasEdges* hasEdges = dynamic_cast<HasEdges*>(arr[0]);
// above returns null on failure
if(hasEdges) hasEdges->getNumberOfEdges();
// releasing memory...
}
Run-time Polymorphism means polymorphic behavior at run time.
The behavior defined by getArea() is changed at run time based on the instance it points to.
So, you are mixing with polymorphism with static compiling problem. Base class does not have a member function name getNumberOfEdge() and you get compiler error.
If you want to have specific implementation called, why not make compiler see it and cast it?
public:
virtual void getArea()=0;
template<typename T>
const T * get() {
return dynamic_cast<T *>(this);
}
};
Now you can cast it to whatever derived type:
auto square_instance = arr[0]->get<square>();
if (square_instance) {
square_instance->getNumberOfEdge();
}
A different approach to run time polymorphism is suggested by Sean Parent. I liked it and trying this approach more often now.

why constructor of base class invokes first? [duplicate]

This question already has answers here:
Order of calling constructors/destructors in inheritance
(6 answers)
Closed 5 years ago.
While running the code below, why is the constructor of the base class is derived first even if we first declare an object of derive class.
#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
~base()
{ cout<<"Destructing base \n"; }
};
class derived: public base {
public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};
int main(void)
{
derived *d = new derived(); //d is defined ahead of the base class object
base *b = d;
delete b;
return 0;
}
Inheritance expresses an "is-a" relationship, so that all objects of class derived ARE objects of class base. derived objects have all of the data and methods that base objects do, plus the data and methods explicitly declared in the derived class declaration.
It's perfectly possible (and common) to write Derived classes that depend on the implementation of their Base classes. For example, suppose that we have
class Base {
public:
Base() { n = 5; }
int GetN() const { return n; }
private:
int n;
};
class Derived : public Base {
public:
Derived() { m = GetN() * 2; }
int GetM() const { return m; }
private:
int m;
};
Now we'd expect
Derived* d = new Derived();
std::cout << d->GetM() << std::endl;
to print 10, which is exactly what it should do (barring any mistakes on my part). This is a totally reasonable (if a little contrived) thing to do.
The only way the language can get code like this to work properly is to run the Base constructor before the Derived constructor when constructing an object of type Derived. This is because the Derived constructor depends on being able to call the GetN() method, which it inherits from Base, the proper functioning of which depends on the data member n having been properly initialised in the Base constructor.
To summarise, when constructing any Derived object, C++ must construct it as a Base object first because Derived is-a Base and will generally depend on it's implementation and data.
When you do
base* b = d;
in your code, you're declaring a variable b that is of type "pointer to a base object" and then initialising this variable with the same memory address held in d. The compiler doesn't mind you doing this because all derived objects ARE base objects, so it makes sense that you might want to treat d as a b. Nothing actually happens to the object here though, it's simply a declaration and instantiation of a pointer variable. The object pointed to by d already was a base object, since all derived objects are base objects.
Note that this explanation is intentionally a little fuzzy round the edges and is nowhere near a full explanation of the relationship between base and derived classes in C++. You'll want to go looking in other articles/books/the standard for that. I hope this is relatively easy to understand for beginners though.

Why virtual functions defy access specifiers ? C++ [duplicate]

This question already has answers here:
Public virtual function derived private in C++
(3 answers)
Closed 6 years ago.
let's assume u have a class base and class A which inherits from base . base have a declaration of a pure virtual functions called getValue() which is public , and A contains the definition(implementation) of the functions which is set as private .
When trying to use the function getValue() from base reference or pointer (base& /base*) to an A object it access it even though it's declared as private
Because in C++, virtuality and access are orthogonal concerns. When the compiler sees a base* or base& and it needs to call getValue on it, then it's sufficient that the function is accessible in base.
The fact that A declares its (overriding) getValue as private is irrelevant. After all, how could it be relevant? When base.getValue() or base->getValue() is called, you don't know that you might be dealing with an A. That's the whole point of object-oriented programming in the first place!
This does not mean that it's good style to vary access specifiers within a class hierarchy, though, because it can be confusing. In fact, you should split your getValue into two different functions, one being virtual and the other one non-virtual.
Long story: C++ behaves very different from other popular programming languages here, because it actually allows and encourages private virtual functions. Virtual member functions should be private by default, and public member functions should be non-virtual by default, and call the private virtual ones if necessary. (The only exception is the destructor, of course.) Herb Sutter once called this the Non-Virtual Interface Idiom.
Example:
#include <iostream>
class Base
{
public:
virtual ~Base() {}
int getValue() const
{
int const value = doGetValue();
if (value < 0)
{
// error
}
return value;
}
private:
virtual int doGetValue() const = 0;
};
class A : public Base
{
private:
int doGetValue() const override
{
return 123;
}
};
int main()
{
Base* ptr = new A; // use std::unique_ptr in real code
std::cout << ptr->getValue() << "\n";
delete ptr;
}

Why private members get inherited?

So private members in the base class are also in the inherited class but not accessible in it, right?
Are they actually in the memory allocated to the the inherited object?
Are they actually in the memory allocated to the the inherited object?
Yes, they need to exist. The private members are part of the implementation detail of the base class. Without them, in general, the base class wouldn't be able to function (which is why they exist in the first place).
Making them private just allows the base class to create its implementation however it chooses, without exposing that to anybody, including the subclass.
Yes. Just for example, you can use a public function from the base class that manipulates private data, even in an instance of the derived class:
class Base {
int x;
public:
Base() : x(0) {}
void inc() { ++x; }
void show() { std::cout << x << "\n"; }
};
class Derived : public Base {
};
int main() {
Derived d;
d.show();
d.inc();
d.show();
}
With a properly functioning compiler, this must display:
0
1
...showing that the data in the Base object is present in the Derived object, even though it's not (directly) accessible.
Of course with almost anything in C++, there's the "as-if" rule -- if the compiler can determine that it can somehow produce the correct observable behavior for the program, even without including the private part(s) of the base class, then it's free to do so. The most obvious example of this would be if you included something (member function or data) in the base class that was simply never used in practice.
Yes they are,
When object of the derived class is being constructed all of its base classes are first being constructed as well.
Consider this example:
class Base
{
int x;
public:
Base(int px)
: x(px)
{
}
};
class Derived : public Base
{
int y;
public:
Derived(int px, int py)
: y(py), Base(px)
{
}
};
This example compiles and works and Base is initialized (constructor is called) before you reach the body of the Derived constructor.

How can I call a parent constructor after some processing?

I want to do some processing before the parent constructor is called. The following example shows why I want to do this despite the fact that I have made it slightly trivial for the sake of clarity. The real parent constructor is doing some rendering, but lets try and solve this problem first.
Essentially, the problem comes in when an overriden function is called by the parent constructor, but the child's data is not set up yet. How do I fix this?
class BaseClass {
public:
int myNumber;
BaseClass(){
myNumber = 0;
this->printNumber();
}
virtual void printNumber(){
printf("My number is %d\n", this->myNumber);
}
}
class ChildClass : BaseClass {
public:
float childNumber;
ChildClass(float myNumber) : BaseClass() {
this->childNumber = myNumber;
}
void printNumber(){
printf("My number is %f\n", this->childNumber);
}
}
the problem comes in when an overriden function is called by the parent constructor,
No, that never happens. Within the constructor of BaseClass its dynamic type is BaseClass as well, so the printNumber() call will resolve to its own number instead of some derived class. Why? Because at that time the constructors for ChildClass has not yet finished running and so it wasn't yet created.
As #FredLarson comments, here is more info on the subject: http://parashift.com/c++-faq/calling-virtuals-from-ctors.html
Like others said above, you shouldn't call a virtual member from a constructor. But to address your problem there is an idiom that might help you, it is called base-from-member:
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Base-from-Member
What it does basically, is take advantage of the fact that base classes are initialized in the order they are declared. You may be able to do what you need to do in a separate base class before your base class is initialized.
class OtherBaseClass {
int Num;
OtherBaseclass(float num) : Num(num)
{
printf("My number is %d\n", this->Num);
}
};
class ChildClass : OtherBaseClass, BaseClass {
public:
float childNumber;
ChildClass(float myNumber) : OtherBaseClass(myNumber), BaseClass() {
....
Note that the constructor of the base class cannot call to the virtual function version of the derived class, that is, your ChildClass::printNumber() function will not be called.
That said, if you want to execute something before the constructor of the base class, one way to do it is using yet another base class, and put it before the other one:
class RunMeFirst
{
public RunMeFirst()
{ printf("whatever...\n"); }
};
class ChildClass : private RunMeFirst, public BaseClass
{ /*...*/ };
Do you have to implement the rendering functionality in a base class? Could you instead employ composition instead of inheritance. Using composition would allow you to easily control the member initialization order, e.g.:
#include <iostream>
class renderer
{
public:
renderer(int number)
{
std::cout << "Number is " << number << std::endl;
}
};
class foo
{
public:
foo()
: number_(12)
, renderer_(number_)
{
}
private:
int number_;
renderer renderer_;
};
int main()
{
foo bar;
}
In general, prefer composition to inheritance. Also, the Liskov Substitution Principle may be of use here, too, from a design point of view.
There are several things that run before a base class' constructor:
Initialization of arguments
Virtual base classes' constructors
Other base classes declared earlier's constructors
One commonly used solution is called the "base from member idiom" and involves moving the member to a new base class that is constructed first.
Thanks to #K-ballo for pointing out the error and because of that I was able to restructure the code a bit to do what I wanted, but as this isnt a technical correct answer to the question either, Ill leave the correct answer as is.
class BaseClass {
public:
int myNumber;
BaseClass(bool initialize = true){
myNumber = 0;
if (initialize){
this->initialize();
}
}
void initialize(){
this->printNumber();
}
virtual void printNumber(){
printf("My number is %d\n", this->myNumber);
}
}
class ChildClass : BaseClass {
public:
float childNumber;
ChildClass(float myNumber) : BaseClass(false) {
this->childNumber = myNumber;
this->initialize();
}
void printNumber(){
printf("My number is %f\n", this->childNumber);
}
}