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.