0 votes
in C Plus Plus by
What is a Constructor and how is it called?

1 Answer

0 votes
by
Constructor is a member function of the class having the same name as the class. It is mainly used for initializing the members of the class. By default constructors are public.

There are two ways in which the constructors are called:

Implicitly: Constructors are implicitly called by the compiler when an object of the class is created. This creates an object on a Stack.

Explicit Calling: When the object of a class is created using new, constructors are called explicitly. This usually creates an object on a Heap.

Example:

class A{

 int x; int y;

 public A() : x(0) , y(0) {} //default (no argument) constructor

 };

 main()

 {

                    A Myobj; // Implicit Constructor call. In order to allocate memory on stack,

                                    //the default constructor is implicitly called.

                  A * pPoint = new A(); // Explicit Constructor call. In order to allocate

                                                  //memory on HEAP we call the default constructor.

 }

Related questions

0 votes
asked Jun 23, 2019 in PHP by SakshiSharma
+1 vote
asked Jul 16, 2019 in C Plus Plus by Indian
...