C ++ Primer study note _ 65 _ object-oriented programming -- Overview, definition base class and derived class

Source: Internet
Author: User

Object-Oriented Programming-Overview, definition of base classes and derived classes


Introduction:

Object-Oriented programming is based on three basic concepts: data abstraction, inheritance, and dynamic binding.

In C ++,Data abstraction using classesTo inherit from one class:The derived class inherits the members of the base class.. Dynamic binding enables the compilerAt runtime, it is determined whether to use the function defined in the base class or the function defined in the derived class..

Inheritance and dynamic binding simplify our program in two aspects: [inheritance] can easily define new classes that are similar to other classes but not the same, and [derivation] can be easier to writeIgnore programs with different similar types.


Object-Oriented Programming: overview

The key idea of object-oriented programming isPolymorphism(Polymorphism). The reason why the types associated by inheritance are called polymorphism types is that many forms of derived or base types can be used interchangeably in many cases ". As we will see, in C ++, polymorphism is only usedReferences or pointers of types associated by inheritance.


1. Inheritance

Derived class(Derivedclass)InheritanceBase Class(Baseclass)Defined members, which can be used without changing the derived classOperations unrelated to the specific characteristics of the derived type, A derived class can redefine member functions related to the derived type,Special Functions,Consider the characteristics of the derived type. Finally, in addition to the members inherited from the base class, the derived class can also define more members.

We often say that the classes associated with inheritance constituteInheritance level. One class is called the root,Therefore, other classes directly or indirectly inherit the root class.. For example:


class Item_base
{
public:
    Item_base(const std::string &book = "",
              double sales_price = 0.0):isbn(book),price(sales_price) {}

    std::string book() const
    {
        return isbn;
    }

    virtual double net_price(std::size_t n) const
    {
        return n * price;
    }
    virtual ~Item_base() {}

private:
    std::string isbn;

protected:
    double price;
};


The derived classes of Item_base do not need to be changed to inherit the book function: the derived classes do not need to be redefined to obtain the meaning of ISBN. On the other hand, each derived class needs to define its own net_price function version to implement an appropriate discount price policy.

In C ++, the base class must specifyWhich functions do you Want to override in a derived class?, DefinedVirtualThe base class is expected to be redefined by the derived class. The function that the base class wants to inherit from cannot be defined as a virtual function.

After discussing this, we can see that our class will define three (const) member functions:

1) The non-virtual function std: stringbook () returns ISBN. Defined by Item_base and inherited by Bulk_item.

2) The two versions of the virtual function doublenet_price (size_t) (one of which has been defined) return the total price of a certain number of books. The Item_base class and the Bulk_item class define the version of the function.


2. dynamic binding

PassDynamic bindingYou can write programs to use any type of objects in the inheritance hierarchy, without worrying about the specific types of objects. Programs that use these classesYou do not need to distinguish whether a function is defined in a base class or a derived class.For example, you can compile the print_total function:


void print_total(ostream &os,const Item_base &item,size_t n)
{
    os << "ISBN: " << item.book()
       << "\t number sold: " << n << "\ttotal price: "
       << item.net_price(n) << endl;
}


Note :]

First, although the second parameter of this function is a reference to Item_base, you can pass the Item_base object or Bulk_item object to it.

Second, because the parameter is referenced and net_price is a virtual function, the call to net_price willConfirm at runtime. Which version of net_price will be called depends on the real parameter passed to print_total.


[Summary]

In C ++, dynamic binding occurs when a virtual function is called through a reference (or pointer) of a base class.Reference(Or pointer)It can be a base object or a derived class object.,This is actually the key to dynamic binding. The virtual function called by reference (or pointer) is determined at runtime. The called function is defined by the actual type of the object referred to by reference (or pointer.


Define base classes and derived classes

I. Define the base class

Like other classes, the base class also has its interfaces and implemented data and function members:


class Item_base
{
public:
     Item_base (const std :: string & book = "",
               double sales_price = 0.0): isbn (book), price (sales_price) ()

     std :: string book () const
     {
         return isbn;
     }

     virtual double net_price (std :: size_t n) const
     {
         return n * price;
     }

     // The root class of the inheritance hierarchy generally defines a virtual destructor
     virtual ~ Item_base () {}

private:
     std :: string isbn;

protected:
     double price;
};


1. base class member functions

Virtual function: the purpose of Reserved Words virtual is to enableDynamic binding. The Member is a non-virtual function by default.The call of non-virtual functions is determined during compilation.To specify the function as a virtual function, the virtual keyword must be added:


    virtual double net_price(std::size_t n) const;


Apart from constructorsAny non-static member can use the virtual function. Reserved Words virtualOnly appears in the member function declaration within the class,It cannot appear outside the class definition body.

[Best practices]

Base ClassGenerallyDerived classYesRedefinitionAny function is defined as a virtual function..


2. Access Control and inheritance

In the base class, the public and private labels have common meanings:User code canPublicMembers cannot accessPrivateMember, PrivateMembers can only be accessed by members and friends of the base class.. The public and private member of the base classThe access permission is the same as any other part of the program.: It can access public members but not private members.

ProtectedMembers can beAccess from a derived class ObjectHoweverCannot be accessed by this type of common users.


II,ProtectedMember

It can be considered that the protected access label is a combination of private and public:

1) like a private member,ProtectedThe member cannot beClass userAccess.

2) Like a public member,ProtectedThe member can beDerived class of this classAccess.

In addition, protected has another important nature:

A derived class can only access the protected member of its base class through the derived class object. The derived class has no special access permission to the protected member of its base class type object.


void Bulk_item::memfcn(const Bulk_item &d,const Item_base &b)
{
    double ret = price;
    ret = d.price;
    ret = b.price;  //Error
}


[Key concepts: Class Design and protected members]

The provider of a derived class usually (but not always) needs to access (generally private) The base class implementation,To allow such access, general access to the implementation is still prohibited., Provides an additional protected access label.

When defining a class to act as a base class, the standard for designing the member as public has not changed: the interface function should still be public, and the data should generally be private.The inherited class must determine which part of the declaration is implementedProtectedWhich parts are declaredPrivate.If you want to disable access to a derived class, you should set it to private. The members that provide the derived class to implement the required operations or data should be set to protected. In other words, the interface provided to the derived class is a combination of protected members and public members.


Iii. Derived classes

To define a derived class, useList of derived classesSpecify the base class. The list of derived classes specifies one or more base classes and access permissions:


class ClassName: access-label base-class


It is most common to inherit a single base class. Then the access Label [public, private, protected] determines the access permission to the inherited members. If you want to inherit the interface of the base class, you should perform public derivation.

The derived class inherits the members of the base class and can define its own additional members. Each derived class object contains two parts: Members inherited from the base class and custom members. Generally,Derived class only(Heavy)Define aspects that are different from the base class or expand the base class behavior.


1. Define a derived class

The Bulk_item class is derived from the Item_base class. The Bulk_item class inherits the book, isbn, and price members. The Bulk_item class must redefine the net_price function and define the data members required for this operation:


class Bulk_item:public Item_base
{
public:
    double net_price(std::size_t ) const;

private:
    std::size_t min_qty;
    double discount;
};


Each Bulk_item object containsFour data members:SlaveItem_baseInheritedIsbnAndPrice, CustomMin_qtyAndDiscount.


2. Derived classes and virtual functions

A derived class generally redefines the inherited virtual function. If the derived class does not redefine a virtual function, the version defined in the base class is used.

The derived type must be declared for each inherited member to be redefined. The declaration of a virtual function must exactly match the definition method in the base class, but there is an exception: the virtual function that returns a reference (or pointer) to the base type. A virtual function in a derived class can return a reference (or pointer) of a derived class of the type returned by a base class function ).

[Note]

Once a function is declared as a virtual function in the base class, it is always a virtual function, and the fact that a derived class cannot change this function to a virtual function. When a derived class redefinition of a virtual function, you can use virtual reserved words, but this is not required [but we recommend that you do this to remind the class users that this function is a virtual function].


3. The derived class object contains the base class object as the sub-Object

A derived class object consists of multiple parts: a (non-static) member defined by the derived class and a sub-object composed of a base class (non-static) member.

[Note: The C ++ language does not require the compiler to consecutively arrange the base class and derived part of the object. Therefore, the diagram shows the concept representation of how the class works, rather than the physical representation .] <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD48cD48YnIgLz48YnIgLz48L3A + PHA + PGJyIC8 + PGJyIC8 + running/K/B/J0tTKudPDu/running = "brush: java;"> double Bulk_item: net_price (std: size_t cnt) const {if (cnt> = min_qty) {return cnt * (1-discount) * price;} return cnt * price ;}

Because each derived class object has a base class, the class can access the public and protected members of its base class, just like those members are their own [don't take yourself as an outsider O (nobody _ Nobody) O ha!]!


5. The class used as the base class must beDefined


class Item_base; // only declared
// Error: Item_base is not defined
class Bulk_item: public Item_base {};


Each derived class contains and can access its base class members. To use these Members,The derived class must know what they are.. This rule implies that it is impossible to derive a class from the class itself.


6. Use a derived class as the base class


class Base
{
    /*....*/
};
class D1: public Base
{
    /*....*/
};
class D2: public D1
{
    /*....*/
};


Each class inherits all its base class members.. The bottom-layer derived class inherits the members of its base class, and the base class inherits the members of its own base class, so that the inheritance chain goes up sequentially. The bottom-layer derived class object contains each of itsDirect base classAndIndirect base class.


7. Declaration of a derived class

The declaration of a derived class contains the class name, not the list of derived classes.


class Bulk_item: public Item_base; // Error
class Bulk_item; // OK

// P479 Exercise 15.6
class Bulk_item: public Item_base
{
public:
     double net_price (std :: size_t) const;

private:
     std :: size_t min_qty;
     double discount;
};

double Bulk_item :: net_price (std :: size_t cnt) const
{
     if (cnt> = min_qty)
     {
         return cnt * (1-discount) * price;
     }

     return cnt * price;
}

// Exercise 15.7
class Item_derivd: public Item_base
{
public:
     double net_price (std :: size_t) const;

private:
     std :: size_t count;
     double discount;
};

double Item_derivd :: net_price (std :: size_t cnt) const
{
     if (cnt <= count)
     {
         return cnt * (1-discount) * price;
     }

     return cnt * price;
} 



To be continued...


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.