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

• The BrassPlus class adds three new private data members and three new public member functions to the Brass class.

• Both the Brass class and the BrassPlus class declare the ViewAcct() and Withdraw() methods; these are the methods that will behave differently for a BrassPlus object than they do with a Brass object.

• The Brass class uses the new keyword virtual in declaring ViewAcct() and Withdraw(). These methods are now termed virtual methods.

• The Brass class also declares a virtual destructor, even though the destructor does nothing.

The first point in the list is nothing new. The RatedPlayer class did something similar when it added a new data member and two new methods to the TableTennisPlayer class.

The second point in the list is how the declarations specify that methods are to behave differently for the derived class. The two ViewAcct() prototypes indicate that there will be two separate method definitions. The qualified name for the base-class version is Brass::ViewAcct(), and the qualified name for the derived-class version is BrassPlus::ViewAcct(). A program will use the object type to determine which version to use:

Brass dom("Dominic Banker", 11224, 4183.45);

BrassPlus dot("Dorothy Banker", 12118, 2592.00);

dom.ViewAcct();      // use Brass::ViewAcct()

dot.ViewAcct();      // use BrassPlus::ViewAcct()

Similarly, there will be two versions of Withdraw(): one that’s used by Brass objects and one that’s used by BrassPlus objects. Methods that behave the same for both classes, such as Deposit() and Balance(), are declared only in the base class.

The third point (the use of virtual) is more involved than the first two points. It determines which method is used if the method is invoked by a reference or a pointer instead of by an object. If you don’t use the keyword virtual, the program chooses a method based on the reference type or pointer type. If you do use the keyword virtual, the program chooses a method based on the type of object the reference or pointer refers to. Here is how a program behaves if ViewAcct() is not virtual:

// behavior with non-virtual ViewAcct()

// method chosen according to reference type

Brass dom("Dominic Banker", 11224, 4183.45);

BrassPlus dot("Dorothy Banker", 12118, 2592.00);

Brass & b1_ref = dom;

Brass & b2_ref = dot;

b1_ref.ViewAcct();      // use Brass::ViewAcct()

b2_ref.ViewAcct();      // use Brass::ViewAcct()

The reference variables are type Brass, so Brass::ViewAccount() is chosen. Using pointers to Brass instead of references results in similar behavior.

In contrast, here is the behavior if ViewAcct() is virtual:

// behavior with virtual ViewAcct()

// method chosen according to object type

Brass dom("Dominic Banker", 11224, 4183.45);

BrassPlus dot("Dorothy Banker", 12118, 2592.00);

Brass & b1_ref = dom;

Brass & b2_ref = dot;

b1_ref.ViewAcct();      // use Brass::ViewAcct()

b2_ref.ViewAcct();      // use BrassPlus::ViewAcct()

In this case, both references are type Brass, but b2_ref refers to a BrassPlus object, so BrassPlus::ViewAcct() is used for it. Using pointers to Brass instead of references results in similar behavior.

It turns out, as you’ll see in a bit, that this behavior of virtual functions is very handy. Therefore, it is the common practice to declare as virtual in the base class those methods that might be redefined in a derived class. When a method is declared virtual in a base class, it is automatically virtual in the derived class, but it is a good idea to document which functions are virtual by using the keyword virtual in the derived class declarations, too.

The fourth point is that the base class declares a virtual destructor. This is to make sure that the correct sequence of destructors is called when a derived object is destroyed. We’ll discuss this point in more detail later in this chapter.

Note

If you redefine a base-class method in a derived class, the usual practice is to declare the base-class method as virtual. This makes the program choose the method version based on object type instead of the type of a reference or pointer. It’s also the usual practice to declare a virtual destructor for the base class.

Class Implementations

The next step is to prepare the class implementation. Part of this has been done already by the inline function definitions in the header file. Listing 13.8 provides the remaining method definitions. Note that the keyword virtual is used just in the method prototypes in the class declaration, not in the method definitions in Listing 13.8.

Listing 13.8. brass.cpp

// brass.cpp -- bank account class methods

#include

#include "brass.h"

using std::cout;

using std::endl;

using std::string;

// formatting stuff

typedef std::ios_base::fmtflags format;

typedef std::streamsize precis;

format setFormat();

void restore(format f, precis p);

// Brass methods

Brass::Brass(const string & s, long an, double bal)

{

    fullName = s;

    acctNum = an;

    balance = bal;

}

void Brass::Deposit(double amt)

{

    if (amt < 0)

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

Все книги серии 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.

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

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