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

2. The constructor methods are not inherited, the destructor is not inherited, the assignment operator is not inherited, and friends are not inherited.

3. If the return type were void, you would still be able to use single assignment but not chain assignment:

baseDMA magazine("Pandering to Glitz", 1);

baseDMA gift1, gift2, gift3;

gift1 = magazine;         // ok

gift 2 = gift3 = gift1;   // no longer valid

If the method returned an object instead of a reference, the method execution would be slowed a bit because the return statement would involve copying the object.

4. Constructors are called in the order of derivation, with the most ancestral constructor called first. Destructors are called in the opposite order.

5. Yes, every class requires its own constructors. If the derived class adds no new members, the constructor can have an empty body, but it must exist.

6. Only the derived-class method is called. It supersedes the base-class definition. A base-class method is called only if the derived class does not redefine the method or if you use the scope-resolution operator. However, you really should declare as virtual any functions that will be redefined.

7. The derived class should define an assignment operator if the derived-class constructors use the new or new [] operator to initialize pointers that are members of that class. More generally, the derived class should define an assignment operator if the default assignment is incorrect for derived-class members.

8. Yes, you can assign the address of an object of a derived class to a pointer to the base class. You can assign the address of a base-class object to a pointer to a derived class (downcasting) only by making an explicit type cast, and it is not necessarily safe to use such a pointer.

9. Yes, you can assign an object of a derived class to an object of the base class. Any data members that are new to the derived type are not passed to the base type, however. The program uses the base-class assignment operator. Assignment in the opposite direction (base to derived) is possible only if the derived class defines a conversion operator, which is a constructor that has a reference to the base type as its sole argument, or else defines an assignment operator with a base-class parameter.

10. It can do so because C++ allows a reference to a base type to refer to any type derived from that base.

11. Passing an object by value invokes the copy constructor. Because the formal argument is a base-class object, the base-class copy constructor is invoked. The copy constructor has as its argument a reference to the base class, and this reference can refer to the derived object passed as an argument. The net result is that a new base-class object whose members correspond to the base class portion of the derived object is produced.

12. Passing an object by reference instead of by value enables the function to avail itself of virtual functions. Also passing an object by reference instead of by value may use less memory and time, particularly for large objects. The main advantage of passing by value is that it protects the original data, but you can accomplish the same end by passing the reference as a const type.

13. If head() is a regular method, then ph->head() invokes Corporation::head(). If head() is a virtual function, then ph->head() invokes PublicCorporation::head().

14. First, the situation does not fit the is-a model, so public inheritance is not appropriate. Second, the definition of area() in House hides the Kitchen version of area() because the two methods have different signatures.

Answers to Chapter Review for Chapter 14

1.

2.

Gloam::Gloam(int g, const char * s) : glip(g), fb(s) { }

Gloam::Gloam(int g, const Frabjous & fr) : glip(g), fb(fr) { }

// note: the above uses the default Frabjous copy constructor

void Gloam::tell()

{

    fb.tell();

    cout << glip << endl;

}

3.

Gloam::Gloam(int g, const char * s)

             : glip(g), Frabjous(s) { }

Gloam::Gloam(int g, const Frabjous & fr)

             : glip(g), Frabjous(fr) { }

// note: the above uses the default Frabjous copy constructor

void Gloam::tell()

{

    Frabjous::tell();

    cout << glip << endl;

}

4.

class Stack

{

private:

    enum {MAX = 10};        // constant specific to class

    Worker * items[MAX];    // holds stack items

    int top;                // index for top stack item

public:

    Stack();

    Boolean isempty();

    Boolean isfull();

    Boolean push(const Worker * & item); // add item to stack

    Boolean pop(Worker * & item);        // pop top into item

};

5.

ArrayTP sa;

StackTP< ArrayTP > stck_arr_db;

ArrayTP< StackTP > arr_stk_wpr;

Listing 14.18 generates four templates: ArrayTP, ArrayTP, ArrayTP, and Array< ArrayTP, 10>.

6. If two lines of inheritance for a class share a common ancestor, the class winds up having two copies of the ancestor’s members. Making the ancestor class a virtual base class to its immediate descendants solves that problem.

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

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

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

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