Lesson 1
Constructor Member Functions
The following will be discussed:
- How constructors and destructors provide management of class-defined object
- How to use a constructor for initialization
- About the use of default constructors
- How to use constructor initializers
- How constructors can perform automatic conversions
At the end of the module, you will be given the opportunity to take a quiz covering these topics.
The process of creating and deleting objects in C++ can be described by the following two operations.
Every time an instance of a class is created the constructor method is called.
The constructor has the same name as the class and it does not have a return type.
The destructor has the same name as the class and has a '~' in front of it.
Constructors
It is very common for some part of an object to require initialization before it can be
used. For example, the stack class.
Before the stack can be used, tos had to be set to zero. This was performed by using the function init( ). Because the requirement for initialization is so common, C++ allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor function. A constructor is a special function that is a member of a class and has the same name as that class.
For example, here is how the stack class looks when converted to use a constructor for initialization:
// This creates the class stack.
class stack {
int stck[SIZE];
int tos;
public:
stack(); // constructor
void push(int i);
int pop();
};
Notice that the constructor stack( ) has no return type specified. In C++, constructors cannot return values and have no return type. The stack( ) constructor is coded like this:
// stack's constructor
stack::stack()
{
tos = 0;
cout << "Stack Initialized\n";
}
The C++ Programming Language