#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class MyInt
{
int* a;
int length;
public:
MyInt();
explicit MyInt(int length);
MyInt(const MyInt&);
MyInt& operator=(const MyInt&);
~MyInt();
};
// MyInt.cpp
MyInt::MyInt():a(NULL)
{
std::cout <<"Default Constructor"<<std::endl;
}
MyInt::MyInt(int size):length(size),a(new int[size])
{
std::cout<<"Parameterized Constructor"<<std::endl;
}
MyInt::MyInt(const MyInt& obj)
{
std::cout<<"Copy Constructor called"<<std::endl;
length = obj.length;
a = new int[length];
}
MyInt& MyInt::operator=(const MyInt& obj)
{
if(this != &obj)
{
if(NULL != a)
delete [] a;
length = obj.length;
a = new int[length];
}
return *this;
}
void printVector(std::vector<MyInt>& v1)
{
// for(int* num : v1)
//std:cout << num <<" ";
//std::cout<<endl;
}
MyInt::~MyInt()
{
if(NULL != a)
delete [] a;
}
int main()
{
std::vector<MyInt> v1,v2;
for(int i = 0 ; i < 5 ; ++i)
{
// v1.push_back(MyInt(i+1));
MyInt obj(i+1);
v1.push_back(obj);
}
//Delete the heap before calling vector clear
return 0;
}
The outpupt I expect is:
Parameterized Constructor
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Parameterized Constructor
Copy Constructor called
The actual output is
Parameterized Constructor
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Copy Constructor called
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Copy Constructor called
Copy Constructor called
Copy Constructor called
Copy Constructor called
What is the hidden truth for this, Could anyone help me better understand this?