Is there a difference between copy initialization and direct initialization in C++?


The Copy initialization can be done using the concept of copy constructor. As we know that the constructors are used to initialize the objects. We can create our copy constructor to make a copy of some other object, or in other words, initialize current object with the value of another object. On the other hand, the direct initialization can be done using assignment operation.

The main difference between these two types of initialization is that the copy initialization creates a separate memory block for the new object. But the direct initialization does not make new memory space. It uses reference variable to point to the previous memory block.

Copy Constructor Or Copy Initialization (Syntax)

classname (const classname &obj) {
   // body of constructor
}

Direct Initialization or Assignment Operator (Syntax)

classname Ob1, Ob2;
Ob2 = Ob1;

Let us see the detailed differences between Copy initialization and Direct initialization.

Copy initializationDirect Initialization
The Copy initialization is basically an overloaded constructorDirect initialization can be done using assignment operator.
This initializes the new object with an already existing objectThis assigns the value of one object to another object both of which are already exists.
Copy initialization is used when a new object is created with some existing objectThis is used when we want to assign existing object to new object.
Both the objects uses separate memory locations.One memory location is used but different reference variables are pointing to the same location.
If no copy constructor is defined in the class, the compiler provides one.If the assignment operator is not overloaded then bitwise copy will be made

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements