Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we say Constructor Creates Objects?

Someone told me that constructor creates the objects. But on internet I searched that constructor executed when objects created.. Can you explain about this? I'm new to C++

like image 379
Asif Mushtaq Avatar asked Sep 27 '26 19:09

Asif Mushtaq


1 Answers

In C++ a constructor is a special kind of class member function that is executed when an object of that class is instantiated.

Constructors are typically used to initialize member variables of the class to appropriate default values, or to allow the user to easily initialize those member variables to whatever values are desired.

So when you call the constructor you have an already instantiated object, so the constructor doesn't create the object, nor creates the objects variables, it is simply used to initialize the variables inside that object (or to make some task you want to before the object is used).

EDIT: Also:

A constructor performs its work in this order:

  1. It calls base class and member constructors in the order of declaration.
  2. If the class is derived from virtual base classes, it initializes the object's virtual base pointers.
  3. If the class has or inherits virtual functions, it initializes the object's virtual function pointers. Virtual function pointers point to the class's virtual function table to enable correct binding of virtual function calls to code.
  4. It executes any code in its function body.

Check these links for more infos:

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

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

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

like image 152
dnlcrl Avatar answered Sep 29 '26 09:09

dnlcrl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!