I have the following problem. I am busy coding up an inheritance structure in C++. Briefly, this is what I am attempting to do. Class A is the base class and classes B and C are inherited class. Classes B and C each have different and unique member functions.
Now, using the boost smart pointer library I make a vector of shared pointer of class type A as follows:
class A{
A();
virtual print();
}
class B : public A{
B();
virtual print();
}
class C{
C();
virtual print();
void uniqueFunc();
}
int main(){
vector<shared_ptr<A> > myA;
shared_ptr<B> myB;
shared_ptr<C> myC;
myA.push_back(myB);
myA.push_back(myC);
}
Now I have a method for checking the type of members within the vector. This isn’t the issue. My question is, how do I call uniqueFunc for a member of class type C within the vector. Would I have to downcast? Or do I have to create virtual function. I do however, need uniqueFunc to be unique to class C. I would like to avoid creating copies of members and rather directly change the member in the vector.
You either need to downcast to
boost::shared_ptr<C>or create a virtual function inA.Assuming you want to downcast, you could use Boost’s pointer cast functions:
(or use
dynamic_pointer_cast<C>if you need dynamic type checking.)