-2

My question is a basic one. Since std::strings are arrays am I handling them correctly in my copy constructor?

class json{
    private:
        std::string _objectContents;
        std::string _regComments;

        bool _isJson;
        int numElements;

    public:
        json(const json&);

        ...
};

json::json(const json& source){
    _objectContents = source._objectContents;
    _regComments = source._regComments;
    _isJson = source._isJson;
    _numElements = source.numElements;
}

*edited remove pointer and changed to array in question.

user249806
  • 299
  • 1
  • 3
  • 14

2 Answers2

3

am i setting my std::strings correct

You are setting them correct but it can be better.

  1. You don't need an explicitly defined copy constructor. The one generated by the compiler will do the right thing for the member variables you have.

  2. If you must explicitly define the copy constructor, initialize the members using initialization list. Change the implementation to:

    json::json(const json& source) : 
       _objectContents(source._objectContents),
       _regComments(source._regComments),
       _isJson(source._isJson),
       _numElements(source.numElements)
    {
    }
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • thanks! i keep getting an error when i was using the string constructor inside the method. Your answer makes perfect sense. I see now that I do not need to explicitly do this for each string, also. – user249806 Jan 20 '15 at 17:50
2

The string assignment operator implicitly copies(or moves) the underlying character array from the source string to the destination string(a deep copy) rather than copying just their pointers(a shallow copy).
so Yes you the code is correct.
Since all of your member variables can be copied using an assignment operator you do not need to explicitly declare a copy constructor.
Though you would have needed a copy constructor had you used a C style string. In which case the default copy constructor does a shallow copy while you may be intending to do a deep copy.