Dela via


Constructors (C++)

A member function with the same name as its class is a constructor function. Constructors cannot return values. Specifying a constructor with a return type is an error, as is taking the address of a constructor.

If a class has a constructor, each object of that type is initialized with the constructor prior to use in a program. (For more information about initialization, see Initialization Using Special Member Functions.)

Constructors are called at the point an object is created. Objects are created as:

  • Global (file-scoped or externally linked) objects.

  • Local objects, within a function or smaller enclosing block.

  • Dynamic objects, using the new operator. The new operator allocates an object on the program heap or "free store."

  • Temporary objects created by explicitly calling a constructor. (For more information, see Temporary Objects.)

  • Temporary objects created implicitly by the compiler. (For more information, see Temporary Objects.)

  • Data members of another class. Creating objects of class type, where the class type is composed of other class-type variables, causes each object in the class to be created.

  • Base class subobject of a class. Creating objects of derived class type causes the base class components to be created.

Example

// constructors.cpp
// compile with: /c
class MyClass {
public:
   MyClass(){}
   MyClass(int i) : m_i(i) {}

private:
   int m_i;
};

See Also

Reference

Special Member Functions