Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

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.

like image 77
Dan Story Avatar answered Oct 24 '25 13:10

Dan Story


You're storing parent*, which has no function_blah method. You need to either make function_blah a virtual method of parent, or use dynamic_cast to downcast to a child*.

like image 28
Ben Avatar answered Oct 24 '25 13:10

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!