Passing pointer to derived class, to function that

2019-06-02 09:31发布

OK. I'm not very good at polymorphism in C++, but I've a problem now. Imagine these classes:

class Parent {
public:
     Parent();
     virtual ~Parent();
};

class Child : public Parent
{
public:
     Child();
};

class Director
public:
     Director();
     void doStuff(Parent* p);
};


// Assume we have a instance of Director, and call the doStuff function here:
doStuff(new Child()); // Gives error

I get the error

cannot convert parameter 1 from 'Child *' to 'Parent *'

And my simple question is, WHY this doesn't work? Do I need to do any sort of casting or what, or what is the problem?

EDIT: I put all my files here as they are. I think the problem lies in my inclusions, since I really dont have any idea of how it's supposed to be done with #ifndef and such. Please check them out.
Director.h: http://pastebin.com/2uJqezju
Director.cpp: http://pastebin.com/SZ6cuBJC
IApp.h: http://pastebin.com/euCAwpnL
IApp.cpp: http://pastebin.com/JHDuQUhW
IScene:h: http://pastebin.com/cweH9G6p
IScene.cpp: http://pastebin.com/9epW0dRA

Then I have created some instances of it:
GameApp.h (inherits EDGE::IApp): http://pastebin.com/QbjbVqSi
GameApp.cpp: http://pastebin.com/sYJvmbeP
GameScene.h (inherits EDGE::IScene): http://pastebin.com/K1WYNvRf
GameScene.cpp: http://pastebin.com/uJx3FLBW

Don't be afraid to check them out, there are really like 10 lines of code in each of them. But the problem is in GameApp.cpp where I try to create an instance of GameScene, and pass it to the Director->createNewScene(IScene* scene).

1条回答
女痞
2楼-- · 2019-06-02 10:06

Director.h:

class IScene;

should be inside namespace

查看更多
登录 后发表回答