In a project of mine I encountered this problem where the polymorphism seemingly doesn't work. Derived classes don't seem to override the base class, but no errors ocurr either.
This is a simplification of the code, but it generates the same problem. The usage of vector
and unique_ptr
is the same as in my project, I suspect that my usage of those is what's causing the problem.
I expect
void print() override
{
printf("B HEJ");
}
to override
virtual void print()
{
printf("A HEJ");
}
, but it doesn't. Why?
Here is the complete source code:
#include <iostream>
#include <string>
#include <memory>
#include <vector>
class A
{
public:
virtual void print()
{
printf("A HEJ");
}
};
class B : public A
{
public:
void print() override { printf("B HEJ"); }
};
int main()
{
std::vector<std::unique_ptr<A>> ass;
ass.emplace_back(std::make_unique<A>(B()));
ass[0]->print();
std::cin.get();
}
make_unique
makes a new object too. – Ricci