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

Next, consider the copy constructor. As you saw in Chapter 12, the default copy constructor does memberwise copying, which is inappropriate for dynamic memory allocation. However, memberwise copying is fine for the new lacksDMA member. That leaves the matter of the inherited baseDMA object. What you need to know is that memberwise copying uses the form of copying that is defined for the data type in question. So copying a long to a long is done using ordinary assignment. But copying a class member or an inherited class component is done using the copy constructor for that class. Thus, the default copy constructor for the lacksDMA class uses the explicit baseDMA copy constructor to copy the baseDMA portion of a lacksDMA object. So the default copy constructor is fine for the new lacksDMA member, and it’s also fine for the inherited baseDMA object.

Essentially the same situation holds for assignment. The default assignment operator for a class automatically uses the base-class assignment operator for the base-class component. So it, too, is fine.

These properties of inherited objects also hold true for class members that are themselves objects. For example, Chapter 10, “Objects and Classes,” implements the Stock class by using a string object to represent the company name. The standard string class, like our String example, uses dynamic memory allocation. Now you see why this wouldn’t create problems. The default Stock copy constructor would use the string copy constructor to copy the company member of an object, the default Stock assignment operator would use the string assignment operator to assign the company member of an object, and the Stock destructor (default or otherwise) would automatically call the string destructor.

Case 2: Derived Class Does Use new

Suppose that the derived class uses new:

// derived class with DMA


class hasDMA :public baseDMA


{


private:


    char * style;  // use new in constructors


public:


...


};

In this case, of course, you do have to define an explicit destructor, copy constructor, and assignment operator for the derived class. Let’s consider these methods in turn.

A derived class destructor automatically calls the base-class destructor, so its own responsibility is to clean up after what the derived-class constructors do. Thus, the hasDMA destructor has to free the memory managed by the style pointer and can rely on the baseDMA destructor to free the memory managed by the label pointer:

baseDMA::~baseDMA()  // takes care of baseDMA stuff


{


   delete [] label;


}



hasDMA::~hasDMA()      // takes care of hasDMA stuff


{


    delete [] style;


}

Next, consider copy constructors. The baseDMA copy constructor follows the usual pattern for arrays of char. That is, they use strlen() to find the length needed to hold the C-style string, allocate sufficient memory (the number of characters plus one byte for the null character), and use the strcpy() function to copy the original string to the target:

baseDMA::baseDMA(const baseDMA & rs)


{


    label = new char[std::strlen(rs.label) + 1];


    std::strcpy(label, rs.label);


    rating = rs.rating;


}

The hasDMA copy constructor only has access to hasDMA data, so it must invoke the baseDMA copy constructor to handle the baseDMA share of the data:

hasDMA::hasDMA(const hasDMA & hs)


         : baseDMA(hs)


{


    style = new char[std::strlen(hs.style) + 1];


    std::strcpy(style, hs.style);


}

The point to note is that the member initializer list passes a hasDMA reference to a baseDMA constructor. There is no baseDMA constructor with a type hasDMA reference parameter, but none is needed. That’s because the baseDMA copy constructor has a baseDMA reference parameter, and a base class reference can refer to a derived type. Thus, the baseDMA copy constructor uses the baseDMA portion of the hasDMA argument to construct the baseDMA portion of the new object.

Next, consider assignment operators. The baseDMA assignment operator follows the usual pattern:

baseDMA & baseDMA::operator=(const baseDMA & rs)


{


    if (this == &rs)


        return *this;


    delete [] label;


    label = new char[std::strlen(rs.label) + 1];


    std::strcpy(label, rs.label);


    rating = rs.rating;


    return *this;


}

Because hasDMA also uses dynamic memory allocation, it, too, needs an explicit assignment operator. Being a hasDMA method, it only has direct access to hasDMA data. Nonetheless, an explicit assignment operator for a derived class also has to take care of assignment for the inherited base class baseDMA object. You can accomplish this by explicitly calling the base class assignment operator, as shown here:

hasDMA & hasDMA::operator=(const hasDMA & hs)


{


    if (this == &hs)


        return *this;


    baseDMA::operator=(hs);  // copy base portion


    delete [] style;         // prepare for new style


    style = new char[std::strlen(hs.style) + 1];


    std::strcpy(style, hs.style);


    return *this;


}

The following statement might look a little odd:

baseDMA::operator=(hs);  // copy base portion

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

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

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

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