Question

I looked through different thread and I have a hard time understanding how to utilize copy constructor.

If I want to manipulate my class, but I need to have original values to do so, I have to create a copy.

    class object {
           public:
           int member[5][5];

           object(object&); <-- how do we create a copy here?

           void manipulate() {
             <<-- how do I call it here?
           }
};

I've been trying different things such as object copy = object(object&) but it does not work.

Was it helpful?

Solution

object(object&); <-- how do we create a copy here?

One simple way is to omit the declaration, and let C++ compiler do it for you. Since your object does not allocate resources in its constructor's body, C++ can handle creating the copy constructor for you.

<<-- how do I call it here?

Like this:

object copy(*this);
... // Manipulate it here

OTHER TIPS

object( const object &obj )
{
   for ( size_t i = 0; i < 5; i++ )
   {
      for ( int j = 0; j < 5; j++ )
      {
         member[i][j] = rhs.member[i][j];
      }
   }
}

Or you can write simply

object( const object &obj ) = default;

because your copy constructor does not do something special.

As for its using then you may use it the following way

object one;
onject two( one );

or

object one;
onject two = one;

or even as

object one;
onject two { one };

or

object one;
onject two = { one };

Also take into account that if you explicitly defined the copy constructor then you should explicitly define the default constructor if you need to have it.

A copy constructor is usually created because you cannot use the one generated by the compiler. In such a case, you will usually copy each member one by one.

For example (written on the fly - not sure if it would even compile with errors/warnings)

class A
{
public:
    A();
    A(const A& src)
    {
        m_array = (char*)new char[src.m_arraySize];
        memcpy(m_array, src.m_array, src.m_arraySize);
        m_arraySize = src.m_arraySize;
    }
private:
    char* m_array;
    int m_arraySize;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top