So I was playing around with the concept of inheritance in C++ to get a better understanding of it and I used static_cast to cast adress of a base class object to a derived class pointer.
class A
{
public:
A() { cout << "A's constructor called " << endl; }
};
class B:public A
{
public:
B() { cout << "B's constructor called " << endl; }
void funcinB() { cout << "Hello from B" << endl; }
};
int main()
{
A a;
B *b = static_cast<B*>(&a);
if (b)
{
b->funcinB();
}
}
the program calls B's method, which is something I don't understand as the derived class object was never consructed. following is the output of the program
A's constructor called
Hello from B
Now I know you're not suposed to use static_cast this way, but I'm looking for an explanation as to why the program was able to call B's method.
Thanks!