One base multiple derived classes

Hello;

I want to use inheritance to make two classes and I want them to have same base class. Different derived classes and same base instance.

For example
1
2
3
class A { public: int x; };
class B : public A { int y };
B instance1, instance2;


When I change instance1.x=2 I want instance2.x to be 2 too. But not instance1.y and instance2.y, I want y variables to be discrete while x variables are same.

Is something like that possible with inheritance?
Declare x as static.
Yes but I'm not considering just x, I want whole A base class to be same.

For example same constructors too. I want its constructors to run just one time and you cannot define a constructor static.
Last edited on
How about constructing B with an A reference instead of deriving B from A?
Yes, it's the solution I've used.

Like B.A->x, so it's without inheritance.

I just wondered is it possible to make what I wanted.


For example if I have a brother then we have the same mother, not with same type like height, weight, eye color etc. of two mothers but just one same mother. If my mother wears a red pullover, then my brother's mother wears the same red pullover too. Isn't that logical? I just thought that this type of inheritance could be made in C++
Last edited on
That doesn't translate well to inheritance. The relationship you're describing is that of a tree:
1
2
3
4
Person mother, you, your_brother;
you.mother=&mother;
your_brother.mother=&mother;
mother.put_on_red_pullover();

Inheritance is an is-a relationship. Neither you nor your brother are subtypes/subspecies of your mother.
constructors and destructors of the base class is always called when a new object of a derived class is created or destroyed.

helios is right, declare x of the base class to be static not its constructor, anyways static variables are initiated only once....
Topic archived. No new replies allowed.