Dynamic casting

Hello everyone,i wrote the following code where i try to convert a base class to a derived using dynamic_cast.I know that dynamic_cast doesn't allow this casting (although static allows it )but i want to ask about the error message which my compiler return:<< 'Base' is not a polymorphic type>>.
What does it mean? How can i make Base class polymorphic in order to succeed the conversion instead of using static_cast?

Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
using namespace std;

class Base
{
	public:
		void print1(){cout<<"hello Base \n";}
	private:
};


class Derived:public Base
{
	public:
		void print2(){cout<<"hello Derived \n";}
	private:
};

int main()
{
	Base* b1=new Base;
	Derived* d2=new Derived;

	d2=dynamic_cast<Derived*>(b1);

	
	return 0;
}

Thank you.
A polymorphic class is a class with at least a virtual method. If you don't have any method you want to make virtual, you can give it a virtual destructor
ok thanks mate :)
What are you actually trying to achieve?

In general, downcasting from a pointer to a real Base instance to a pointer to a Derived instance is a bad idea.

Say you had this:
1
2
3
4
5
6
7
class Derived : public Base
{
  public:
    int getGuts() const { return m_guts; }
  private:
    int m_guts;
};

and you managed to coerce a pointer to a new Base instance into a Derived* somehow.

Your subsequent call to getGets() will return garbage!

EDIT: by the way, you were probably just trying things out, but you actually have a memory leak in your code above.
Last edited on
Yeap kfmfe04 , i know tha it return garbage but as you said i am just experimenting.Thanks anyway for your post!
If you are experimenting, try overloading the cast operators to do what you want in a safe way.
And I can't think of any situation where this is useful, allot of the polymorphism rules and build in functionality makes downcasting not needed and dangerous.

What are you trying to get out of this experiment?
Last edited on
kfmfe04 wrote:
In general, downcasting from a pointer to a real Base instance to a pointer to a Derived instance is a bad idea.
dynamic_cast will never return a pointer/reference to an incomplete object
Topic archived. No new replies allowed.