Trying to learn the difference in behavior of instantiating derived class objects
I created a base class "person" and a derived class "employee" as below
person
class person
{
protected:
string name;
public:
person();
~person();
virtual void setName(string myName)
{
name = myName;
}
};
employee
class employee : public person
{
public:
employee();
~employee();
void setName(string myName)
{
name = myName+"さん";
}
};
int main()
{
person newPerson = person();
employee anotherPerson1 = employee();
employee* anotherPerson2 = new employee();
person extraPerson1 = employee();
person* extraPerson2 = new employee();
newPerson.setName("new");
anotherPerson1.setName("another1");
anotherPerson2->setName("another2");
extraPerson1.setName("extra1");
extraPerson2->setName("extra2");
cout << newPerson.getName() << endl;
cout << anotherPerson1.getName() << endl;
cout << anotherPerson2->getName() << endl;
cout << extraPerson1.getName() << endl;
cout << extraPerson2->getName();
}
new
another1さん
another2さん
extra1
extra2さん
I understand the behavior of newPerson, anotherPerson1 and anotherPerson2.
I fail to understand why extraPerson1 and extraPerson2 behave differently even though both seem to have similar initiations.
Please help!
With
person extraPerson1 = employee();
you slice the employee
object into a person
object. The object extraPerson1
is a person
object and not an employee
object. When you call its setName
function you're calling person::setName
.
Polymorphism and virtual functions only work if you have pointers or references.