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++
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:
- It calls 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, 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.
- 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With