Having this class:
class A
{
int number;
int number2;
public:
A(int _number):number(_number),number2(0)
{
cout<<"Normal constructor\n";
}
A()
{
cout<<"Default constructor\n";
}
A(const A& source)
{
number = source.number;
number2 = source.number2;
cout<<"Copy constructor\n";
}
A & operator=(const A& source)
{
number = source.number;
number2 = source.number2;
cout<<"Assignment operator\n";
return *this;
}
};
If vector<A> obj {1,2,3}
is created, normal constructor
is called three times because it is not declared as explicit
and therefore it is used as a converting constructor
. Then the copy constructor
is called three times.
- Is there any way a
vector
can be declared and instantiated while skipping the copying operation?
If vector<A> obj_1;
is executed, an empty vector which can hold objects of type A
is created - no constructors called, but the object exists.
- Why there is no constructor called?
- Did I declared the object such as it is fully workable?
From this link:
A copy constructor is used to initialize a previously uninitialized object from some other object's data.
An assignment operator is used to replace the data of a previously initialized object with some other object's data.
Doing obj_1 = obj
, if my obj_1 was previously initialized results in calling the copy constructor
instead of operator=
function inside my class A
as I was expecting?
Also, inside vector
there is already an operator=
function. How can I know when will be called each?
vector<A> obj {1,2,3};
vector<A> obj_1;
obj_1 = obj; // Why copy constructor called instead of function operator= inside my class