Chapter 56: C++ 4



Take a look at Vector.h (sample files listed at the bottom of notes) for an example of a C++ class.

First let’s look at our constructors and destructors:

Vector();                 // default constructor
Vector(Vector *);         // constructor
Vector(const Vector &);   // copy constructor
~Vector();                // destructor

Constructors are special member functions used to create instances of our class. We can have multiple constructors if there are multiple ways to create instances. In the case of our Vector class, we declare a default constructor and two other constructors to give three ways to make a Vector. You might be confused about the use of the & symbol in our third constructor, but we’ll talk about this in a second - it’s a C++ concept called a reference.

Finally, we have a destructor. This function is responsible for destroying the class when it’s time for it to be deallocated.

SRP (Single Responsibility Principle)

This is a general purpose software design principle:

Every class that you write should have one (and only one!) responsibility.

In C++ we often talk about “memory management” in terms of being a responsibility. In other words, if you need to do memory management, then you need to have a class that is solely responsible for memory management.

If you need to add an array of something to a class that you are writing, you should not be writing code that allocates and frees memory within that class that already has other responsibilities. Instead, you should use std::vector.

Example Files