Search code examples
c++oopnew-operator

new operator -> with or without


Objective

Trying to learn the difference in behavior of instantiating derived class objects

My work

  1. Created a class "person"
  2. Added a virtual method to "person" class that sets value to variable name
  3. Defined a class "employee" derived from the base class "person"
  4. Added a method to "employee" class that sets value to variable name initially defined in the base class but adds "さん" suffix after it.
  5. Created different types or initiations and tested the difference between the outputs

Defined classes

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+"さん";
    }
};

Main

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();
}

Console output

new
another1さん
another2さん
extra1
extra2さん

Question

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!


Solution

  • 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.