When do you use each inheritance?
class Base{}; class Derived: protected Base{}; class Derived2: public Base{};
My case:
I have class called Snapshot which only contains GetXXX methods. It is a light-weight classed used to store current state of the Value class. I also use it for recovery, keeping instances of this class long after Value class instance are gone. A Manager class, processes instances of the Snapshot class. Let me show you the code:
class Snapshot { public: Snapshot (const Snapshot * snap) { _x=snap->_x; _y=snap->_y; _z=snap->_z; } Snapshot (){_x=_y=_z=0;} int GetX(){return _x;} int GetY(){return _y;} int GetZ(){return _z;} ~virtual Snapshot(){} protected: int _x,_y,_z; }; class Value:public Snapshot { /*Very heavy class with a lot of components used to calculate _x, _y, _z*/ }; class Manager { public: void Process( const Snapshot * snap) { } };
How do you feel about this design? What are the alternatives?
Thanks
Solutions and issues
-
Solution: I would create makeSnapshot function which would return Snapshot object by given Value object.
-
Issues:
-
major issue: I sent snapshots at very frequently (every second, even less), hence I don’t want to incur the construction and destruction cost minor issue:
-
semi-major issue I will have to make Value a friend of Snapshot, as I don’t want
to introduce setters.
-
Generally speaking I would use public inheritance, if I want to implement a specific interface, e.g. if my class is to be accessed thrugh a specific contract. Protected inheritance could be used, if you just want to reuse the functionality implemented in the parent.
I would make Snapshot a pure virtual class, e.g. just an interface, and Value would implement the getXYZ methods. E.g. you probably don’t need the _x,_y,_z members in Snapshot.