Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why constructor is called only once?

Tags:

c++

Consider the below program:

class A {     public:     A(int i)     {             cout<<"Called"<<endl;     } };  int main() {     vector<A> v(5,A(1));     return 0; }        

I am getting the output: http://ideone.com/81XO6

 Called 

Why the constructor gets called only once even if we are constructing 5 objects?
How vector is internally handled by the compiler?

like image 447
Green goblin Avatar asked Jul 22 '12 06:07

Green goblin


People also ask

Is constructor called once?

A constructor is called every time the component is mounted, not only once.

Can we call constructor more than once?

Constructors are called only once at the time of the creation of the object.

How many times is a constructor called?

Constructors are never called explicitly. Constructors never return any value.

Can we call constructor twice in Java?

No, there is no way to do this. Even at the JVM bytecode level, a chain of <init> methods (constructors) can be called at most once on any given object.


2 Answers

Your class has two constructors and you are watching only one of them. std::vector creates its elements by copy-constructing them from the original element you supplied. For that purpose, the copy-constructor of class A is called 5 times in your example.

The copy-constructor for A in your example is implicitly declared and defined by the compiler. If you so desire, you can declare and define it yourself. If you print something from it, you will see that it is called at least 5 times.

like image 108
AnT Avatar answered Oct 13 '22 07:10

AnT


It gets called once since the line

vector<A> v(5,A(1));  

will call the constructor and the line becomes vector v(5,X);

where X is the object constructed after calling the constructor.

After that the copy constructor is used.

Try adding

A(const &A); 

To the class declaration to verify this.

like image 23
Ed Heal Avatar answered Oct 13 '22 05:10

Ed Heal