Share via


Class-Type Objects

An object is a typed region of storage in the execution environment; in addition to retaining state information, it also defines behavior. Class-type objects are defined using class-name. Consider the following code fragment:

// class_type_objects.cpp
class Account
{
public:
   Account()   // Default constructor
   {
   }
   Account( double );   // Construct from double.
   double& Deposit( double );
   double& Withdraw( double, int );
};

int main()
{
   Account CheckingAccount;   // Define object of class type.
}

The preceding code declares a class (a new type) called Account. It then uses this new type to define an object called CheckingAccount.

The following operations are defined by C++ for objects of class type:

  • Assignment. One object can be assigned to another. The default behavior for this operation is a memberwise copy. This behavior can be modified by supplying a user-defined assignment operator.

  • Initialization using copy constructors.

The following are examples of initialization using user-defined copy constructors:

  • Explicit initialization of an object. For example:

    Point myPoint = thatPoint;
    

    declares myPoint as an object of type Point and initializes it to the value of thatPoint.

  • Initialization caused by passing as an argument. Objects can be passed to functions by value or by reference. If they are passed by value, a copy of each object is passed to the function. The default method for creating the copy is memberwise copy; this can be modified by supplying a user-defined copy constructor (a constructor that takes a single argument of the type "reference to class").

  • Initialization caused by the initialization of return values from functions. Objects can be returned from functions by value or by reference. The default method for returning an object by value is a memberwise copy; this can be modified by supplying a user-defined copy constructor. An object returned by reference (using pointer or reference types) should not be both automatic and local to the called function. If it is, the object referred to by the return value will have gone out of scope before it can be used.

Overloaded Operators explains how to redefine other operators on a class-by-class basis.

See Also

Reference

Overview of Classes