Can we say that the constructor creates objects?

Someone told me that the constructor creates objects. But on the internet, I was looking for a constructor to execute when objects are created. Can you explain about this? I am new to C ++

+3


source to share


3 answers


In C ++, a constructor is a special type of member function of a class that is executed when an object of that class is created.

Constructors are commonly used to initialize the member variables of a class to their appropriate default values, or so that the user can easily initialize these member variables to whatever values ​​they want.

So when you call a constructor, you have an object already created, so the constructor does not create an object or create object variables, it is simply used to initialize variables inside that object (or to do some task you want before using the object).

EDIT: Also:

The constructor does its work in the following order:

  • It calls the base class and member constructors in the order of declaration.
  • If the class is derived from virtual base classes, it initializes the object's virtual base pointers.
  • If the class has or inherits virtual functions, initializes the object with virtual function pointers. Virtual function pointers point to the class virtual function table to properly bind virtual function calls to code.
  • It executes any code in its function body.


Check out these links for more information:

http://www.learncpp.com/cpp-tutorial/85-constructors/

https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx

https://isocpp.org/wiki/faq/ctors

+7


source


class a{int a = 0;int b = 0;} a obj = new a();

in the above code your obj is created the memory for obj is allocated on the stack and then the constructor code is executed



+2


source


English is an imprecise language and intuition is well served by masking small details when they don't matter.

If you have a task to "create a (default initialized) object of type T

", then you do it with T()

. Or other options depending on the need (for example new T()

).

It is literally correct to say that calling a constructor creates a (temporary) object. The fact that the magic happens between the site where you call the constructor and where you go into the constructor is a detail that is not worth paying attention to.

Also: I believe "create an object" is also a technical term defined by the C ++ standard, which may or may not conflict with the intuitive notion of "create". I do not have a reference to determine if this object is "created" by this technical definition before you enter the constructor or after the constructor succeeds.

-1


source







All Articles