Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 10

Respect Your Parents

When you write a subclass, you need to be aware of the interaction between parent classes and child classes. Issues such as order of creation, constructor chaining, and casting are all potential sources of bugs.

Parent Constructors

Objects don’t spring to life all at once; they must be constructed along with their parents and any objects that are contained within them. C++ defines the creation order as follows:

1.The base class, if any, is constructed.

2.Non-static data members are constructed in the order in which they were declared.

3.The body of the constructor is executed.

These rules can apply recursively. If the class has a grandparent, the grandparent is initialized before the parent, and so on. The following code shows this creation order. As a reminder, we generally advise against inlining methods, as we’ve done in the code that follows. In the interest of readable and concise examples, we have broken our own rule. The proper execution will output the result 123.

#include <iostream> using namespace std;

class Something

{

public:

Something() { cout << “2”; }

};

class Parent

{

public:

Parent() { cout << “1”; }

};

class Child : public Parent

{

public:

Child() { cout << “3”; }

protected:

Something mDataMember;

};

int main(int argc, char** argv)

{

Child myChild;

}

When the myChild object is created, the constructor for Parent is called first, outputting the string “1”. Next, mDataMember is initialized, calling the Something constructor which outputs the string “2”. Finally, the Child constructor is called, which outputs 3.

234

Discovering Inheritance Techniques

Note that the Parent constructor was called automatically. C++ will automatically call the default constructor for the parent class if one exists. If no default constructor exists in the parent class, or if one does exist but you wish to use an alternate constructor, you can chain the constructor just as when initializing data members in the initializer list.

The following code shows a version of Super that lacks a default constructor. The associated version of Sub must explicitly tell the compiler how to call the Super constructor or the code will not compile.

//Super.h class Super

{

public: Super(int i);

};

//Sub.h

class Sub : public Super

{

public:

Sub();

};

// Sub.cpp Sub::Sub() : Super(7)

{

// Do Sub’s other initialization here.

}

In the preceding code, the Sub constructor passes a fixed value (7) to the Super constructor. Sub could also pass a variable if its constructor required an argument:

Sub::Sub(int i) : Super(i) {}

Passing constructor arguments from the subclass to the superclass is perfectly fine and quite normal. Passing data members, however, will not work. The code will compile, but remember that data members are not initialized until after the superclass is constructed. If you pass a data member as an argument to the parent constructor, it will be uninitialized.

Parent Destructors

Because destructors cannot take arguments, the language can automatically call the destructor for parent classes. The order of destruction is conveniently the reverse of the order of construction:

1.

2.

3.

The body of the destructor is called.

Any data members are destroyed in the reverse order of their construction.

The parent class, if any, is destructed.

Again, these rules apply recursively. The lowest member of the chain is always destructed first. The following code adds destructors to the previous example. If executed, this code will output “123321”.

235

Chapter 10

#include <iostream> using namespace std;

class Something

{

public:

Something() { cout << “2”; }

virtual ~Something() { cout << “2”; }

};

class Parent

{

public:

Parent() { cout << “1”; }

virtual ~Parent() { cout << “1”; }

};

class Child : public Parent

{

public:

Child() { cout << “3”; }

virtual ~Child() { cout << “3”; }

protected:

Something mDataMember;

};

int main(int argc, char** argv)

{

Child myChild;

}

Notice that the destructors are all virtual. As a rule of thumb, all destructors should be declared virtual. If the preceding destructors were not declared virtual, the code would continue to work fine. However, if code ever called delete on a superclass pointer that was really pointing to a subclass, the destruction chain would begin in the wrong place. For example, the following code is similar to the previous example but the destructors are not virtual. This becomes a problem when a Child object is accessed as a pointer to a Parent and deleted.

class Something

{

public:

Something() { cout << “2”; }

~Something() { cout << “2”; } // Should be virtual, but will work

};

class Parent

{

public:

Parent() { cout << “1”; }

~Parent() { cout << “1”; } // BUG! Make this virtual!

};

class Child : public Parent

{

236

Discovering Inheritance Techniques

public:

Child() { cout << “3”; }

~Child() { cout << “3”; } // Should be virtual, but will work

protected:

Something mDataMember;

};

int main(int argc, char** argv)

{

Parent* ptr = new Child();

delete ptr;

}

The output of this code is a shockingly terse “1231”. When the ptr variable is deleted, only the Parent destructor is called because the Child destructor was not declared virtual. As a result, the Child destructor is not called and the destructors for its data members are not called.

Technically, you could fix the above problem by simply making the Parent destructor virtual. The “virtualness” would automatically be used by any children. However, we advocate making all destructors virtual so that you never have to worry about it.

Always make your destructors virtual!

Referring to Parent Data

Names can become ambiguous within a subclass, especially when multiple inheritance (see below) comes into play. C++ provides a mechanism to disambiguate names between classes: the scope resolution operator. The syntax (two colons) is the same as referencing static data in a class.

When you override a method in a subclass, you are effectively replacing the original as far as other code is concerned. However, that parent version of the method still exists and you may want to make use of it. If you simply called the method by name, however, the compiler would assume that you meant the subclass version. This could easily lead to an infinite loop, as in the example that follows;

Sub::doSomething()

{

cout << “In Sub’s version of doSomething()” << endl;

doSomething();

// BUG! This will recursively call this method!

}

To call the parent’s version of the method explicitly, simply prepend the parent’s name and two colons:

Sub::doSomething()

{

cout << “In Sub’s version of doSomething()” << endl; Super::doSomething(); // call the parent version.

}

Calling the parent version of the current method is a commonly used pattern in C++. If you have a chain of subclasses, each might want to perform the operation already defined by the superclass but add their

own additional functionality as well.

237

Chapter 10

For example, imagine a class hierarchy of types of books. A diagram showing such a hierarchy is shown in Figure 10-4.

Book

Paperback Technical

Romance

Figure 10-4

Since each lower class in the hierarchy further specifies the type of book, a method that gets the description of a book really needs to take all levels of the hierarchy into consideration. This can be accomplished by chaining to the parent method as above. The following code illustrates this pattern:

#include <iostream> #include <string>

using namespace std;

class Book

{

public:

virtual string getDescription() { return “Book”; }

};

class Paperback : public Book

{

public:

virtual string getDescription() {

return “Paperback “ + Book::getDescription();

}

};

class Romance : public Paperback

{

public:

virtual string getDescription() {

return “Romance “ + Paperback::getDescription();

}

};

class Technical : public Book

{

public:

virtual string getDescription() {

return “Technical “ + Book::getDescription();

}

};

int main()

238