Wednesday, August 29, 2007

VIRTUAL INHERITANCE


Example using source-code

#include
using namespace std;

class A
{
public:
A()
{
cout<<"\n A() ";
}
~A()
{
cout<<"\n ~A() ";
}
void f()
{
cout<<"\n A::f() ";
}

};

class B:public virtual A
{
public:
B()
{
cout<<"\n B() ";
}
~B()
{
cout<<"\n ~B() ";
}

void f()
{
cout<<"\n B::f() ";
}

};

class C:public virtual A
{
public:
C()
{
cout<<"\n C() ";
}
~C()
{
cout<<"\n ~C() ";
}

void f()
{
cout<<"\n C::f() ";
}

};



class D:public C,public B
{
public:
D()
{
cout<<"\n D() ";
}
~D()
{
cout<<"\n ~D() ";
}

};



class X
{
public:
X()
{
cout<<"\n X() ";
}
~X()
{
cout<<"\n ~X() ";
}

};



class E:public X,public B,public C
{
public:
E()
{
cout<<"\n E() ";
}
~E()
{
cout<<"\n ~E() ";
}
};



class M:public B
{
public:
M()
{
cout<<"\n M() ";
}
~M()
{
cout<<"\n ~M() ";
}
};



// error C2584: 'N' : direct base 'A' is inaccessible; already a base of 'B'
/*
class N:public A,public B
{
public:
N()
{
cout<<"\n N() ";
}
~N()
{
cout<<"\n ~N() ";
}
};
*/

int main(int argc, char **argv)
{
D d1;
/*
A()
C()
B()
D()
*/ Destruction will be in the reverse order

//d1.f(); // Error In this line
// error C2385: 'D::f' is ambiguous.
// Could be the 'f' in base 'C' of class 'D' or the 'f' in base 'B' of class 'D'
// If f() is overridden in D , then obviously that version will be called without any ambiguity.


E e1;
/*
A()
X()
B()
C()
E()
*/ Destruction will be in the reverse order

//e1.f(); // Error In this line
// error C2385: 'E::f' is ambiguous.
// Could be the 'f' in base 'B' of class 'E' or the 'f' in base 'C' of class 'E'
// If f() is overridden in E , then obviously that version will be called without any ambiguity.

M m1;
/*
A()
B()
M()
*/ Destruction will be in the reverse order

m1.f(); // B::f()
return 0;
}

0 comments;Click here for request info on this topic:

Post a Comment