I am creating a vector with class objects as below.
#include <iostream>
#include <vector>
using namespace std;
class myclass
{
public:
myclass(int a = 0) : x(a)
{
cout << "myclass constructor" << endl;
}
int x;
};
int main()
{
vector<myclass> v(2, 1);
cout << "size : " << v.size() << endl;
cout << v[0].x << endl;
cout << v[1].x << endl;
}
As per my understanding 2 objects will be created with value '1'. But constructor is getting called only once. When I print the values of the objects, both objects are printing x values as '1'. Below is the output.
myclass constructor
size : 2
1
1
I couldn't understand why constructor is not getting called twice.
1) Is copy constructor getting called here?
I tried to write copy constructor in the class as below
myclass(myclass &obj)
{
x = obj.x;
cout << "Copy Constructor" << endl;
}
but it is throwing following errors while compiling.
vector.cpp:15:9: note: no known conversion for argument 1 from ‘const myclass’ to ‘myclass&’ vector.cpp:10:9: note: myclass::myclass(int) myclass(int a = 0) : x(a) ^ vector.cpp:10:9: note: no known conversion for argument 1 from ‘const myclass’ to ‘int’
2) Is there any rule that we should not define copy constructor if we are going to create vector of objects of that class? What are the rules we should follow if we are creating vector with user defined class objects?
myclass(const myclass &obj). Theconstpart is quite important.