I have some doubts about static_cast and dynamic_cast in C++. Do they completely change the object a pointer is pointing to from a class A to a class B by preserving the already-set member variables (except the ones that cannot be passed from derived to base) ?
I noticed that if I have something like
struct Base
{
Base() { }
virtual ~Base() { }
virtual void Method() { cout << "Base Method"; }
};
class Derived : public Base
{
public:
virtual void Method() { cout << "Override Method"; }
};
struct Derived2 : public Derived
{
Derived2() { cout << "Derived2 constructor"; }
void Method() { cout << "Override2 Method"; }
};
int main()
{
Base *myPointer = new Derived();
static_cast<Derived2*>(myPointer)->Derived2::Method();
delete myPointer;
return 0;
}
The constructor isn’t called, but the method does. How is this possible?
The casts don’t change the object at all. They only give you a different pointer to a related class type in the inheritance hierarchy:
For example, the above dynamic cast succeeds if we have a hierarchy
AnotherClass : BaseandDerived : AnotherClass(andBaseis polymorphic).A
static_castcan usually be used when you already know that you have a more derived dynamic type, but happen to have only a pointer or reference to a base.(A static cast can never be used to cast from a virtual base, in which case you always need
dynamic_cast.)