How to use derived classes with vectors and common pointers?

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!

+2
source share
2 answers

Your approach is correct, but also a compiler. It’s good that you have a vector of common pointers to the base class, but you will need to specify the actual type in order to get certain functionality.

typedef boost::shared_ptr<Hand> pointer; useless, but you only need a typedef in the base class. You will not throw between smart pointers. I would rename the base class of typedef to

 typedef boost::shared_ptr<BodyPart> BodyPartPtr; 

although.

Alan's good point in the comments: you have to make the virtual destructor of the base class virtual in order to prevent UB, since you will remove (indirectly) pointers to derived types using a pointer to the base type.

+3
source

Your approach is right (although you really don't need a typedef ), you just need to use boost::static_pointer_cast ( Doc here ) to convert from shared_ptr<BodyPart> to shared_ptr<Hand> when you need it.

You can also take a look at enable_shared_from_this at some point in your training.

+2
source

All Articles