C++ Concept Map

Constructor functions

Every class has at least one constructor function, even when none is declared. The job of a constructor functions is to allocate space for an object, and to set its initial internal state by assigning values to some or all of its data members.

There may be any number of different constructors, since function members may be overloaded. However, all must have the same name as the class that contains them, and none may have a return type. The constructor which takes no arguments is the default constructor. If no constructor is declared at all, the compiler will create a standard default constructor that allocates space but does no initialization.

A special constructor is the copy constructor which takes one object of the same type as an argument through a reference parameter, and copies it to create a new one. Below are some examples:

class C {
private:
  int x;
public:
     C() { x = 0; }				// the default constructor
     C(int xx) { x = xx; }	// an overloaded constructor
     C(C &orig) { x = orig.x; }	// the copy constructor	
};

Please mail any corrections and/or suggestions to Roger Hartley at
rth@cs.nmsu.edu

Copyright © 2003 Roger Hartley