I have the following C++ code:
#include <iostream>
class Base {
public:
Base() { }
Base(const Base& other) { this->foo(); }
virtual ~Base() { }
virtual void foo() { std::cout << "Base::foo" << std::endl; }
};
class My : public Base {
public:
My() : Base() { }
My(const My& other) : Base(other) { }
virtual ~My() { }
void foo() { std::cout << "My::foo" << std::endl; }
};
int main(int argc, char** argv);
int main(int argc, char** argv) {
My* my = new My();
My* my2 = new My(*my);
}
Class My
inherits from Base
. The important thing is that Base
has a virtual method foo
which is overridden in My
.
Polymorphism not kicking in
In the copy ctor of Base
, called by My
's copy ctor, I call foo
. However I expect Base::Base(const Base&)
to call My::foo
, however when running the program I get:
Base::foo
Why is this happening? Should polymorphism have My::foo
be called?