As shown in the following code i am trying to convert a base class pointer to derived class pointer. I am expecting compiler error from the following code but does not report any error. Also the function "SomeMethod_2" printing value 10.
#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << "Base class constructor\n";
}
};
class Derived : public Base
{
public:
int Val;
Derived() {
cout << "Derived class constructor\n";
}
void SomeMethod(void)
{
cout << "SomeMethod\n";
}
void SomeMethod_1(void)
{
Val = 10;
}
void SomeMethod_2(void)
{
cout << Val;
}
};
int main()
{
Base* BaseObj = new Base();
Derived* DerivedObj = (Derived*) BaseObj;
DerivedObj->SomeMethod(); # Expecting compiler error
DerivedObj->SomeMethod_1();
DerivedObj->SomeMethod_2();
return 0;
}
dynamic_cast<Derived*>at runtime.(Derived*)BaseObjis a c-style cast and sloppy speaking it tells the compiler: "I am more clever than you, do not bother me with warnings or errors". Don't use it when you want the compiler to help you with warnings / errors