views:

143

answers:

3

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  A: 

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

Ben
+4  A: 

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.

Dan Story
Thank you very much for you suggestions. I'll use the virtual functions.
tsubasa
A: 

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.

zdawg