I got that subobjects are member subobjects, base class subobjects and arrays.
I couldn't find anything that explicit explain the two first terms. In the following code for example:
struct A{int a;};
struct B{int b;};
struct C:public A,public B{};
I think that: int a is a member subobject of a possible, not yet instantiated, object of type A; int a is a base class subobject of a possible, not yet instantiated, object of type C. Is it Right? What is the definition of member subobject and base class subobject? Could you provide examples?
Whenever a class inherits from another one it inherits, too, an instance of that class:
class A { };
class B : A { };
Then class B internally looks like:
class B
{
A a; // <- implicit base class sub-object, not visible to you
};
Note that in some cases there might be even be more than one A!
class A { };
class B : A { };
class C : A { };
class D : C, B { };
D then internally looks like:
class D
{
B b; // { A a; }
C c; // { A a; }
};
with b and c being the base class sub-objects; or in a flattened representation:
class D
{
A aFromB; // inherited from B, but not a sub-object of D itself
// other members of B
A aFromC; // inherited from C, again not a sub-object of D
// other members of C
};
B and C base class sub-objects are not visible in this representation, still they are there in form of the respective A instance combined with the respective other members (think of having braces around).
If you want to avoid duplicates of A, you need to inherit virtually: class B : virtual A { } – all virtually inherited (directly or indirectly) instances of A are then combined into one single instance (though if there are non-virtually inherited ones these remain in parallel to the combined one), consider:
class A { };
class B : A { };
class C : virtual A { };
class D : virtual A { };
class E : A, B, C
{
A combinedAFromCAndD;
// other members of B
// other members of C
A separateAFromD
// other members of D
};
Note: These layouts above are just examples, concrete layouts might vary.
In your code, the base class subobjects of instances of C are the instances of A and B contained inside it. Each of those subobjects has a subobject itself (a and b); those are not considered subobjects of the instance of C (because they're subobjects of subobjects), but are considered "nested objects" of the instance of C.
Related
Consider:
#include <iostream>
using namespace std;
class A {// base class
private:
int data;
public:
A(int data = 0)
{
this->data = data;
}
void show()
{
cout << data << endl;
return;
}
};
class B : virtual public A {
public:
B(int data = 0) :
A(data) {
}
};
class C : virtual public A {
public:
C(int data = 0) :
A(data) {
}
};
class D : public B, public C {
public:
D(int dataB = 0, int dataC = 0) :
B(dataB),
C(dataC) {
}
};
int main() {
D d(1, 2);
d.B::show();
d.C::show();
return 0;
}
The above code is the diamond class inheritance diagram. The base class is A. I use virtual inheritance to avoid the diamond problem. But why is the output of this program 0,0, not 1,2 as I expect?
B's constructor is passed data=1, and in its initializer list it calls A with data. C's constructor similar is passed data=2 and its initializer list it calls A with data.
We then ask the B and C subobjects to show their value. And we get 0 0 not 1 2 as I expect.
When you have this scheme with virtual inheritance, it is up to the most derived class in the hierarchy (in this case D) to call the constructor of the common base (A)1,2.
Since your constructor for A has a default parameter data = 0, it can be used as a default constructor. And this is what's happening, the common A sub-object gets default constructed, since you omitted it from D's member initialization list.
If you remove the default value for data, you'll get a nice compiler error for emphasis:
A(int data)
{
this->data = data;
}
On g++ it results with:
main.cpp: In constructor 'D::D(int, int)':
main.cpp:37:16: error: no matching function for call to 'A::A()'
C(dataC) {
1 Remember that with virtual inheritance there is only one sub-object of type A. And both the B and C sub-objects refer to it. It is impossible for your calls to show to print different things, since they access the same data. That is why it's up to the most derived class, so there is no ambiguity.
[class.mi/4]
A base class specifier that does not contain the keyword virtual specifies a non-virtual base class. A base class specifier that contains the keyword virtual specifies a virtual base class. For each distinct occurrence of a non-virtual base class in the class lattice of the most derived class, the most derived object shall contain a corresponding distinct base class subobject of that type. For each distinct base class that is specified virtual, the most derived object shall contain a single base class subobject of that type.
[class.base.init/13.1]
In a non-delegating constructor, initialization proceeds in the following order:
First, and only for the constructor of the most derived class, virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
...
2 So if you want to construct A with specific data you'd define D::D() like this instead:
D(int dataA = 0) :
A(dataA) {
}
When you have virtual inheritance, the virtual base class is initialized by the constructor of the most derived class.
D(int dataB = 0, int dataC = 0) :
B(dataB),
C(dataC) {}
is equivalent to:
D(int dataB = 0, int dataC = 0) :
A(),
B(dataB),
C(dataC) {}
which is, in your case, the same as
D(int dataB = 0, int dataC = 0) :
A(0),
B(dataB),
C(dataC) {}
Unless you construct an instance of B,
B(int data = 0) :
A(data) {
}
is the same as
B(int data = 0) {}
with no code to initialize A since A is already initialized in the constructor of D.
Same thing applies to the implementation of C::C(int data).
That explains the output you are seeing.
I think you misunderstood the concept of virtual inheritance and the 'diamond problem'. With virtual inheritance, you create a diamond inheritance pattern, but from your post, it appears that you want to avoid that and instead have two bases A, one from B and another from C. To obtain that, simply avoid virtual inheritance in B and C, when your code will write 1 2.
Incidently, if only B has virtual inheritance from A but C conventional inheritance from A, then D will have two bases A, but that from B is again default initialised (as explained in the other answers).
Say I have several classes that inherit like so.
#include <iostream>
struct A {
A() {std::cout << "a";}
};
struct B : A {};
struct C : A {};
struct D : B, C {};
int main {
D d;
}
On executing the program, as expected, I see two A objects were constructed, one for the B and one for the C object that are constructed when creating a D object. Whoever, how can I not create two A objects? I want the same A object to be used to create B and C objects. Is this possible?
If B and C both use virtual inheritance for A, then there will only be a single base class object for each D object:
struct B : virtual A {};
struct C : virtual A {};
//...
D d; //prints "a" rather than "aa"
Live demo
If you're looking for a non-polymorphic solution, you're out of luck. Otherwise, change to the following:
struct B : virtual A {};
struct C : virtual A {};
As written, every D object has two sub-objects of type A, one inherited from class B and one inherited from class C. So the constructor of A must run twice, once for each sub-object.
If the original design is wrong, and there should only be one A sub-object, despite the use of two bases B and C, the change is to make A a virtual base of B and a virtual base of C. That way there will only be one A sub-object in a D object, and the constructor of A will only run once when a D object is constructed.
This question already has answers here:
In C++, what is a virtual base class?
(11 answers)
Closed 8 years ago.
I'm trying to understand what exactly purpose of a virtual specifier in base class. As said in the c++14 working draft we have:
For each distinct base class that is specified virtual, the most
derived object shall contain a single base class subobject of that
type.
From this quote I'm assume that if we create an instance c of class C which is a derived class for A and B we're create an objects of A and B implicitly.
Question: How can I access to an instances of a base classes via an instance of derived class?
An object of class struct C : A, B {}; contains two base subobjects, one of type A and one of type B. You can access them "directly":
void foo(A &);
void bar(B &);
C c;
foo(c); // accesses the A-subobject
bar(c); // accesses the B-subobject
You can also say static_cast<A&>(c) and static_cast<B&>(c) explicitly, though this is not often needed. You sometimes need to disambiguate names, though:
struct A { void f(); };
struct B { void f(); };
struct C : A, B { void f(); };
C c;
c.f(); // calls the member "f" of C
c.A::f(); // calls the member "f" of the A-base subobject of c
c.B::f(); // calls the member "f" of the B-base subobject of c
All this is not really related to the concept of virtual inheritance, which says that there is only relevant base subobject, even if it is referred to through multiple distinct inheritances:
struct V {};
struct A : virtual V {};
struct B : virtual V {};
struct C : A, B {};
In this last example, an object C c has only one base subobject of type V, not two, and the V-base subobjects of the A- and B-base subobjects of c see the same V base subobject. The virtual base is "shared" across the inheritance hierarchy.
virtual specifier is not related to accessing base sub-object, rather number of base sub-object in derived object. You can access base sub-object even if the base is not virtual. virtual is here to solve other problems like diamond inheritance problem
I understand the concept of virtual inheritance, but I couldn't find the answer to this anywhere. Say you have class D which inherits class B and C. Both B and C inherit class A. So you could make B and C virtually inherit A to avoid two instances of A. But do you have to specify virtual inheritance at both B and C or does it already create only one instance of A if one of the two virtually inherits A and the other doesn't?
Thanks
They must all be virtual. From C++11 10.1 [class.mi]/7:
A class can have both virtual and non-virtual base classes of a given type.
class B { /* ... */ };
class X : virtual public B { /* ... */ };
class Y : virtual public B { /* ... */ };
class Z : public B { /* ... */ };
class AA : public X, public Y, public Z { /* ... */ };
For an object of class AA, all virtual occurrences of base class B in the class lattice of AA correspond to a single B subobject within the object of type AA, and every other occurrence of a (non-virtual) base class B in the class lattice of AA corresponds one-to-one with a distinct B subobject within the object of type AA. Given the class AA defined above, class AA has two subobjects of class B: Z’s B and the virtual B shared by X and Y, as shown below.
You need to specify virtual inheritance for both B and C to have one A. Otherwise the class that is not using virtual inheritance will "share" class A.
This can enable one to have the following:
Why you want to do this is another matter.
http://en.wikipedia.org/wiki/Diamond_problem
I know what it means, but what steps can I take to avoid it?
A practical example:
class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};
Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.
To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue:
class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
virtual inheritance. That's what it's there for.
I'd stick to using multiple inheritance of interfaces only. While multiple inheritance of classes is attractive sometimes, it can also be confusing and painful if you rely on it regularly.
Inheritance is a strong, strong weapon. Use it only when you really need it. In the past, diamond inheritance was a sign that I was going to far with classification, saying that a user is an "employee" but they are also a "widget listener", but also a ...
In these cases, it's easy to hit multiple inheritance issues.
I solved them by using composition and pointers back to the owner:
Before:
class Employee : public WidgetListener, public LectureAttendee
{
public:
Employee(int x, int y)
WidgetListener(x), LectureAttendee(y)
{}
};
After:
class Employee
{
public:
Employee(int x, int y)
: listener(this, x), attendee(this, y)
{}
WidgetListener listener;
LectureAttendee attendee;
};
Yes, access rights are different, but if you can get away with such an approach, without duplicating code, it's better because it's less powerful. (You can save the power for when you have no alternative.)
class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};
In this the attributes of Class A repeated twice in Class D which makes more memory usage... So to save memory we make a virtual attribute for all inherited attributes of class A which are stored in a Vtable.
Well, the great thing about the Dreaded Diamond is that it's an error when it occurs. The best way to avoid is to figure out your inheritance structure beforehand. For instance, one project I work on has Viewers and Editors. Editors are logical subclasses of Viewers, but since all Viewers are subclasses - TextViewer, ImageViewer, etc., Editor does not derive from Viewer, thus allowing the final TextEditor, ImageEditor classes to avoid the diamond.
In cases where the diamond is not avoidable, using virtual inheritance. The biggest caveat, however, with virtual bases, is that the constructor for the virtual base must be called by the most derived class, meaning that a class that derives virtually has no control over the constructor parameters. Also, the presence of a virtual base tends to incur a performance/space penalty on casting through the chain, though I don't believe there is much of a penalty for more beyond the first.
Plus, you can always use the diamond if you are explicit about which base you want to use. Sometimes it's the only way.
I would suggest a better class design. I'm sure there are some problems that are solved best through multiple inheritance, but check to see if there is another way first.
If not, use virtual functions/interfaces.
Use inheritance by delegation. Then both classes will point to a base A, but have to implement methods that redirect to A. It has the side effect of turning protected members of A into "private" members in B,C, and D, but now you don't need virtual, and you don't have a diamond.
This is all I have in my notes about this topic. I think this would help you.
The diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a member in A that B and C, and D does not override it, then which member does D inherit: that of B, or that of C?
struct A { int a; };
struct B : A { int b; };
struct C : A { int c; };
struct D : B, C {};
D d;
d.a = 10; //error: ambiguous request for 'a'
In the above example, both B & C inherit A, and they both have a single copy of A. However D inherits both B & C, therefore D has two copies of A, one from B and another from C. If we need to access the data member an of A through the object of D, we must specify the path from which the member will be accessed: whether it is from B or C because most compilers can’t differentiate between two copies of A in D.
There are 4 ways to avoid this ambiguity:
1- Using the scope resolution operator we can manually specify the path from which a data member will be accessed, but note that, still there are two copies (two separate subjects) of A in D, so there is still a problem.
d.B::a = 10; // OK
d.C::a = 100; // OK
d.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a
2- Using static_cast we can specify which path the compiler can take to reach to data member, but note that, still there are two copies (two separate suobjects) of A in D, so there is still a problem.
static_cast<B&>(static_cast<D&>(d)).a = 10;
static_cast<C&>(static_cast<D&>(d)).a = 100;
d.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a
3- Using overridden, the ambiguous class can overriden the member, but note that, still there are two copies (two separate suobjects) of A in D, so there is still a problem.
struct A { int a; };
struct B : A { int b; };
struct C : A { int c; };
struct D : B, C { int a; };
D d;
d.a = 10; // OK: D::a = 10
d.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a
3- Using virtual inheritance, the problem is completely solved: If the inheritance from A to B and the inheritance from A to C are both marked "virtual", C++ takes special care to create only one A subobject,
struct A { int a; };
struct B : virtual A { int b; };
struct C : virtual A { int c; };
struct D : B, C {};
D d;
d.a = 10; // OK: D has only one copy of A - D::a = 10
d.A::a = 20; // OK: D::a = 20
Note that "both" B and C have to be virtual, otherwise if one of them is non-virtual, D would have a virtual A subobject and another non-virtual A subobject, and ambiguity will be still taken place even if class D itself is virtual. For example, class D is ambiguous in all of the following:
struct A { int a; };
struct B : A { int b; };
struct C : virtual A { int c; };
struct D : B, C {};
Or
struct A { int a; };
struct B : virtual A { int b; };
struct C : A { int c; };
struct D : B, C {};
Or
struct A { int a; };
struct B : A { int b; };
struct C : virtual A { int c; };
struct D : virtual B, C {};
Or
struct A { int a; };
struct B : virtual A { int b; };
struct C : A { int c; };
struct D : virtual B, C {};