Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A constructor is a function with the same name as the class. The main purpose of a constructor is to initialize member variables of a newly-created object to some default values. It might also call other initialization functions.<br> Just like other functions in C++, constructors can be overloaded. (An overloaded function is a new version of an existing function with different arguments). For example, consider the following <code>Point</code> class with three constructors:</p> <pre><code>class Point { public: Point() : x_(0), y_(0) { } Point(int x, int y) : x_(x), y_(y) { } Point(const Point&amp; p) : x_(p.x), y_(p.y) { } private: int x_; int y_; }; </code></pre> <p>The first constructor initializes the co-ordinates to zero, while the second allows the user to specify their default values:</p> <pre><code>void create_and_destroy_points () { Point p1; // =&gt; x_ = 0, y_ = 0 Point p2(100, 200); // x_ = 100, y_ = 200 } </code></pre> <p>When declared that way, those <code>Point</code> objects are allocated on the <em>stack</em>. That means the memory allocated to them will be automatically released when the <code>create_and_destroy_points</code> function returns. In other words, <code>p1</code> and <code>p2</code> are of no use outside the function.<br> Objects can also be allocated on the <em>heap</em>. This allocates the objects at run time, and they can then survive across various function calls. They are allocated with the <code>new</code> keyword and continue to live until they are deallocated with <code>delete</code>. Failing to delete a heap allocated object after its use will lead to a <em>memory leak</em>.</p> <pre><code>Point* create_point () { Point* p = new Point(100, 200); return p; } Point* p = create_point(); // use p delete p; </code></pre> <p>The third constructor is a <em>copy constructor</em>. It is invoked when a new object is constructed by copying another object:</p> <pre><code>Point p1; Point p2 = p1; // calls the copy constructor for p2 with p1 as argument. Point p3(p1); // alternate syntax </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload