Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Advanced Functions 295

10


programming—the calling program does not have to do anything to ensure that the
object starts in a self-consistent state.
As discussed on Day 6, “Understanding Object-Oriented Programming,” if you do not
explicitly declare a constructor for your class, a default constructor is created that takes
no parameters and does nothing. You are free to make your own default constructor, how-
ever, that takes no arguments but that “sets up” your object as required.
The constructor provided for you is called the “default” constructor, but by convention so
is any constructor that takes no parameters. This can be a bit confusing, but it is usually
clear which one is meant from the context.
Take note that if you make any constructors at all, the default constructor is not provided
by the compiler. So if you want a constructor that takes no parameters and you’ve cre-
ated any other constructors, you must add the default constructor yourself!

Overloading Constructors ....................................................................................


Constructors, like all member functions, can be overloaded. The capability to overload
constructors is very powerful and very flexible.
For example, you might have a rectangle object that has two constructors: The first takes
a length and a width and makes a rectangle of that size. The second takes no values and
makes a default-sized rectangle. Listing 10.3 implements this idea.

LISTING10.3 Overloading the Constructor


1: // Listing 10.3 - Overloading constructors
2:
3: #include <iostream>
4: using namespace std;
5:
6: class Rectangle
7: {
8: public:
9: Rectangle();
10: Rectangle(int width, int length);
11: ~Rectangle() {}
12: int GetWidth() const { return itsWidth; }
13: int GetLength() const { return itsLength; }
14: private:
15: int itsWidth;
16: int itsLength;
17: };
18:
19: Rectangle::Rectangle()
20: {
Free download pdf