So I have a simple snippet of code:
class Base {
public:
virtual void print() {cout<<"Base print"<<endl;}
};
class Derived: public Base {
public:
virtual void print() {cout<<"Derived print"<<endl;}
};
now in my main.cpp
, when I downcast a Base
class that is instantiated as Derived
, I can only downcast if it's a heap variable and not a stack variable, any idea why?
This seems like a simple issue, but I can't find an answer online for it.
Works
int main() {
Base* x = new Derived();
Derived* d = dynamic_cast<Derived*>(x);
if (d){
d->print(); // This line executes
} else {
cout<<"Cast failed"<<endl;
}
return 0;
}
Doesn't Work:
int main() {
Base x = Derived();
Derived* d = dynamic_cast<Derived*>(&x);
if (d){
d->print();
} else {
cout<<"Cast failed"<<endl; // This line executes
}
return 0;
}