Can someone explain the reason for the non-polymorphic behavior of this piece of simple C++ code?
// src/main.cpp
#include <iostream>
class Base {
public:
Base() {
std::cout << "Making Base" << std::endl;
}
virtual void hello() {
std::cout << "Hello Base" << std::endl;
}
};
class Derived : public Base {
public:
Derived() {
std::cout << "Making Derived" << std::endl;
}
void hello() override {
std::cout << "Hello Derived" << std::endl;
}
};
int main() {
Base* bp = new Derived();
// Making Base
// Making Derived
bp->hello();
// Hello Derived
Base b = Derived();
// Making Base
// Making Derived
b.hello();
// Hello Base
}
Compile and run:
% g++ -std=c++14 -Wall -o obj/main.o -c src/main.cpp
% g++ -std=c++14 -Wall -o app obj/main.o
% ./app
Making Base
Making Derived
Hello Derived
Making Base
Making Derived
Hello Base
I would have expected b.hello()
to generate output Hello Derived
, or cause a compiler warning/error.