-
virtual class-es
I dont know how to explain to all of you in English.So I m going to show you my problem
Code:
class Base
{
private:
int x;
public:
Base(int xx){x=xx;}
};
class Derived1:public Base
{
private:
int y;
public:
Derived1(int xx,int yy):Base(xx)
{ y=yy;}
};
class Derived2:public Base
{
private:
int z;
public:
Derived2(int xx,int yy):Base(xx)
{ y=yy;}
};
class Final:virtual public Deived1,virtual public Derived2
{
};
Why do we write virtual in Final?
-
Not my arena, but I think it may have to do with the "dreaded diamond".
-
For starters, that's not where you want the virtuals.
Code:
class Derived1 : virtual public Base
{
};
class Derived2 : virtual public Base
{
};
If you don't do this, the join class (Final in your example) will have two "copies" of Base, the Base it inherited from Derived1, and the Base it inherited from Derived2. Sometimes, this is exactly what you want. Other times it isn't.
By using virtual inheritance, Final only has one Base component, rather than two.