Wednesday, September 1, 2010

Constructors in c++

When an object of a class is created, C++ calls the constructor for that class. If no constructor is defined, C++ invokes a default constructor, which allocates memory for the object, but doesn't initialize it.

Why you should define a constructor

Uninitialized member fields have garbage in them. This creates the possibility of a serious bug (eg, an uninitialized pointer, illegal values, inconsistent values, ...).

Declaring a constructor

A constructor is similar to a function, but with the following differences.
  • No return type.
  • No return statement.
Example [extracts from three different files].
//=== point/point.h =================================================
#ifndef POINT_H
#define POINT_H
class Point {
Point(); // parameterless default constructor
Point(int new_x, int new_y); // constructor with parameters
int getX();
int getY();
int x;
int y;
Here is part of the implementation file.
//=== point/point.cpp ==============================================
. . .
Point::Point() { // default constructor
x = 0;
y = 0;

Point::Point(int new_x, int new_y) { // constructor
x = new_x;
y = new_y;
. . .
And here is part of a file that uses the Point class.
//=== point/main.cpp ==============================================
. . .
Point p; // calls our default constructor
Point q(10,20); // calls constructor with parameters
Point* r = new Point(); // calls default constructor
Point s = p; // our default constructor not called.
. . .

No comments:

Post a Comment