Hi, I'm writing some code to test how virtual inheritance behaves, my problem is that the virtual inheritance behaves like a "normal" public inheritance
non virtual inheritance -
http://ideone.com/2joewK
virtual inheritance -
http://ideone.com/WXTo2Z
as you can see the output is 1:1 the same, how is this possible ?
In my understanding virtual inheritance can be used to guide the construction of an object according to the inheritance itself, meaning that I'm surprised to see the call to the ctor and dtor of A when using virtual inheritance in the second example.
What I'm doing wrong and what are the practical aspect of virtual inheritance ?
I'm posting the same examples here
ctor_NON_virtual_inheritance.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
class A
{
std::string k;
int j;
public:
A() { std::cout << "ctor A" << std::endl;};
~A() { std::cout << "dtor A" << std::endl;};
};
class B : public A
{
public:
B() { std::cout << "ctor B" << std::endl;};
~B() {std::cout << "dtor B" << std::endl;};
};
int main()
{
{
std::cout << "building an A obj" << std::endl;
A a;
}
{
std::cout << "building a B obj" << std::endl;
B b;
}
return(0);
}
|
ctor_virtual_inheritance.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
class A
{
std::string k;
int j;
public:
A() { std::cout << "ctor A" << std::endl;};
~A() { std::cout << "dtor A" << std::endl;};
};
class B : public virtual A
{
public:
B() { std::cout << "ctor B" << std::endl;};
~B() {std::cout << "dtor B" << std::endl;};
};
int main()
{
{
std::cout << "building an A obj" << std::endl;
A a;
}
{
std::cout << "building a B obj" << std::endl;
B b;
}
return(0);
}
|
Thanks.