So I have a class Base
and a class Derived: public Base
.
baseInstance.doSomething()
will print Base::doSomething()
.
derivedInstance.doSomething()
will print Derived::doSomething()
.
Here is the code:
#include "Base.h"
#include "Derived.h"
#include <vector>
int main(){
Base base;
std::cout<<"Base should do something:\n";
base.doSomething();
Derived derived;
std::cout<<"\nDerived should do something:\n";
derived.doSomething();
std::vector<Base> vec;
vec.push_back(derived);
std::cout<<"\nDerived should do something:\n";
vec[0].doSomething();
return 0;
}
Expected output:
Base should do something:
Base::doSomething()
Derived should do something:
Derived::doSomething()
Derived should do something:
Derived::doSomething()
Actual output:
Base should do something:
Base::doSomething()
Derived should do something:
Derived::doSomething()
Derived should do something:
Base::doSomething()
How do I preserve class type in a std::vector
?
EDIT: But wouldn't the object slicing leave method implementation alone? And just remove excess fields? And is there a way to circumnavigate this?