Difficulty Level: Rookie
Consider the following C++ program.
#include<iostream> #include<stdio.h> using namespace std; class Test { public: Test() {} Test(const Test &t;) { cout<<"Copy constructor called "<<endl; } Test& operator = (const Test &t;) { cout<<"Assignment operator called "<<endl; return *this; } }; // Driver code int main() { Test t1, t2; t2 = t1; Test t3 = t1; getchar(); return 0; } |
chevron_right
filter_none
Output:
Assignment operator called
Copy constructor called
Copy constructor is called when a new object is created from an existing object, as a copy of the existing object (see this G-Fact). And assignment operator is called when an already initialized object is assigned a new value from another existing object.
t2 = t1; // calls assignment operator, same as "t2.operator=(t1);" Test t3 = t1; // calls copy constructor, same as "Test t3(t1);" |
chevron_right
filter_none
References:
http://en.wikipedia.org/wiki/Copy_constructor
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Self assignment check in assignment operator
- When should we write our own assignment operator in C++?
- Is assignment operator inherited?
- Default Assignment Operator and References
- Copy Constructor in C++
- When should we write our own copy constructor?
- When is copy constructor called?
- Why copy constructor argument should be const in C++?
- Advanced C++ | Virtual Copy Constructor
- Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backwards()
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Operator Overloading '<<' and '>>' operator in a linked list class
- Constructor Overloading in C++
- Can a constructor be private in C++ ?
- Constructor Delegation in C++
- What is conversion constructor in C++?
- Passing a vector to constructor in C++
- Dynamic Constructor in C++ with Examples
- Difference Between Constructor and Destructor in C++
- Advanced C++ | Virtual Constructor

