I am trying to understand static_cast in regards to upcasting(child to parent). It is not making sense to me. I have to cast a child to a parent and demonstrate it. Upon looking at some code online and referencing books this is what I have.
Mustang *myMustang = new Mustang; Car *myCar = new Car; myMustang = static_cast<Mustang*>(myCar); But frankly, it does not show anything. I have no verification that it even casted. I tried to add a public function to the Car class and have it called from the child, but... it is obviously inherited.
This also implies I currently do not see a purpose in this type of upcasting.
My question is, how do I verify this even casted and what is the purpose of this typing of casting?
update: The answers were a bit hard to follow due to the fact I do not have experience with this type of casting and virtual functions are a vague memory. My friend was able to help me. Below is the code in case anyone else has the same issue.
class Car { public: virtual void Greeting() { cout << "I am a car." << endl; }; }; class Focus : public Car{ public: void FocusGreeting() { cout << "Hello, I am a Ford Focus." << endl; } }; class Mustang : public Car { public: virtual void Greeting() override { cout << "I am a Ford Mustang." << endl; } }; // in main Mustang* myMustang = new Mustang; Car *myCar = new Car; myCar->Greeting(); cout << "Now "; myCar = static_cast<Car*>(myMustang); myCar->Greeting();
Mustangis a base class ofCar, this is undefined behaviour