Class Structure:
C++ classes have a rich set of functions and operators that allow a designer to provide an expressive and effective language other code uses to invoke class operations. This section explores C++ class structure in detail. Most of that detail you will find in the linked presentation and code examples.
A class declaration declares, and may define, member functions and member state on which the member functions act.
A member function definition defines a single copy of code, placed in static memory, that serves all instances of the class.
Non-static member data declarations declare, and may define, data held in each instance of the class. The values of that data are unique to each class instance.
Static member data declarations declare a single copy of data for each declaration, placed in static memory, that serve all instances of the class. That is, each instance sees the same value of the static data.
Static data members must be defined below the class declaration. If you don't do this, no memory is reserved in static memory for the data and you will get linker errors when you build the package containing the class.
- Functions with names that are the same as the class name are constructors. The declaration of a class instance always causes a constructor to be called.
- A function with the name of the class prepended with a tilde (~) is a destructor. Destructors are called when the thread of execution leaves the scope in which the class instance was declared.
- Constructors and destructors are defined to manage allocation of resources to each instance of the class. Using code should not have to participate in the management for those resources.
- Operators are functions that are called whenever the operator symbol(s) appear immediately following the name of an existing instance of the class.
- Function arguments that are assigned a value define the default value for that argument, which is omitted in a function definition if we want to use the default value. Default arguments must be defined left-to-right.
- Functions whose declaration ends with the keyword const guarantee that the state of the instance won't be changed by calling the function.
- Note that public class declarations are always part of a header file, e.g., Str.h. The member function definitions are usually placed in an implementation file, Str.cpp. However, it is acceptable to place the function definition in-line withing the class declaration, or just after the class declaration if we qualify them as inline.