Constructors
Constructors
This domain tests special member functions that initialize objects. A constructor has the same name as its class, has no return type (not even void), and is called automatically when an object is created. It can be overloaded: default (no arguments), parameterized and copy constructors are common. A destructor, written with a tilde before the class name, has no arguments and no return type and runs when an object's lifetime ends.
Rules
- If no constructor is declared, the compiler supplies a default constructor; declaring any constructor suppresses that implicit default.
- A parameterized constructor initializes with supplied values:
Point p(3,4);. - A copy constructor
Point(const Point &p)initializes a new object from an existing one; it is called on copy initialization and when passing by value. - Constructors can use an initializer list:
Point(int a, int b) : x(a), y(b) { }.
Worked example
class Point { int x, y; public: Point(int a, int b) { x=a; y=b; } int sum() { return x+y; } };
Point p(3,4); cout << p.sum(); prints 7. The constructor runs at the declaration of p, so no separate initialization call is needed. Point q; would fail because the compiler-generated default constructor is suppressed once the parameterized constructor exists.
Traps
Writing void Point() is not a constructor. A constructor cannot be virtual. A destructor takes no parameters and cannot be overloaded. Do not confuse a copy constructor with assignment. The implicit default constructor disappears after you declare another constructor.