Noob to C++. I countered a weird issue when playing with inheritance in C++. I have a Parent class, and 2 child class that inherit Parent class.
#include <iostream>
#include <memory>
class Parent {
public:
Parent() {}
};
class Child1: public Parent {
public:
int param1;
Child1(int param): Parent() {
param1 = param;
}
};
class Child2: public Parent {
public:
int param2;
Child2(int param): Parent() {
param2 = param;
}
};
int main() {
std::shared_ptr<Parent> obj = std::make_shared<Child1>(123);
std::cout << std::static_pointer_cast<Child2>(obj)->param2 << std::endl;
// output 123 and no run time error, wut?
return 0;
}
As you can see, although obj is initialized with Child1's constructor, it can still be cased to Child2. Event param2 has the same value as param1.
What's going on here? Is there a term for this kind of behavior? Is this special to shared_ptr?
Thanks a lot!