A constructor is nothing more than a "function" that gets called when an object is constructed. It's purpose is to
"initialize" the contents of the object. (Recall that fundamental types such as int,bool, float, etc are not implicitly
initialized by the compiler). Keep in mind that there is a difference between
initialization and
assignment.
Almost all newbies use assignment because they are not familiar with initializer list syntax.
A destructor is nothing more than a "function" that gets called when an object is destroyed. It's purpose is to
"clean up" after the object. Usually, this means freeing any memory allocated by the object.
Here is dreamincolor's example done correctly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class MyIntArray
{
public:
// The default constructor should initialize the object to an array of zero elements (what else???)
MyIntArray() : numElements(), array() {}
// Here is a constructor that makes an array of N copies of V
MyIntArray( size_t n, int v ) : numElements( n ), array( new int[ n ] )
{ std::fill( array, array + n, v ); }
// The destructor should "clean up" -- usually, this means deallocating memory that the object allocated
~MyIntArray() { delete array; } // C++ standard guarantees that delete of a NULL pointer is OK.
private:
size_t numElements;
int* array;
};
|
Note: some syntax help. Here is a detailed explanation of one of the constructors above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// Here is a constructor that makes an array of N copies of V
MyIntArray( size_t n, int v )
: // the colon here indicates that what follows is an initializer list.
// you can initialize any or all of the data members of the class this way.
// you must keep the ordering of these the same as the order of declaration of the members in the class
// because the C++ standard guarantees you that members are initialized in the order of declaration,
// regardless of the order in which you put them here:
numElements( n ), // This is initializer list syntax. It is the same as saying "numElements = n;" except
// that it has to be like I wrote it. Essentially, all initializers in this list have to look
// like constructor calls.
array( new int[ n ] )
{
// All of the initializers are run BEFORE even the first line of code in the body of the constructor. Most objects
// can be completely initialized rather easily by the initializer list such that the body of the constructor can remain
// empty. It should be your goal to keep the body empty and do all the work in the initializer list, but I'm just
// presenting a more comprehensive example here. I could have also done this in the initializer list via a function
// call.
std::fill( array, array + n, v ); // just fills the array with v
}
|