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

By the way, it’s not an error for a class to have a virtual destructor even if it is not intended to be a base class; it’s just a matter of efficiency.


Tip

Normally, you should provide a base class with a virtual destructor even if the class doesn’t need a destructor.


Friends

Friends can’t be virtual functions because friends are not class members, and only members can be virtual functions. If this poses a problem for a design, you might be able to sidestep it by having the friend function use virtual member functions internally.

No Redefinition

If a derived class fails to redefine a function (virtual or not), the class will use the base class version of the function. If a derived class is part of a long chain of derivations, it will use the most recently defined version of the function. The exception is if the base versions are hidden, as described next.

Redefinition Hides Methods

Suppose you create something like the following:

class Dwelling


{


public:


      virtual void showperks(int a) const;


...


};


class Hovel : public Dwelling


{


public:


      virtual void showperks() const;


...


};

This causes a problem. You might get a compiler warning similar to the following:

Warning: Hovel::showperks(void) hides Dwelling::showperks(int)

Or perhaps you won’t get a warning. Either way, the code has the following implications:

Hovel trump;


trump.showperks();      // valid


trump.showperks(5);     // invalid

The new definition defines a showperks() function that takes no arguments. Rather than resulting in two overloaded versions of the function, this redefinition hides the base class version that takes an int argument. In short, redefining inherited methods is not a variation of overloading. If you redefine a function in a derived class, it doesn’t just override the base class declaration with the same function signature. Instead, it hides all base-class methods of the same name, regardless of the argument signatures.

This fact of life leads to a couple rules of thumb. First, if you redefine an inherited method, you need to make sure you match the original prototype exactly. One relatively new exception to this rule is that a return type that is a reference or pointer to a base class can be replaced by a reference or pointer to the derived class. This feature is termed covariance of return type because the return type is allowed to vary in parallel with the class type:

class Dwelling


{


public:


// a base method


      virtual Dwelling & build(int n);


      ...


};


class Hovel : public Dwelling


{


public:


// a derived method with a covariant return type


      virtual Hovel & build(int n);  // same function signature


      ...


};

Note that this exception applies only to return values, not to arguments.

Second, if the base class declaration is overloaded, you need to redefine all the base-class versions in the derived class:

class Dwelling


{


public:


// three overloaded showperks()


      virtual void showperks(int a) const;


      virtual void showperks(double x) const;


      virtual void showperks() const;


      ...


};


class Hovel : public Dwelling


{


public:


// three redefined showperks()


      virtual void showperks(int a) const;


      virtual void showperks(double x) const;


      virtual void showperks() const;


      ...


};

If you redefine just one version, the other two become hidden and cannot be used by objects of the derived class. Note that if no change is needed, the redefinition can simply call the base-class version:

void Hovel::showperks() const {Dwelling::showperks();}

Access Control: protected

So far the class examples in this book have used the keywords public and private to control access to class members. There is one more access category, denoted with the keyword protected. The protected keyword is like private in that the outside world can access class members in a protected section only by using public class members. The difference between private and protected comes into play only within classes derived from the base class. Members of a derived class can access protected members of a base class directly, but they cannot directly access private members of the base class. So members in the protected category behave like private members as far as the outside world is concerned but behave like public members as far as derived classes are concerned.

For example, suppose the Brass class declared the balance member as protected:

class Brass


{


protected:


    double balance;


...


};

In this case, the BrassPlus class could access balance directly without using Brass methods. For example, the core of BrassPlus::Withdraw() could be written this way:

void BrassPlus::Withdraw(double amt)


{


    if (amt < 0)


        cout << "Withdrawal amount must be positive; "



             << "withdrawal canceled.\n";


    else if (amt <= balance)       // access balance directly


        balance -= amt;


    else if ( amt <= balance + maxLoan - owesBank)


    {


        double advance = amt - balance;


        owesBank += advance * (1.0 + rate);


        cout << "Bank advance: $" << advance << endl;


        cout << "Finance charge: $" << advance * rate << endl;


        Deposit(advance);


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

Все книги серии 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.2
1С: Управление торговлей 8.2

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

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

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