Software & Finance





C++ FAQ - Difference Between Assignment and Initialization





 

If an assignment takes place at the time of definition, then it is called initialization.

 

Example for a Variable

int m; // it is called both declaration and definition

m = 10; // it is called assignment

 

int m = 10; // All three takes place in a single line - declaration and definition and initialization

Example for a class

class Shape

{

private:

    int m,n;

public:

    Shape() : m(0), n(0) { }

    Shape(int a, int b) : m(a), n(b) { }

 

    Shape(const Shape& other)

    {

        this->m = other.m;

        this->n = other.n;

    }

 

    const Shape& operator = (const Shape& other)

    {

        this->m = other.m;

        this->n = other.n;

        return *this;

    }

   

};

 

void TestFunction()

{

    Shape a(10, 20); // calls the parameterized constructor

    Shape b = a; // called initialization and calls the copy constructor

 

    Shape c(b); // called initialization and calls the copy constructor

 

    Shape d;

    d = c; // called assignment and calls the assignment operator

}