I am fairly new to C++ (& OOP). I am struggling to understand the following piece of code:
#include <iostream>
class Base {
public:
Base() {
std::cout << "In Base Constr: " << __FUNCSIG__ << std::endl;
}
virtual ~Base() {
std::cout << "In Base Destr: " << __FUNCSIG__ << std::endl;
}
void A() {
std::cout << "In Base func A " << __FUNCSIG__ << std::endl;
}
};
class Derived : public Base {
public:
Derived() {
std::cout << "In Derived Constr: " << __FUNCSIG__ << std::endl;
}
~Derived() {
std::cout << "In Derived Destr: " << __FUNCSIG__ << std::endl;
}
void B() {
std::cout << "In Derived func B " << __FUNCSIG__ << std::endl;
}
};
void test(Base* b) {
Derived* d = static_cast<Derived*>(b);
d->A();
d->B(); // How is this valid??
}
int main() {
Base *b = new Derived();
std::cout << "In main" << std::endl;
b->A();
std::cout << __LINE__ << std::endl;
Base *bb = new Base();
std::cout << __LINE__ << std::endl;
test(bb);
delete b;
delete bb;
}
I am not sure, why & how the line d->B()
works? even though the pointer was typecasted to Derived class, but the Base class object itself should not have that function in memory.
I am not sure, why & how the line b->B() works? [..] the Base class object itself should not have that function in memory
You're right! It doesn't work!
(Well, functions aren't stored "in memory", but…)
The call is invalid. The static_cast
says "I promise that this Base*
points to a Derived
". That promise was broken.
The program has undefined behaviour. That can in practice mean that things "appear" to work, especially if no member variables were touched by the non-existent function...