I have the following code snippet, and I want to know that which path do c++ compiler choses to inherit the member.
class B
{
public:
void display()
{
cout << "B";
}
};
class B1 : virtual public B
{
};
class B2 : virtual public B
{
};
class C : public B1, public B2
{
};
int main()
{
C c;
c.display();
getchar();
return 0;
}
Is it really possible to have the path chosen by the compiler and if there is then please tell. Might be a basic question but please take some time for it. Thanks in advance.
It's not chosen by the compiler, it's defined by the language. B is virtual, so C has exactly one B base class. Its base classes will be constructed in the order B, B1, B2.
Related
This is the code I got from the internet...
and how virtual keyword is working?
i think this virtual keyword has something to do with this behaviour but I don't understand what it is.
class A {
int x;
public:
A(int i) { x = i; }
void print() { cout << x; }
};
class B : virtual public A {
public:
B()
: A(10)
{
}
};
class C : virtual public A {
public:
C()
: A(10)
{
}
};
class D : public B, public C {
};
int main()
{
D d;
d.print();
return 0;
}
why am I able to call grandparent method with grandchild object?
Because that is how inheritance works. That member function was inherited by the child class and the grand child.
I read that it was not possible
Either what you read is wrong or you misunderstood it.
how virtual keyword is working?
When a virtual base occurs multiple times in a hierarchy, those occurrences are combined into a single base sub object.
In the case of D, the base A of B and the base A of C are the same base which would not be the case if the inheritance wasn't virtual.
You can be right in your assumption, but it is not that easy.
print is declared as a public member function. Since you derive every class with public, you still can call print from your D class object.
If you desire your described behaviour, one way is, you have to rewrite your class
class A {
int x;
public:
A(int i) { x = i; }
private:
void print() { cout << x; }
};
You should study the topic of 'inheritance'. You can start with that ARTICLE.
In general a diamond class structure points to bad software design. Yeah there may be some good reasons to create something like that. But judging the type of the question, you should really forget about that and avoid it. Unless you are really sure about what you are doing.
The structure you found is described here.
I am trying to understand better the concept of virtual inheritance, and what are its perils.
I read in another post (Why is Default constructor called in virtual inheritance?) that it (= virtual inheritance) changes the order of constructor call (the "grandmother" is called first, while without virtual inheritance it doesn't).
So I tried the following to see that I got the idea (VS2013):
#define tracefunc printf(__FUNCTION__); printf("\r\n")
struct A
{
A(){ tracefunc; }
};
struct B1 : public A
{
B1(){ tracefunc; };
};
struct B2 : virtual public A
{
B2() { tracefunc; };
};
struct C1 : public B1
{
C1() { tracefunc; };
};
struct C2 : virtual public B2
{
C2() { tracefunc; };
};
int _tmain(int argc, _TCHAR* argv[])
{
A* pa1 = new C1();
A* pa2 = new C2();
}
The output is:
A::A
B1::B1
C1::C1
A::A
B2::B2
C2::C2
Which is not what I expected (I expected the order of the 2 classes will be different).
What am I missing? Can someone explain or direct me to a source that explains it better?
Thanks!
In your example, your output is to be expected. Virtual inheritance comes into play in the instance when you have a class with multiple inheritance who's parent classes also inherit from the same class/type (i.e. the "diamond problem"). In your example, your classes might be set up to virtually inherit (if needed elsewhere in the code), but they don't necessarily 'virtually inherit' based on your example since none of the derived classes (B1/B2/C1/C2) do more than inherit directly from A.
To expand, I've tweaked your example to explain a little more:
#include <cstdio>
#define tracefunc printf(__FUNCTION__); printf("\r\n")
struct A
{
A() { tracefunc; }
virtual void write() { tracefunc; }
virtual void read() { tracefunc; }
};
struct B1 : public A
{
B1() { tracefunc; };
void read(){ tracefunc; }
};
struct C1 : public A
{
C1() { tracefunc; };
void write(){ tracefunc; }
};
struct B2 : virtual public A
{
B2() { tracefunc; };
void read(){ tracefunc; }
};
struct C2 : virtual public A
{
C2() { tracefunc; };
void write(){ tracefunc; }
};
// Z1 inherits from B1 and C1, both of which inherit from A; when a call is made to any
// of the base function (i.e. A::read or A::write) from the derived class, the call is
// ambiguous since B1 and C1 both have a 'copy' (i.e. vtable) for the A parent class.
struct Z1 : public B1, public C1
{
Z1() { tracefunc; }
};
// Z2 inherits from B2 and C2, both of which inherit from A virtually; note that Z2 doesn't
// need to inherit virtually from B2 or C2. Since B2 and C2 both virtual inherit from A, when
// they are constructed, only 1 copy of the base A class is made and the vtable pointer info
// is "shared" between the 2 base objects (B2 and C2), and the calls are no longer ambiguous
struct Z2 : public B2, public C2
{
Z2() { tracefunc; }
};
int _tmain(int argc, _TCHAR* argv[])
{
// gets 2 "copies" of the 'A' base since 'B1' and 'C1' don't virtually inherit from 'A'
Z1 z1;
// gets only 1 "copy" of 'A' base since 'B2' and 'C2' virtualy inherit from 'A' and thus "share" the vtable pointer to the 'A' base
Z2 z2;
z1.write(); // ambiguous call to write (which one is it .. B1::write() (since B1 inherits from A) or A::write() ?)
z1.read(); // ambiguous call to read (which one is it .. C1::read() (since C1 inherits from A) or A::read() ?)
z2.write(); // not ambiguous: z2.write() calls C2::write() since it's "virtually mapped" to/from A::write()
z2.read(); // not ambiguous: z2.read() calls B2::read() since it's "virtually mapped" to/from A::read()
return 0;
}
While it might be "obvious" to us humans which call we intend to make in the case of the z1 variable, since B1 doesn't have a write method, I would "expect" the compiler to choose the C1::write method, but due to how the memory mapping of objects work, it presents a problem since the base copy of A in the C1 object might have different information (pointers/references/handles) than the copy of the A base in the B1 object (since there's technically 2 copies of the A base); thus a call to B1::read() { this->write(); } could give unexpected behaviour (though not undefined).
The virtual keyword on a base class specifier makes it explicit that other classes that virtually inherit from the same base type, shall only get 1 copy of the base type.
Note that the above code should fail to compile with compiler errors explaining the ambiguous calls for the z1 object. If you comment out the z1.write(); and z1.read(); lines the output (for me at least) is the following:
A::A
B1::B1
A::A
C1::C1
Z1::Z1
A::A
B2::B2
C2::C2
Z2::Z2
C2::write
B2::read
Note the 2 calls to the A ctor (A::A) before Z1 is constructed, while Z2 only has 1 call to the A constructor.
I recommend reading the following on virtual inheritance as it goes more in depth on some of the other pitfalls to take note of (like the fact that virtually inherited classes need to use the initialization list to make base class ctor calls, or that you should avoid using C-style casts when doing such a type of inheritance).
It also explains a little more to what you were initially alluding to with the constructor/destructor ordering, and more specifically how the ordering is done when using multiple virtual inheritance.
Hope that can help clear things up a bit.
The output of compiler is right. In fact, this is about the goal of virtual inheritance. Virtual inheritance is aimed to solve the 'Diamond problem' in the multiple inheritance. For example, B inherits from A, C inherits from A and D inherits from B, C. The diagram is like this:
A
| |
B C
| |
D
So, D has two instances A from B and C. If A has virtual functions, there is a problem.
For example:
struct A
{
virtual void foo(){__builtin_printf("A");}
virtual void bar(){}
};
struct B : A
{
virtual void foo(){__builtin_printf("B");}
};
struct C : A
{
virtual void bar(){}
};
struct D : B, C
{
};
int main()
{
D d;
d.foo(); // Error
}
If I use my xlC compiler to compile and run:
xlC -+ a.C
The error message is like that:
a.C:25:7: error: member 'foo' found in multiple base classes of different types
d.foo(); // Error
^
a.C:9:18: note: member found by ambiguous name lookup
virtual void foo(){__builtin_printf("B");}
^
a.C:3:18: note: member found by ambiguous name lookup
virtual void foo(){__builtin_printf("A");}
^
1 error generated.
Error while processing a.C.
The error message is very clear, member 'foo' found in multiple base classes of different types. If we add virtual inheritance, the problem is solved. Because the construction rights of A is handled by D, there is one instance of A.
Back to your code, the inheritance diagram is like this:
A A
| |
B1 B2
| |
C1 C2
There is no 'diamond problem', this is only single inheritance. So, the construction order is also A->B2->C2, there is no difference of output.
You won't be able to see any difference in the output because the output will be same in any of the following class hiearchies:
Hiearchy 1
class A {};
class B2 : virtual public A {};
class C2 : virtual public B2 {};
Hiearchy 2
class A {};
class B2 : public A {};
class C2 : virtual public B2 {};
Hiearchy 3
class A {};
class B2 : virtual public A {};
class C2 : public B2 {};
Hiearchy 3
class A {};
class B2 : public A {};
class C2 : public B2 {};
In all these case, A::A() will be executed first, followed by B2::B2(), and then C2::C2().
The difference between them is when does A::A() get called. Does it get called from B2::B2(), or C2::C2()?
I am not 100% clear on the answer for Hiearchy 1. I think B2::B2() should get called from C2::C2 since B2 is a virtual base class of C. A::A() should get called from B2:B2() since A is a virtual base class of B2. But I could be wrong on the exact order.
In Hierarchy 2, A::A() will be called from B2::B2(). Since B2 is the virtual base class of C2, B2::B2() gets called from C2::C2(). Since A is a normal base class of B2, A::A() gets called from B2::B2().
In Hierarchy 2, A::A() will be called from C2::C2(). Since A is a virtual base class, A::A() gets called from C2::C2(). B2::B2() gets called after the call to A::A() is completed.
In Hierarchy 4, A::A() will be called from B2::B2(). I think this case needs no explanation.
To clarify my doubt regarding Hiearchy 1, I used the following program:
#include <iostream>
class A
{
public:
A(char const *from) { std::cout << "Called from : " << from << std::endl; }
};
class B2 : virtual public A
{
public:
B2() : A("B2::B2()") {}
};
class C2 : virtual public B2
{
public:
C2() : A("C2::C2()") {}
};
int main()
{
C2 c;
}
I got the following output:
Called from : C2::C2()
This confirms what #T.C indicated in his comment, which is different from what I had expected. A::A() gets called from C2::C2, not from B2::B2.
I have a base class B and 2 derived classes D1, D2.
class B {
int commonFunc();
virtual int specifyFunc();
}
class D1 : public B {
int specifyFunc();
}
class D2 : public B {
int specifyFunc();
}
Now I meet a requirement that i need to extend my base class function commonFunc(). Since i don't want to modify existing code in base class, i derived another class like:
class B {
virtual int commonFunc(); // Change to virtual
virtual int specifyFunc();
}
class B2 : public B {
int commonFunc(); // A new commonFunc() to meet new requirement
}
However, D1 and D2 cannot use the new commonFunc() in B2 except I modify the inheritance hierarchy.
Here is a possible solution i figured out
class B {
virtual int commonFunc();
virtual int specifyFunc();
}
class D1 : public B {
int specifyFunc();
}
class D2 : public B {
int specifyFunc();
}
class NewD1 : public D1 {
int commonFunc(); // Overrided commonFunc() in base class
}
class NewD2 : public D2 {
int commonFunc(); // Overrided commonFunc() in base class
}
Since the commonFunc() in NewD1 and NewD2 are exactly the same, this solution involves a poor code-copy
I am looking for any design pattern or solution which can dynamically extend base class without much modification to existing class.
You have several solutions. Inheritance should only be used to factorize code for classes having the same responsability. This means that your class Car shouldn't inherit from a class Logger because you want some logging capabilities. This will determine which solution to choose.
1. D1 and D2 have the same responsability than B
Then a good way to have a more modular inheritance is the pattern decorator. This would allow you to do what you want. Just a little code to have an idea:
class B {
virtual int commonFunc();
virtual int specifyFunc();
}
class BDecorator: public B {
B parent;
B(B&);
virtual int commonFunc(); // Implementation forward to parent.
virtual int specifyFunc(); // Implementation forward to parent.
}
class B2: public BDecorator {
int commonFunc();
int specifyFunc();
}
class D1 : public BDecorator {
int specifyFunc();
}
class D2 : public BDecorator {
int specifyFunc();
}
// Use:
B b();
B2 b2(b);
D1 d1(b2);
2. D1 and D2 have not the same responsability than B
Then you should use composition instead of inheritance. This means that you should define a pure abstract class D (an interface) and make D1 and D2 inherit from it. Then, in the constructor of B, you can inject a D. (Yes in this solution, you have to change B a little, tell me if this is really a problem.)
class B {
D d;
int commonFunc();
virtual int specifyFunc(); // Do something with d.
B(D);
}
class D {
virtual int func();
}
class D1 : public D {
int func();
}
class D2 : public D {
int func();
}
// Use with B, but you can use B2 (inheriting from B) instead:
D1 d1();
B b1(d1);
D2 d2();
B b2(d2);
I apologize for my old C++.
Interface Design (Program to an interface, not an implementation)
You could avoid such implementation dependencies by using a common interface (pure abstract class) IB.
You could change behavior (commonFunc())
by adding new classes (NewB) without changing existing classes.
Clients refer to the common interface and are independent of an implementation.
Decorator Design
If you can't do that or really want do extend the behavior of an object dynamically
at run-time, Decorator may help.
But Decorator can only add behavior before and/or after performing the old behavior.
See the following UML diagrams (if you aren't sure how to implement, please let me know).
For further discussion see the GoF Design Patterns Memory for learning
object-oriented design & programming / Decorator / Design Principles (Interface Design)
at http://w3sdesign.com.
I have a diamond problem which look like this:
__ A
/ |\
| B | \
v|/v v\|v \v
B2 B3 C
\v /v /
B4 /
\ /
D
I tried many way to make the best virtual inheritance to get no duplicates but I couldn't find a solution. The class A contains a position. Here's a sample output:
Call: A() position pointer is: 0x2203be8
Call: B()
Call: B2() position pointer is: 0x2203be8
Call: B3() position pointer is: 0x2203be8
Call: C() position pointer is: 0x2203a28
Call: B4() position pointer is: 0x2203be8
Call: D() position pointer is: 0x2203a28
Why does D and C don't have the same pointer for position? Why there's no constructor for this A::position? What virtual inheritance should I make to solve this? Thanks.
EDIT:
Here's a code sample:
class A;
class B;
class B2 : public virtual B, public virtual A;
class B3 : public virtual B, public virtual A;
class C : public virtual A;
class B4 : public virtual B2, public virtual B3;
class D : public B4, public C;
EDIT 2:
To make the output, I put this code inside each constructors:
A::A()
{
std::cerr << "Call: A() position pointer is: " << &_position << std::endl;
}
Since you say the below code, which works on the implementations I have, is broken for you then obviously the code isn't the problem. The problem is with something else in your set up; perhaps a compiler bug. You should narrow down what else could be the cause of the problem; since the code itself is ruled out as a problem perhaps the best next step is to update your compiler.
In any case that makes this question rather specific to your set up. If you do find a solution that might apply to other people then you should come back and post it. Until then I'm voting to close this question.
I'm trying to reproduce your issue. Here's the code I'm using:
#include <iostream>
struct A { int a; };
struct B { int b; };
struct B2 : virtual B, virtual A {};
struct B3 : virtual B, virtual A {};
struct B4 : virtual B2, virtual B3 {}; // these virtuals are unnecessary in this case...
struct C : virtual A {};
struct D : B4, C {};
int main() {
D d;
std::cout << &((B4*)&d)->a << '\n';
std::cout << &((B3*)(B4*)&d)->a << '\n';
std::cout << &((B2*)(B4*)&d)->a << '\n';
std::cout << &((A*)(B2*)(B4*)&d)->a << '\n';
std::cout << &((A*)(B3*)(B4*)&d)->a << '\n';
std::cout << &((C*)&d)->a << '\n';
std::cout << &((A*)(C*)&d)->a << '\n';
}
But the results I get are as expected, where the a member is the same for every object. I get the same results if I use print the addresses out in the constructors as well: http://ideone.com/8FdQ1O
If I make a slight change and remove the virtual keyword from C's definition:
...
struct C : A {};
...
(version using constructors)
then I do see the problem you describe where C has it's own A sub-object different from the virtual one used by B2, B3, and B4.
Are you sure you're using the virtual keyword in all the places you need it? The results you show seem to indicate you're missing it somewhere. Also I note that the output you show does not reflect the same order of constructors as the code fragments you show; the output shows A() first, but the code indicates that B() should be executed first.
The way virtual inheritance works is that a most derived type will contain a single virtual sub-object for each type that is virtually inherited anywhere in the inheritance tree. Additionally the most derived type will contain a sub-object for each instance of non-virtual inheritance:
struct A {};
struct B : virtual A {};
struct C : A, B {};
struct D : virtual A, C {};
struct E : A, D {};
struct F : virtual A, E {};
struct G : A, F {};
G g;
g contains a total of four A sub objects; one for each time A is non-virtually inherited (in C, E, and G), and once for all of the times A is virtually inherited (in B, D, and F).
What code do you currently have? It looks like the solution is going to be:
class D;
class C : public virtual D;
class B4 : public virtual D;
class B2 : public virtual B4;
class B3 : public virtual B4;
class B : public B2, public B3;
class A : public B2, public B3, public C;
based on your diagram. If I'm reading it wrong and A is the base, not D. Then it would need to look like this:
class A;
class B;
class B2 : public virtual B, public virtual A;
class B3 : public virtual B, public virtual A;
class C : public virtual A;
class B4 : public virtual B2, public virtual B3;
class D : public B4, public C;
Why does D and C don't have the same pointer for position?
Because you are non-virtually inheriting D from B4 and C. That means you have two copies of A (and two pointers).
In D constructor &B4::position is different from &C::position
Why there's no constructor for this A::position?
No idea, any chances that your A class has more than one constructor, and that a default-silent constructor is called by C::C()?
What virtual inheritance should I make to solve this?
Make all virtual. That means that you need to explicitly call every constructor from D::D() (i.e. A::A(),B::B(),B2::B2(),B3::B3(),C::C() ).
Tbh I believe you should reconsider your hierarchy. I don't know the details, but it seems that your problem has a cleaner solution via component-design.
I am trying to figure out an interesting multiple inheritance issue.
The grandparent is an interface class with multiple methods:
class A
{
public:
virtual int foo() = 0;
virtual int bar() = 0;
};
Then there are abstract classes that are partially completing this interface.
class B : public A
{
public:
int foo() { return 0;}
};
class C : public A
{
public:
int bar() { return 1;}
};
The class I want to use inherits from both of the parents and specifies what method should come from where via using directives:
class D : public B, public C
{
public:
using B::foo;
using C::bar;
};
When I try to instantiate a D I get errors for trying to instantiate an abstract class.
int main()
{
D d; //<-- Error cannot instantiate abstract class.
int test = d.foo();
int test2 = d.bar();
return 0;
}
Can someone help me understand the problem and how to best make use of partial implementations?
You don't have diamond inheritance. The B and C base classes of D each have their own A base class subobject because they do not inherit virtually from A.
So, in D, there are really four pure virtual member functions that need to be implemented: the A::foo and A::bar from B and the A::foo and A::bar from C.
You probably want to use virtual inheritance. The class declarations and base class lists would look like so:
class A
class B : public virtual A
class C : public virtual A
class D : public B, public C
If you don't want to use virtual inheritance then you need to override the other two pure virtual functions in D:
class D : public B, public C
{
public:
using B::foo;
using C::bar;
int B::bar() { return 0; }
int C::foo() { return 0; }
};
You need to make your base classes virtual in order for them to inherit properly. The general rule is that all non-private member functions and base classes should be virtual UNLESS you know what you're doing and want to disable normal inheritance for that member/base.