How does one correctly typecast a parent class as a child class in C++?
For example, if I have two classes,
Atom -> Cu
(Parent) (Child)
and I've identified that I have an Atom a
that is actually an instance of Cu
, then how to I typecast a
to a Cu
object?
What I've tried so far:
Cu c = (Cu) a
-> No matching conversion for C-style cast from 'Atom' to 'Cu'
Cu c = Cu (a)
-> No matching conversion for functional-style cast from 'Atom' to 'Cu'
Cu c = static_cast<Cu>(a)
-> No matching conversion for static_cast from 'Atom' to 'Cu'
Cu c = dynamic_cast<Cu*>(&a)
-> 'Atom' is not polymorphic
Edit: A (rough) solution
Here's a piece of working code that accomplishes what I needed:
// Overrides Atom::equals(Atom* other)
bool Cu::equals(Atom* a) {
// checks to see if a is a Cu pointer
if(other->getID() == "Cu") {
// If so, typecasts it
Cu* c = (Cu*) a;
// Checks functions specific to Cu atoms
...
}
}
Edit 2
I've marked this question as a duplicate because 1) The best solution I've read involves "virtual functions", and 2) The question that this question now redirects to mentions them and explains why they are useful.