I need little help with inheritance in C++. I have code with same structure like this:
class IBase {
public:
virtual long Dimensions() = 0;
};
class IShape : public IBase {
virtual long Area() = 0;
};
class Rectangle : public IShape {
private:
long x;
public:
long Dimensions() {return x};
long Area() {return x*x};
};
class Rhombus: public IShape {
private:
long x;
long fi;
public:
long Dimensions() {return x};
long Area() {return x*x*sin(fi)};
};
As you can see, implementation of Dimensions() is same for both classes. Now I wan't to do something like this:
class BaseImplementation : public IBase {
protected:
long x;
public:
virtual long Dimensions() {return x};
};
class Rectangle : public IShape, public BaseImplementation {
public:
long Area() {return x*x};
};
class Rhombus: public IShape, public BaseImplementation {
private:
long fi;
public:
long Area() {return x*x*sin(fi)};
};
Is possible to insert implementation of method Dimensions() into class Rhombus from BaseImplementation? Is this supported in some version of C++ standard? Thx.
The problem with your hierarchy is that your
Rectangle
now inheritsIBase
twice: once throughIShape
, and once throughBaseImplementation
. C++ feature called Virtual Inheritance is designed to deal with situations like that. Note that you need to makeIShape
's inheritingIBase
virtual public
as well.