calling a virtual function of a base class that is assigned a derived class uses base class function

I've attempting to call the function fly(), it's a virtual function of the base class FlyingBehaviour and derived class FlyWithWings. when I do this

1
2
FlyingBehaviour fb = FlyWithWings();
fb.fly()


nothing happens, it calls the FlyingBehaviour version of the fly() function rather than the FlyWithWings version.

edit:
this works, why?


1
2
3
    FlyBehaviour* fb = new FlyWithWings();
    fb->fly();
    delete fb;


FlyingBehaviour.hpp
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef FLYBEHAVIOUR_HPP
#define FLYBEHAVIOUR_HPP

class FlyBehaviour
{
public:
    FlyBehaviour();
    virtual ~FlyBehaviour() = default;
    virtual void fly() {};
};

#endif //FLYBEHAVIOUR_HPP 


FlyWithWings.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef FLYWITHWINGS_HPP
#define FLYWITHWINGS_HPP

//SELF
#include "FlyBehaviour.hpp"

class FlyWithWings : public FlyBehaviour
{
public:
    FlyWithWings();
    virtual void fly();
};

#endif //FLYWITHWINGS_HPP 


FlyWithWings.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "FlyWithWings.hpp"

//STD
#include <iostream>

FlyWithWings::FlyWithWings()
{
    std::cout << "FlyWithWings Behaviour constructed\n";
}

void FlyWithWings::fly()
{
    std::cout << "Flying with wings\n";
}
Last edited on
Your problem is this:

FlyingBehaviour fb = FlyWithWings();

This instantiates an instance of FlyingBehavior by copying from the FlyWithWings instance. In the end, fb is a FlyingBehavior instance. Try this instead:
1
2
3
4
5
6
#include <memory>

//...

std::unique_ptr<FlyingBehavior> fb {new FlyWithWings};
fb->fly();
Make sure you have a compiler that supports C++11. If not, try this:
1
2
3
FlyingBehavior *fb = new FlyWithWings;
fb->fly();
delete fb; //essential 
Last edited on
Thanks LB, I just found out that new'ing it made it work before I saw your post. But I still don't see how a pointer fits in to this.

That was a really fast reply though.
Last edited on
It can also work with references:
1
2
3
FlyWithWings fww;
FlyingBehavior &fb = fww;
fb.fly();


The point is that FlyingBehavior should be the interface, not the actual type, and you can only do that with a pointer or reference.
Last edited on
Thanks, though I suppose you meant FlyingBehaviour&? this forum is great for quick questions :]
Last edited on
Yes, whoops, you're right I missed the ampersand.
Topic archived. No new replies allowed.