P-P
P-P

Reputation: 1710

Is it OK to use multiple inheritance if one parent class is an interface?

enter image description here

Is it OK to use multiple inheritance if one parent class is an interface (only contains pure virtual functions with virtual destructor)?

I want to expose only interface part (yellow class in the picture) to increase compile speed. Green part is implementation part. But CPet should inherit from CAnimal(is-a relation) and IPet(implement), there are "Diamond of Death" :(

Interface classes (in yellow) only have pure virtual functions and virtual destruction, so when I create CDog, CCat through factory class, there are no problem like ambiguity. CDog has two vtables (from IDog and CPet) but in the virtual function tables, the points indicate same function (CDog member functions).

There's no compile error, no running error... but I'm worry about this hierarchy. Is it OK or are there any problems?

PS : I don't want to use 'virtual inheritance' because if I use that, I can't look into class member variable through watch view.(I guess it is because virtual inheritance link to parent class like linked-list.)

Environment : Visual Studio C++ 2008 or over.

Upvotes: 2

Views: 1109

Answers (1)

DRH
DRH

Reputation: 8366

Given the description above, you should not be able instantiate an instance of CPet because the pure virtual function IAnimal::isAlive() is undefined in the IPet vtable.

struct IAnimal {
    virtual ~IAnimal() {}
    virtual void isAlive() = 0;
};

struct IPet : public IAnimal {
};

struct CAnimal : public IAnimal {
    virtual void isAlive() {
    }
};

struct CPet : public CAnimal, public IPet {
};

int main(void) {
    CPet cp;
}

Produces the following when compiled with Visual C++ 2008 & 2010:

animal.cpp(18) : error C2259: 'CPet' : cannot instantiate abstract class
    due to following members:
    'void IAnimal::isAlive(void)' : is abstract
    mytest.cpp(5) : see declaration of 'IAnimal::isAlive'

GCC produces a similiar warning:

animal.cpp: In function 'int main()':
animal.cpp:18:7: error: cannot declare variable 'cp' to be of abstract type 'CPet'
animal.cpp:14:8: note:   because the following virtual functions are pure within 'CPet':
animal.cpp:3:15: note:  virtual void IAnimal::isAlive()

Upvotes: 2

Related Questions