CIS 250 - Class concepts (details)

Objectives

Terminology

A simple class

Function return types

Function overloading

You can have multiple functions with the same name, but different argument lists. The compiler can determine which function to use based on the argument list.

See overload1.cpp for an example.

Constructors, destructors, and dynamic memory allocation

It is common to overload constructors, but unlike Java, C++ constructors can not call each other. Since we try to eliminate duplicate code when possible and funnel error checking through individual functions for each check, it makes sense to create a common initialization function that all the constructors can call. This initialization function is also the ideal place to update a static object count variable if there is one.

You don't have to worry about overloading destructors. There can be only one. A destructor may not be needed unless you have to deallocate memory that was allocated by the object in a constructor or mutator method. Another reason you might need a destructor is to decrement a static object count variable.

The examples for this section use a C-style string as an instance variable. Smooth handling of a C-style string instance variable usually requires dynamic memory allocation and deallocation. You have to be careful when writing such code so you know that the pointer to the string has been initialized properly, and the memory returned when the object is destroyed.

See person.h, person.cpp, and testPerson.cpp for an example.

See person2.h, person2.cpp, and testPerson2.cpp for a more detailed example using dynamic memory allocation.