You mean something like this? If you run this program you will see that class A is common to all the other classes. There are not separate instances of class A in class B, C and E. Any changes to the data in class A is reflected in all other classes because of the virtual keyword.
#include <iostream>
using std::cout;
class A
{
public:
A() {x = 0;}
void show() {cout << "x = " << x << '\n';}
protected:
int x;
};
class B :virtual public A
{
public:
B() {y = 0; A::x = 2;}
void show() {cout << "y = " << y << '\n'; A::show();}
protected:
int y ;
};
class C :virtual public A
{
public:
C() {z = 0; A::x = 3;}
void show() {cout << "z = " << z << '\n'; A::show();}
protected:
int z ;
};
class E : virtual public B,virtual public C, virtual public A
{
public:
E() { A::x = 4; B::y = 2;}
void show()
{
B::show();
C::show();
A::show();
}
};
int main()
{
E e;
e.show();
}
Hmm... I didn't use virtual and didn't redeclare base function(show) in my child class...
It's like:
class A
{
protected:
int convert(char a) { return a-48; }
};
class B : public A
{
protected:
int cal_circle(char radius) { return 3 * convert(radius); }
};
class C : public A
{
protected:
int cal_square(char width) { return convert(width)*2; }
};
class E : public B, public C, public A
{
public:
void size ()
{
cout<<"circle size: "<<cal_circle('3')<<endl;
cout<<"square size: "<<cal_square('2')<<endl;
//at here i need to use A.convert(int *)
cout<<"convert: "<<convert('4')<<endl;
}
};
int main()
{
E e;
e.size();
}
I just tried to use virtual and it solve the error but why?
class V { /* ... */ };
class B1 : virtual public V { /* ... */ };
class B2 : virtual public V { /* ... */ };
class B3 : public V { /* ... */ };
class X : public B1, public B2, public B3 { /* ... */
};
if I remove all the virtual, are they B1,B2,B3 still pointing to the same V all 3 of them point to 3 different V?
Compile and run the program I posted but remove the virtual keyword everywhere. It will show you the difference between using virtual and not using virtual.