Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a copy constructor for my class which has a std::stringstream member?

Tags:

c++

stl

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) {}
like image 644
quamrana Avatar asked Mar 30 '11 11:03

quamrana


People also ask

How do you create a copy constructor for a class?

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.

How do you include a Stringstream in C++?

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”.

What is the right way to declare a copy constructor of a class if the name of the class is Myclass Mcq?

Explanation: The syntax must contain the class name first, followed by the classname as type and &object within parenthesis. Then comes the constructor body.


1 Answers

You can try this:

MyClass(const MyClass& other): strm(other.strm.str()) {}
like image 103
ognian Avatar answered Oct 02 '22 16:10

ognian