DJ M
DJ M

Reputation: 41

How to change an instance of a class into an instance of a subclass

Basically what I am trying to do is set an instance of class 'MovingHero' into a 'ShootingHero', which is a subclass of 'MovingHero'.

As I have it now, the MovingHero class has a function called levelUp() that looks like this:

MovingHero levelUp()
{
    ShootingHero theHero();
    return theHero;
}

and in my main function I have:

if(hero1.getScore() == 5)
   hero1 = hero1.levelUp();

I'm not getting any errors, but after the if statement executes, hero1 is still a MovingHero rather than a ShootingHero.

I think this has something to do with operator overloading but I'm just not sure. Any help would be appreciated. Thanks!

Upvotes: 0

Views: 161

Answers (2)

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14313

Polymorphism only works with pointers (and technically references, although this isn't as common). MovingHero and ShootingHero are two different types; there is no way to successfully assign objects of one type to another.

MovingHero* and ShootingHero* however are both essentially the same type (a pointer) differing only in the type of data the point to (which has no effect on the actual pointer (it just provides the compiler with information regarding what is considered "legal")), so you can successfully assign pointers to ShootingHero objects to pointers to MovingHero objects.

Indeed, you can always assign pointers of any type to pointers of any other type using a cast, although this will more often than not lead to garbage values when you dereference the pointers. However, polymorphism guantees that the conversion will be valid, so there is no need for a cast.

Using polymorphism, your function could be written:

MovingHero* levelUp()
{
    ShootingHero* theHero = new ShootingHero();
    return theHero;
}

Note that you must manually delete this pointer at some point, as it is dynamically allocated.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Operator overloading?! No, it has nothing to do with that.

When you return from that function, you slice your ShootingHero object into a new MovingHero. In order to take advantage of dynamic polymorphism, you need to employ indirection. That means pointers and/or references.

You can't use object copying and keep the original most-derived type: your assumption that you have a MovingHero to work with is incorrect. Please read the chapter in your C++ book about polymorphism.


Actually, you don't have a ShootingHero object, because you wrote ShootingHero theHero(); which is a function declaration. The code you showed us will not compile; you probably meant ShootingHero theHero;.

Upvotes: 3

Related Questions