If I have a class like this, how should I write the copy constructor?
#include <stringstream>
class MyClass {
std::stringstream strm;
public:
MyClass(const MyClass& other){
//...
}
std::string toString() const { return strm.str(); }
};
std::stringstream has no copy constructor itself, so I can't use an initialiser list like this:
MyClass(const MyClass& other): strm(other.strm) {}
A copy constructor has the following general function prototype: ClassName (const ClassName &old_obj); Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.
To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.
Explanation: The syntax must contain the class name first, followed by the classname as type and &object within parenthesis. Then comes the constructor body.
You can try this:
MyClass(const MyClass& other): strm(other.strm.str()) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With