开发者

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

开发者 https://www.devze.com 2022-12-26 02:12 出处:网络
I have a parent class and child class (inherited from parent). In the child class, I have a member function named function_blah();

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?


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.


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*.


Is member _blah() declared virtual in parent? Or is it even declared in parent? Because if not, then you'll never be able to access _blah() through a parent pointer. And yes, you'll also have to downcast, but only if you know exactly that you're expecting a child type.

0

精彩评论

暂无评论...
验证码 换一张
取 消