Reputation: 17
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?
Upvotes: 1
Views: 91
Reputation: 11
In the DerivedData class, you're not correctly calling the parent constructor. you will be calling the constructor as "DerivedData(int value) : Data(value) {}".This small error in the syntax is causing the constructor of the Data class to not be called correctly when you create an object of the DerivedData class. As a result, the _name variable in the Data class remains uninitialized and contains a garbage value.
To fix this issue, you need to modify the DerivedData class definition as follows:
#include <iostream>
#include <string>
using namespace std;
class Data {
protected:
int _value{};
public:
Data(int value) : _value{ value } {}
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) {}
string getName() const {
return "DerivedData";
}
int getValueDoubled() const {
return _value * 2;
}
};
int main() {
DerivedData dd(10);
cout << dd.getName() << endl; // This will output "DerivedData"
return 0;
}
Now the output will show DerivedData
Upvotes: 1
Reputation: 1409
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.
Upvotes: 2