I ran into an issue google could not solve. Why is that cout works for an int object but not a string object in the following program?
#include<iostream>
using namespace std;
class MyClass {
string val;
public:
//Normal constructor.
MyClass(string i) {
val= i;
cout << "Inside normal constructor\n";
}
//Copy constructor
MyClass(const MyClass &o) {
val = o.val;
cout << "Inside copy constructor.\n";
}
string getval() {return val; }
};
void display(MyClass ob)
{
cout << ob.getval() << endl; //works for int but not strings
}
int main()
{
MyClass a("Hello");
display(a);
return 0;
}
You must include the
stringheader to get the overloadedoperator<<.Also you might want to return a
const string&instead of astringfromgetval, change your constructor to accept aconst string&instead of astring, and changedisplayto accept aconst MyClass& obto avoid needless copying.