I have a base type:
class Foo{
public:
int height;
int weight;
void jump();
}
I have a descendant:
class Bar : public Foo{
//Has a different implementation of jump();
}
I have a factory that returns a kind of Foo;
static Foo createTheRightThing(int type){
if (type == 0){
return Foo();
}
else if (type ==1){
return Bar();
}
}
The method that calls createTheRightThing
looks like this:
void boo {
Foo someFoo = FactoryClass::createTheRightThing(1); //Just using 1 to illustrate the problem.
}
The problem:
someFoo is always a Foo
, and never a Bar
, even when I pass 1 in. When I pass 1 in, I can see that the correct else block is entered, and the factory does indeed return a Bar
.
The member variables, match those set by the factory when creating the Bar.
If I call someFoo.jump()
, it is always the jump()
in a Foo. It never calls the jump()
in Bar
.
What am I doing incorrectly ? How do I fix it ? I understand polymorphism in Java, Objective-c, but don't have much experience in C++. Is this problem because I am not creating a new object and returning a pointer ?