Let's play the show and tell, so let's use all the special participants:
#include <iostream> class abc{ public: int a, b; abc() { std::cout << "Default constructor\n"; a = 0; b = 0;} abc(int x) { std::cout << "Int constructor\n"; a = x;} abc(abc const& other): a(other.a), b(other.b) { std::cout << "Copy constructor (" << a << ", " << b << ")\n"; } abc& operator=(abc const& other) { std::cout << "Assignment operator (" << a << ", " << b << ") = (" << other.a << ", " << other.b << ")\n"; a = other.a; b = other.b; return *this; } ~abc() {std::cout << "Destructor Called\n";} }; int main() { abc obj1; std::cout << "OBJ1 " << obj1.a << "..." << obj1.b << "\n"; abc obj2; std::cout << "OBJ2 " << obj2.a << "..." << obj2.b << "\n"; obj2 = 100; std::cout << "OBJ2 " << obj2.a << "\n"; return 0; }
And we get this conclusion :
Default constructor OBJ1 0...0 Default constructor OBJ2 0...0 Int constructor Assignment operator (0, 0) = (100, 0) Destructor Called OBJ2 100 Destructor Called Destructor Called
So, let's reconcile them with string sources:
int main() { abc obj1; // Default constructor std::cout << "OBJ1 " << obj1.a << "..." << obj1.b << "\n"; // OBJ1 0...0 abc obj2; // Default constructor std::cout << "OBJ2 " << obj2.a << "..." << obj2.b << "\n"; // OBJ2 0...0 obj2 = 100; // Int constructor // Assignment operator (0, 0) = (100, 0) // Destructor Called std::cout << "OBJ2 " << obj2.a << "\n"; // OBJ2 100 return 0; // Destructor Called // Destructor Called }
You basically had everything, let's look at surprises.
First surprise: even if obj2 changes the value later abc obj2; it will still call the default constructor at the declaration point.
Second surprise: obj2 = 100 actually means obj2.operator=(abc(100)); , i.e:
- Create a temporary (unnamed)
abc from abc(100) - Assign it to
obj2 - Destroy the temporary before moving on to the next statement
Third surprise: destructors are called at the end of the area, right before the closing bracket } (and yes, after return ). Since you use system("pause") , I assume that you are on Windows => although the luck they cause after the pause is complete, and thus your Windows console disappears in the blink of an eye the moment they appear. You can run the program from a more permanent console or use an additional area:
int main () { {