NO Idea, why the base string get return instead of Derived, is that becasue vector copied only base object from the dervied object?
#include <vector>
#include <iostream>
using namespace std;
class Base
{
protected:
int m_value{};
public:
Base(int value)
: m_value{ value }
{
}
virtual const char* getName() const { return "Base"; }
int getValue() const { return m_value; }
};
class Derived: public Base
{
public:
Derived(int value)
: Base{ value }
{
}
virtual const char* getName() const { return "Derived"; }
};
int main()
{
std::vector<Base> v{};
v.push_back(Base{ 5 });
v.push_back(Derived{ 6 });
for (const auto& element : v)
std::cout << "I am a " << element.getName() << " with value " << element.getValue() << '\n';
return 0;
}
why in second output Base is get return from the getName() methods?
Is that because of vector is not a pointer type or reference?
I am a Base with value 5
I am a Base with value 6 ----> why it prints the Base?
Aucun commentaire:
Enregistrer un commentaire