CIS 3142 — Default Operations for a Class

CISC 3142
Programming Paradigms in C++
Default Operations for a Class

Overview

When a class is defined, several operations are provided — automatically and implicitly — by the compiler. This is done for several reasons:

The Core Concept Behind Providing Default Operations

In essence — within the context of initialization, copying, moving, and cleanup — and in the absence of an explicit function provided by the class designer, the compiler attempts to do the 'right thing', i.e., what would be expected, i.e., at the very least mimic what would happen with a fundamental type, and if possible go beyond that depending on the nature of the data members (e.g. class object with their own constructors, copy constructors, etc)..

A Preliminary Word About Constructors

Constructors can be thought of falling into two distinct categories: application-specific and application-independent: Finally, remember that the whole point of the constructor is to initialize the object so that it is in a valid state vis-a-vis the semantics of the class (Stroustrup speaks of the constructor enforcing or establishing an invariant). The set of constructors comprises the ONLY way a user can initialize an object of the class; i.e., if the Rational class only supplied the 2-arg constructor, one could not create Rational with only a numerator, or NO arguments, regardless of whether such initialization would make sense. In other words, the only legal initialization of the object is what the constructor designers offer.

The Default Operations

First a clarifying note … the term default operation is not the same as default constructor: Again, the idea of a default operation is that it is something the compiler can provide on its own — usually (but not always) with correct semantics.

Note: for this discussion, we're assuming a class C.

Default Constructor (C())

Copy Constructor (C(const C &))

Assignment Operator (C & operator =(const C &))

Destructor

Again, any of the above functions that are supplied by the class designer (and they usually come as a group), suppress the corresponding compiler-supplied default.

Code Used in this Lecture