1

Two classes: Data is parent and DerivedData is child. Why does cout output "Data"?

class Data {
protected:
    int _value {};

public:
    Data(int value) : _value{ value } { }

    std::string getName() const { 
        return "Data"; 
    }

    int getValue() const { 
        return _value; 
    }

    void setValue(const int i) { 
        _value = i; 
    }
};

class DerivedData: public Data {
public:
    DerivedData(int value) : Data{ value } { }

    std::string getName() const { 
        return "DerivedData"; 
    }

    int getValueDoubled() const { 
        return _value * 2; 
    }
};
DerivedData dd{ 5 };
Data d = dd;
Data& rd = dd;
cout << rd.getName() << endl;

This code will output "Data", but why?

Yun
  • 3,056
  • 6
  • 9
  • 28
Ali
  • 17
  • 4
  • 1
    Does this answer your question? [Why do we need virtual functions in C++?](https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c) – nvoigt Oct 02 '21 at 07:46
  • 1
    You have forgotten that `virtual` is needed for functions to be polymorphic. – Some programmer dude Oct 02 '21 at 07:46
  • As a general tip: For each function you want to override in a child class, add the `override` identifier to mark it as such, and the compiler will tell you if the function actually overrides or not. As in `class DerivedData : public Data { public: ...; std::string getName() override const { return "DerivedData"; } ... };` – Some programmer dude Oct 02 '21 at 08:51

1 Answers1

2

You are not using virtual so it is kinda redefinition of the parent function which you think is polymorphsim but it is not.

When it execute this line of code Data& rd = dd; you had expected to be printed DerviedData but this did not happen because your function was not virtual, and base class do not know you are overriding the getName method in derived class.

So to fix this issue need to declare your function virtual:

virtual std::string getName() const { return "Data"; } //Data

And in DerivedData:

std::string getName() const override { return "DerivedData"; } //DerivedData

Now this will behave the way you'd expected.

foragerDev
  • 1,307
  • 1
  • 9
  • 22