I am not familiar with the concept of inheritance, and I am struggling to find a solution to the following problem.
I have 2 classes, Head and Hand. I use instances of these classes mainly as elements of a vector. These two classes have common methods and methods unique to them.
In addition, I deal with general object pointers.
I thought the best way to implement this is to create a BodyPart class, like this
class BodyPart { public: typedef boost::shared_ptr<BodyPart> pointer; private: int commonMember1; double commonMember2; public: int commonMethod1(); int CommonMethod2(); }
and two derived classes like this
class Hand : public BodyPart { public: typedef boost::shared_ptr<Hand> pointer; private: int numFingers; public: int getNumFingers(); void printInfo(); }
Finally, I wanted to declare a Vector of BodyPart elements:
std::vector<BodyPart::pointer> cBodyParts;
containing the elements "Hand" or "Head", and calls my methods on vector elements when I need to.
But this approach does not work very well. Apparently, when I try to get a vector element, the compiler complains that it cannot convert from a generic BodyPart pointer to a generic Hand pointer. Moreover, if a vector is declared as described above, I cannot call methods specific to derived classes (for example, getNumFinger ()) for its element, even if they really belong to this class.
Is there a proper way to handle this? Or is my approach completely wrong? Thanks in advance!
user1156770
source share