Читаем C++ Primer Plus полностью

• The derived-class constructor should pass base-class information to a base-class constructor via a member initializer list.

• The derived-class constructor should initialize the data members that were added to the derived class.

This example doesn’t provide explicit destructors, so the implicit destructors are used. Destroying an object occurs in the opposite order used to construct an object. That is, the body of the derived-class destructor is executed first, and then the base-class destructor is called automatically.

Note

When creating an object of a derived class, a program first calls the base-class constructor and then calls the derived-class constructor. The base-class constructor is responsible for initializing the inherited data members. The derived-class constructor is responsible for initializing any added data members. A derived-class constructor always calls a base-class constructor. You can use the initializer list syntax to indicate which base-class constructor to use. Otherwise, the default base-class constructor is used.

When an object of a derived class expires, the program first calls the derived-class destructor and then calls the base-class destructor.

Member Initializer Lists

A constructor for a derived class can use the initializer list mechanism to pass values along to a base-class constructor. Consider this example:

derived::derived(type1 x, type2 y) : base(x,y) // initializer list

{

    ...

}

Here, derived is the derived class, base is the base class, and x and y are variables used by the base-class constructor. If, say, the derived-class constructor receives the arguments 10 and 12, this mechanism then passes 10 and 12 on to the base-class constructor defined as taking arguments of these types. Except for the case of virtual base classes (see Chapter 14, “Reusing Code in C++”), a class can pass values back only to its immediate base class. However, that class can use the same mechanism to pass back information to its immediate base class, and so on. If you don’t supply a base-class constructor in a member initializer list, the program uses the default base-class constructor. The member initializer list can be used only in constructors.

Using a Derived Class

To use a derived class, a program needs access to the base-class declarations. Listing 13.4 places both class declarations in the same header file. You could give each class its own header file, but because the two classes are related, it makes more organizational sense to keep the class declarations together.

Listing 13.4. tabtenn1.h

// tabtenn1.h -- a table-tennis base class

#ifndef TABTENN1_H_

#define TABTENN1_H_

#include

using std::string;

// simple base class

class TableTennisPlayer

{

private:

    string firstname;

    string lastname;

    bool hasTable;

public:

    TableTennisPlayer (const string & fn = "none",

                       const string & ln = "none", bool ht = false);

    void Name() const;

    bool HasTable() const { return hasTable; };

    void ResetTable(bool v) { hasTable = v; };

};

// simple derived class

class RatedPlayer : public TableTennisPlayer

{

private:

    unsigned int rating;

public:

    RatedPlayer (unsigned int r = 0, const string & fn = "none",

                 const string & ln = "none", bool ht = false);

    RatedPlayer(unsigned int r, const TableTennisPlayer & tp);

    unsigned int Rating() const { return rating; }

    void ResetRating (unsigned int r) {rating = r;}

};

#endif

Listing 13.5 provides the method definitions for both classes. Again, you could use separate files, but it’s simpler to keep the definitions together.

Listing 13.5. tabtenn1.cpp

//tabtenn1.cpp -- simple base-class methods

#include "tabtenn1.h"

#include

TableTennisPlayer::TableTennisPlayer (const string & fn,

    const string & ln, bool ht) : firstname(fn),

        lastname(ln), hasTable(ht) {}

void TableTennisPlayer::Name() const

{

    std::cout << lastname << ", " << firstname;

}

// RatedPlayer methods

RatedPlayer::RatedPlayer(unsigned int r, const string & fn,

     const string & ln, bool ht) : TableTennisPlayer(fn, ln, ht)

{

    rating = r;

}

RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer & tp)

    : TableTennisPlayer(tp), rating(r)

{

}

Listing 13.6 creates objects of both the TableTennisPlayer class and the RatedPlayer class. Notice that objects of both classes can use the TableTennisPlayer class Name() and HasTable() methods.

Listing 13.6. usett1.cpp

// usett1.cpp -- using base class and derived class

#include

#include "tabtenn1.h"

int main ( void )

{

    using std::cout;

    using std::endl;

    TableTennisPlayer player1("Tara", "Boomdea", false);

    RatedPlayer rplayer1(1140, "Mallory", "Duck", true);

    rplayer1.Name();          // derived object uses base method

    if (rplayer1.HasTable())

        cout << ": has a table.\n";

    else

        cout << ": hasn't a table.\n";

    player1.Name();           // base object uses base method

    if (player1.HasTable())

        cout << ": has a table";

    else

        cout << ": hasn't a table.\n";

    cout << "Name: ";

    rplayer1.Name();

    cout << "; Rating: " << rplayer1.Rating() << endl;

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных