Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 153

6


Line 47 calls the Meow()member function, and line 48 prints a message using the
GetAge()accessor. Line 50 calls Meow()again. Although these methods are a part of a
class (Cat) and are being used through an object (Frisky), they operate just like the
functions you have seen before.

Adding Constructors and Destructors..................................................................


Two ways exist to define an integer variable. You can define the variable and then assign
a value to it later in the program. For example:
int Weight; // define a variable
... // other code here
Weight = 7; // assign it a value
Or, you can define the integer and immediately initialize it. For example,
int Weight = 7; // define and initialize to 7
Initialization combines the definition of the variable with its initial assignment. Nothing
stops you from changing that value later. Initialization ensures that your variable is never
without a meaningful value.
How do you initialize the member data of a class? You can initialize the member data of
a class using a special member function called a constructor. The constructor can take
parameters as needed, but it cannot have a return value—not even void. The constructor
is a class method with the same name as the class itself.
Whenever you declare a constructor, you’ll also want to declare a destructor. Just as con-
structors create and initialize objects of your class, destructors clean up after your object
and free any resources or memory that you might have allocated (either in the construc-
tor, or throughout the lifespan of the object). A destructor always has the name of the
class, preceded by a tilde (~). Destructors take no arguments and have no return value.
If you were to declare a destructor for the Catclass, its declaration would look like the
following:
~Cat();

Getting a Default Constructor and Destructor ..............................................


Many types of constructors are available; some take arguments, others do not. The one
that takes no arguments is called the default constructor. There is only one destructor.
Like the default constructor, it takes no arguments.
It turns out that if you don’t create a constructor or a destructor, the compiler provides
one for you. The constructor that is provided by the compiler is the default constructor.
Free download pdf