You are misunderstanding the meaning of a virtual base class. And you are mixing up its meaning with the idea of a static class member.
The use of a virtual base class only comes into play when there is multiple inheritance, and more than one parent class inherit the same base class themselves. For instance, assume you created a new class D:
1 2
|
class D : public B, public C
{ };
|
If A were NOT a virtual base class of classes B and C, then D would have 2 copies of A when it is constructed. Calling
changea()
on an object of class D would cause confusion because it would only change one of the
A::a
values (either the one derived from B or the one derived from C).
By declaring A as a virtual base class of both B and C, class D will only have 1 copy of A within it. Calling
changea
on an object of class D in this case will cause no confusion, and the single copy of
A::a
will be changed appropriately. However, objects of class D would each have their own copy of
A::a
, so calling
changea()
on one object of class D would not affect the value in another object of class D.
To get the behavior you were expecting, you would want to make
A::a
a static member of class A. Then, every object of class A (or a class derived from A) would see the same value.
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 31 32 33 34 35 36 37
|
#include <iostream>
using namespace std;
class A
{
private:
static int a;
public:
void changea(int b);
void displaya();
};
void A::changea(int b)
{
a = b;
}
void A::displaya()
{
cout << a << endl;
}
int A::a = 7;
class B : public A
{ };
class C : public A
{ };
int main()
{
C coffee;
B tea;
coffee.changea(10);
tea.displaya();
}
|
Is that what you're looking for?