Search code examples
c++classvectorparent

how to access child instances in a vector in c++


I have a parent class and child class (inherited from parent). In the child class, I have a member function named function_blah();

I used vector<parent*> A to store 5 parent instances, 3 child instances. So the total number of elements in the vector is 8.

I can easily access to member functions of element A[0] to A[4], which are parent instances. But whenever I try to have access to member functions of element A[5] to A[7], the compiler complains that class parent has no member named 'function_blah'

The way I access to elements is using index. e.x A[i] with i = 0..7. Is it correct? if not, how?


Solution

  • You need to downcast the pointer to the child class in order to use child functions on it.

    When you're accessing a child object using a parent*, you are effectively telling the compiler, "treat this object as a parent". Since function_blah() only exists on the child, the compiler doesn't know what to do.

    You can ameliorate this by downcasting using the dynamic_cast operator:

    child* c = dynamic_cast<child*>(A[6]);
    c->function_blah();
    

    This will perform a runtime-checked, type-safe cast from the parent* to a child* where you can call function_blah().

    This solution only works if you know that the object you're pulling out is definitely a child and not a parent. If there's uncertainty, what you need to do instead is use inheritance and create a virtual method on the parent which you then overload on the child.