0
#include <iostream>

class Base {
public:
    int a;

    Base() : a(0) {};
};

class Inherited1 : public Base {
public:
    void add() {
        a++;
    }
};

class Inherited2 : public Base {
public:
    void sub() {
        a--;
    }
};

class Combined : public Inherited1, public Inherited2 {
//public:
//  int& a;
//
//  Combined() : a(Inherited1::a) {};
};

int main() {
    Combined obj;

    obj.add();
    obj.add();
    obj.sub();

    std::cout << dynamic_cast<Inherited1*>(&obj)->a << ' ';     // -> 2
    std::cout << dynamic_cast<Inherited2*>(&obj)->a;            // -> -1

    return 0;
}

I want to somehow force add() method in Combined class to use the same variable as sub() method without changing Base, Inherited1 or Inherited2 classes, so my program would print out "1 1".

Is it even possible in that example?

I'm curious because I'm trying to create something like std::iostream, just for fun.

fpekal
  • 1
  • 2
    I suspect you may find [virtual base classes](https://stackoverflow.com/questions/21558/in-c-what-is-a-virtual-base-class) interesting. – WhozCraig Sep 25 '21 at 20:43
  • Yes! It's exactly what I've looked for. Thank you very much @WhozCraig! – fpekal Sep 25 '21 at 20:47
  • Note that you're opening a rancid can of worms here: A diamond inheritance hierarchy. It does have its uses, but be very careful about using this in production code. If Base contains data members initialization rules are un-intuitive. Also, you're opening yourself to some "interesting" ambiguity name lookup situations. – ravnsgaard Sep 25 '21 at 21:00

0 Answers0