Given the following code:
class Base {
public:
virtual void Test() {
cout << "Not Overridden" << endl;
}
};
class Derived : public Base {
public:
void Test() override {
cout << "Overridden" << endl;
}
};
int main() {
Base o = Derived();
o.Test();
return 0;
}
Someone like me who is from a Java background, expects the compiler to output Overridden
but surprisingly the output is exactly the otherwise.
If this is a normal behavior, then what's the point of inheritance in C++ at all?
What is that I am missing?
Yes, it's normal behavior, polymorphism only works with pointers and references.
With raw pointer:
int main() {
Base* o = new Derived();
o->Test();
delete o; //when done with using it delete it from memory
//...
}
An alternative to this memory management would be to use smart pointers.
With smart pointer:
int main() {
unique_ptr<Base> o(new Derived); // automatic memory management
o->Test();
//...
}
With reference:
int main() {
Derived d;
Base& o = d;
o.Test();
//...
}
This is something you need to be careful with, when the block where Derived
object was declared goes out of scope, the reference will be rendered useless, for example, if you return it from a function.
Output:
Overridden
Some threads on the site explain why this is so, like this one.
The way you have it leads to object slicing.
You'll also want to add a virtual destructor to your base class.