Inheritance Issues

M

Matthew

Hi, I have a base class called Item with a virtual function act. It's
subclass Sword defines the function again doing something different
from the first. It store the sword in a vector of items and call the
act function and, as to be expected, it calls the one from Item. How
can I get it to call the one from sword?
 
R

Russ Ford

On 20 Nov 2003 12:50:00 -0800, (e-mail address removed) (Matthew) wrote:

Did you declare act as virtual in the Sword class?
 
M

Mike Wahler

Russ Ford said:
On 20 Nov 2003 12:50:00 -0800, (e-mail address removed) (Matthew) wrote:

Did you declare act as virtual in the Sword class?

Not necessary (as long as the signature is the same).

The real issue is: *How* was the function called?
Polymorphism only works via a pointer or reference.

Matthew:

We can only make guesses like this since you show no code.

Show the code.

-Mike
 
M

Mike Wahler

Mike Wahler said:
Not necessary (as long as the signature is the same).

Clarification: if the signature is not the same, then
it's not an override anyway.

-Mike
 
L

lilburne

Matthew said:
Hi, I have a base class called Item with a virtual function act. It's
subclass Sword defines the function again doing something different
from the first. It store the sword in a vector of items and call the
act function and, as to be expected, it calls the one from Item. How
can I get it to call the one from sword?

If you have vector<Item> then you are stuffed because what
is stored in the vector is Item's the Sword part is stripped
off, lookup class slicing (no pun intended) in your book.
What you want is either a vector of pointer to Items
vector<Item*>, or more preferably a vector<
smart_pointer<Item> >. Where 'smart_pointer' is your
favourite wrapper for pointers (boost::shared_ptr at a pinch
I suppose).
 
J

jeffc

Mike Wahler said:
Clarification: if the signature is not the same, then
it's not an override anyway.

If it's not virtual, it's never an override regardless of the signature.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top