C++ Constructors Bob Walton, 7/16/96 Given a struct name `foo', constructors may be used to make new foo objects. A constructor may take any number of arguments. Constructors are defined as follows: struct foo { foo ( void ) // Default constructor. { ... } foo ( int x ) // Construct/convert from a { // single int argument. ... } foo ( int x, int y ) // Construct from two // int arguments. { ... } ... } A constructor with a single argument can be thought of as a conversion operator. Thus if there is a constructor for foo that takes a single int argument, it will be used for statements such as: foo x = 5; ... foo ( 5 ) ... The default constructor is the one with no arguments. It is called to make a new foo by statements such as: foo x; There is no return type for a constructor, not even void. If you define no constructors, the default constructor is defined for you. If you define any constructors, you must define a default constructor (one with no arguments) if you want to declare any variables without giving values. Note the statements: foo x = 5; foo x ( 5 ); do the same thing in C++. You can apply a constructor of two arguments as in foo x ( 5, 6 ); A constructor is a member function. Inside a constructor, there is a current object pointed at by the magic name `this'. Thus in the above foo constructors, `this' has type `foo *' and points at the current object. The following are equivalent: struct foo { int m; // A non-static data member. int n; // A non-static data member. foo ( int x, int y ) { m = x; n = y; } } and struct foo { int m; // A non-static data member. int n; // A non-static data member. foo ( int x, int y ) { this->m = x; this->n = y; } } In fact, whenever you use the name of a non-static data member of a class (struct) in a non-static function member (e.g. constructor) of the class, the name has an implicit `this->' in front of it. Before a constructor is called, memory for the struct (class instance) is allocated, AND constructors are called for all the non-static data members of the struct (class). Typically these are the default constructors. Default constructors for standard C data types do NOTHING. You can define a default constructor that does nothing, as in foo ( void ) {}