why is cout giving an error? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

why is cout giving an error?

I am trying to write a code for making copy constructor in C++. I have made a function print() that basically prints the data members of my class String. But whenever I call that function in my constructor body, my compiler gives an error saying " no match for 'operator <<'. I don't understand why that is the case. Could someone kindly help? Thanks!! #include <cstdlib> using namespace std ; class String { char *str_ ; int len_ ; public: void print() // print function { cout<<"str_ = "<<str_<<"\t"<<"len_ = "<<len_<<endl ; } String(const char* str): str_(strdup(str)), len_(strlen(str_)) // constructor { cout<<"Ctor called "<< print()<<endl ; } String() {} // default constructor String(const String&obj): str_(strdup(obj.str_)), len_(obj.len_) // copy constructor { cout<<"Copy Ctor called :"<<print()<<endl ; } String& operator = (String& obj) // operator oveloading { free(str_) ; str_ = strdup(obj.str_) ; len_ = obj.len_ ; return *this ; } ~String() // destructor { free(str_); cout<<"Dtor called " ; <<print()<<endl ; } }; int main() { String s1("yusha"), s2= "arif" ;

30th Mar 2019, 8:00 AM
Yusha Arif
Yusha Arif - avatar
3 Answers
+ 5
Seniru Pasan is right. Your print returns nothing. You can't cout something of no type. I would suggest not using cout and just do print(), instead of having print return a string.
30th Mar 2019, 8:32 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
I m not a pro in c++. But after looking your code I can conclude something. So first, your print method is a void function. According to my experience voids are not allowed in instances like this. So the best way to fix this is changing your print function. It should look like this, String print() { return "str_ =" + str_ + "\tlen_ = "+len_; } Otherwise call that method outside the cout
30th Mar 2019, 8:15 AM
Seniru
Seniru - avatar
+ 1
Also, ignoring some other mistakes you have, like uninitialized variables in the default constructor, if you want to output the String class with cout then you should overload the << operator for std::ostream. https://docs.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes?view=vs-2017
30th Mar 2019, 9:35 AM
Dennis
Dennis - avatar