Creating objects and downcasting them in the same line?

I am trying to create an object and downcast it in the same line.
But I am getting errors with Child *cp= dynamic_cast <Parent *> new Parent();

#include<iostream>
using namespace std;

class Parent
{
public:
void Parent_display(){cout << "\n I am from Parent "<< endl;}

};

class Child:public Parent
{
public:
void Child_display() {cout << "\n I am from Child \n";}
};

int main()
{

Child *cp= dynamic_cast <Parent *> new Parent(); // This will throw an error
cp->Parent_display(); //Both parent and child can be accessed
cp->Child_display();

return 0;
}

Last edited on
Of course it throws an error. A Parent is not a Child.

You would like to call cp->Child_display();
Look at:
1
2
3
4
5
class Parent
{
public:
void Parent_display(){cout << "\n I am from Parent "<< endl;}
};

Does Parent have function Child_display()? No.

The dynamic_cast does not modify object. You can't cast a pointer to be Child* unless the pointed to object is a Child.


Furthermore, dynamic_cast <Parent *> new Parent() makes no sense. The new returns Parent*. You try to cast it into Parent* ? Useless no-op cast.

You can have Parent* p = new Child;
cannot have Child* p = new Parent;
Topic archived. No new replies allowed.