the use virtual func and inherit

what is wrong with these codes and why?

#include "iostream"
using namespace std;

class base
{
public:
virtual ~base(){}
void work(){_do_work();}
private:
virtual void _do_work();
};

class child:public base
{
child();
private:
void _do_work(){}
};

void main()
{

child test;
test.work();
base *pb=&test;
pb->work();
child *pc = dynamic_cast<child *>pb;
pc->work();
delete pb;
return;

}
firstly, base:: _do_work() is undefined.(edit: if you don't want to define see http://www.cplusplus.com/doc/tutorial/polymorphism/#abstract )
secondly, pb is not dynamicaly allocated, so you can't delete it
Last edited on
I've correct the errors above, but find that

"child *pc = dynamic_cast<child *>(pb);"

will be run-error, what is the reason?
no idea. can you post your full current code?
also, there is another problem with your code. counstructors should be public. (child::child() is private, becouse by default classes have private access type)
Last edited on
You shouldn't use dynamic_cast for that, use static_cast. Use it wisely.
http://www.cplusplus.com/doc/tutorial/typecasting/
delete pb is wrong as the object was declared on the stack with child test;

There's nothing wrong with the rest of it.
Topic archived. No new replies allowed.