imichaelmiers
imichaelmiers

Reputation: 3509

C++ inheritance, members and redundant data

I have two classes Foo and Bar with redundant members. I want a third class FooBar that holds the members of both types which I can pass into functions expecting either type( probably with a cast) and not have two copies of everything floating around.

class Foo{
public:
    A a;
    B b;
    C c;
};

class Bar{
    A a;
    B b;
    D d;
};

class FooBar{
    A a;
    B b;
    C c;
    D d; 
};

In c++, is there anyway to do this without modifying code that uses A or B (or at most changing the types that code expects) and without making extraneous copies or retaining redundant data? Simple Inheritance keeps around duplicate data. Having a common base class and virtual inheritance compiles under clang but appears not to work.

Upvotes: 0

Views: 305

Answers (1)

Barry
Barry

Reputation: 302767

The compiler has no way of knowing that Foo::a and Bar::a refer to the same thing. That may be logically true in your program, but that's certainly not enforced anywhere in code.

If they really mean the same thing, you might want to have a common base:

class AB {
public:
    A a;
    B b;
};

And use virtual inheritance everywhere else:

class Foo : public virtual AB {
public:
    C c;
};

class Bar : public virtual AB {
public:
    D d;
};

class FooBar : public Foo, public Bar {

};

This way, there's only one FooBar::a.

Upvotes: 4

Related Questions