S
S
sddvxd2018-03-24 22:48:42
C++ / C#
sddvxd, 2018-03-24 22:48:42

What happens to an object if its constructors are called multiple times?

Hello

//source.cpp
CClass::CClass(){} //Первый конструктор
CClass::CClass(int a){} //Второй конструктор

//main.cpp

CClass obj; //вызываем первый конструктор

obj = 1; //вызываем второй конструктор

What happens to the object when we call the constructor a second time? Is the code of the second constructor simply executed, or is the object re-created?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Moseychuk, 2018-03-24
@sddvxd

The second entry is not a constructor call, but an assignment operator.
First, a new temporary object is created through the second constructor (because the constructor is implicit, an implicit conversion from int to CClass is allowed). The assignment operator is then called on the first object with the temporary object as a parameter.
In C++, without complex manipulations, it is impossible to call a constructor a second time.
In fact your code is equivalent to this:

CClass obj(); // на самом деле так писать нельзя, это не вызов конструктора а объявление функции

obj = CClass(1);

W
Wexter, 2018-03-24
@Wexter

Who said that the second time the constructor is called?
The second time you call the = operator, if you have it redefined. Otherwise, the compiler will hint at your unsuitability

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question