In contrast to java, C++ does not offer a predefined "toString"-method that is called implicitly whenever a string representation of an object is requested. So your toString
-method will have to be called explicitly then.
In C++, however, something similar is available by overriding the operator <<
for streams. Thereby, you can directly "send" the object contents to a stream (without the need to store everything in an intermediate string object). And you can use the same code to populate a string to be returned by a toString
method, too:
struct Student {
std::string name;
int age;
double finalGrade;
std::string toString() const;
};
ostream& operator << (ostream &os, const Student &s) {
return (os << "Name: " << s.name << "\n Age: " << s.age << "\n Final Grade: " << s.finalGrade << std::endl);
}
std::string Student::toString() const {
stringstream ss;
ss << (*this);
return ss.str();
}
int main() {
Student stud { "john baker", 25, 1.2 };
std::cout << "stud directly: " << stud << endl;
std::string studStr = stud.toString();
std::cout << "stud toString:" << studStr << endl;
}