C++

C++ TutorialBasic input/output in c++C++ AlignmentC++ Argument Dependent Name LookupC++ Arithmitic MetaprogrammingC++ ArraysC++ Atomic TypesC++ AttributesC++ autoC++ Basic Type KeywordsC++ Bit fieldsC++ Bit ManipulationC++ Bit OperatorsC++ Build SystemsC++ C incompatibilitiesC++ C++11 Memory ModelC++ Callable ObjectsC++ Classes/StructuresC++ Client server examplesC++ Common compile/linker errors (GCC)C++ Compiling and BuildingC++ Concurrency with OpenMPC++ Const CorrectnessC++ const keywordC++ Constant class member functionsC++ constexprC++ ContainersC++ Copy ElisionC++ Copying vs AssignmentC++ Curiously Recurring Template Pattern (CRTP)C++ Date and time using chrono headerC++ Debugging and Debug-prevention Tools & TechniquesC++ decltypeC++ Digit separatorsC++ EnumerationC++ ExceptionsC++ Explicit type conversionsC++ Expression templatesC++ File I/OC++ Floating Point ArithmeticC++ Flow ControlC++ Fold ExpressionsC++ Friend keywordC++ function call by value vs. call by referenceC++ Function OverloadingC++ Function Template OverloadingC++ Futures and PromisesC++ Header FilesC++ Implementation-defined behaviorC++ Inline functionsC++ Inline variablesC++ IterationC++ IteratorsC++ KeywordsC++ LambdasC++ Layout of object typesC++ Linkage specificationsC++ LiteralsC++ LoopsC++ Memory managementC++ MetaprogrammingC++ Move SemanticsC++ mutable keywordC++ MutexesC++ NamespacesC++ Non-Static Member FunctionsC++ One Definition Rule (ODR)C++ Operator OverloadingC++ operator precedenceC++ OptimizationC++ Overload resolutionC++ Parameter packsC++ Perfect ForwardingC++ Pimpl IdiomC++ PointersC++ Pointers to membersC++ PolymorphismC++ PreprocessorC++ ProfilingC++ RAII: Resource Acquisition Is InitializationC++ Random number generationC++ Recursive MutexC++ Refactoring TechniquesC++ ReferencesC++ Regular expressionsC++ Resource ManagementC++ Return Type CovarianceC++ Returning several values from a functionC++ RTTI: Run-Time Type InformationC++ Scopes



C++ Copying vs Assignment

From WikiOD

Syntax[edit | edit source]

  • Copy Constructor
  • MyClass( const MyClass& other );
  • MyClass( MyClass& other );
  • MyClass( volatile const MyClass& other );
  • MyClass( volatile MyClass& other );
  • Assignment Constructor
  • MyClass& operator=( const MyClass& rhs );
  • MyClass& operator=( MyClass& rhs );
  • MyClass& operator=( MyClass rhs );
  • const MyClass& operator=( const MyClass& rhs );
  • const MyClass& operator=( MyClass& rhs );
  • const MyClass& operator=( MyClass rhs );
  • MyClass operator=( const MyClass& rhs );
  • MyClass operator=( MyClass& rhs );
  • MyClass operator=( MyClass rhs );

Parameters[edit | edit source]

rhs Right Hand Side of the equality for both copy and assignment constructors. For example the assignment constructor : MyClass operator=( MyClass& rhs );
Placeholder Placeholder

Remarks[edit | edit source]

Other Good Resources for further research :

What's the difference between assignment operator and copy constructor?

assignment operator vs. copy constructor C++

GeeksForGeeks

C++ Articles

Assignment Operator[edit | edit source]

The Assignment Operator is when you replace the data with an already existing(previously initialized) object with some other object's data. Lets take this as an example:

// Assignment Operator
#include <iostream>
#include <string>

using std::cout;
using std::endl;

class Foo
{
  public:
    Foo(int data)
    {
        this->data = data;    
    }
    ~Foo(){};
    Foo& operator=(const Foo& rhs)
    {
            data = rhs.data; 
            return *this;
    }

    int data;
};

int main()
{
   Foo foo(2); //Foo(int data) called
   Foo foo2(42);
   foo = foo2; // Assignment Operator Called
   cout << foo.data << endl; //Prints 42
}

You can see here I call the assignment operator when I already initialized the foo object. Then later I assign foo2 to foo . All the changes to appear when you call that equal sign operator is defined in your operator= function. You can see a runnable output here: http://cpp.sh/3qtbm

Copy Constructor[edit | edit source]

Copy constructor on the other hand , is the complete opposite of the Assignment Constructor. This time, it is used to initialize an already nonexistent(or non-previously initialized) object. This means it copies all the data from the object you are assigning it to , without actually initializing the object that is being copied onto. Now Let's take a look at the same code as before but modify the assignment constructor to be a copy constructor :

// Copy Constructor
#include <iostream>
#include <string>

using std::cout;
using std::endl;

class Foo
{
  public:
    Foo(int data)
    {
        this->data = data;    
    }
    ~Foo(){};
    Foo(const Foo& rhs)
    {
            data = rhs.data; 
    }

    int data;
};

int main()
{
   Foo foo(2); //Foo(int data) called
   Foo foo2 = foo; // Copy Constructor called
   cout << foo2.data << endl;
}

You can see here Foo foo2 = foo; in the main function I immediately assign the object before actually initializing it, which as said before means it's a copy constructor. And notice that I didn't need to pass the parameter int for the foo2 object since I automatically pulled the previous data from the object foo. Here is an example output : http://cpp.sh/5iu7

Copy Constructor Vs Assignment Constructor[edit | edit source]

Ok we have briefly looked over what the copy constructor and assignment constructor are above and gave examples of each now let's see both of them in the same code. This code will be similar as above two. Let's take this :

// Copy vs Assignment Constructor
#include <iostream>
#include <string>

using std::cout;
using std::endl;

class Foo
{
  public:
    Foo(int data)
    {
        this->data = data;    
    }
    ~Foo(){};
    Foo(const Foo& rhs)
    {
            data = rhs.data; 
    }

    Foo& operator=(const Foo& rhs)
    {
        data = rhs.data; 
        return *this;
    }

    int data;
};

int main()
{
   Foo foo(2); //Foo(int data) / Normal Constructor called
   Foo foo2 = foo; //Copy Constructor Called
   cout << foo2.data << endl;

   Foo foo3(42);
   foo3=foo; //Assignment Constructor Called
   cout << foo3.data << endl;
}

Output:

2
2

Here you can see we first call the copy constructor by executing the line Foo foo2 = foo; . Since we didn't initialize it previously. And then next we call the assignment operator on foo3 since it was already initialized foo3=foo;

Credit:Stack_Overflow_Documentation