I am very confused with the inheritance right now. I planned to simply override the initial value of a variable. In the following code i just inherit the base class and try to get it's name, which is saved as a string withing the class. I expected that the derived class can override this value, however it does not do it.
My expected out put was
Derived
Derived
However i get
Base
Base
What is the correct way to implement the following?
#include <iostream>
#include <string>
struct Base {
virtual ~Base() = default;
virtual void id(){
std::cout << id_ << std::endl;
}
std::string id_ = "Base";
};
struct Derived : public Base {
virtual ~Derived() = default;
std::string id_ = "Derived";
};
int main(){
Base* b = new Derived();
Derived* d = new Derived();
b->id();
d->id();
delete d;
delete b;
return 0;
}
See Question&Answers more detail:os