Polymorphism in C + +

Source: Internet
Author: User


L Dynamic Binding

Voidprint_total (ostream &os, const item_base &item, size_t N)

{

os<< "ISBN:" << item.book () << "\tnumber sold:" << n << "\ttotal Price:"

<<item.net_price (n) << Endl;

}

The function works very normally: the book and Net_price functions that call their item parameters print the results. There are two points worth noting about this function.

First, although the second parameter of this function is item_base item_base Bulk_item object to it.

second, because the formal parameter is a reference and net_ Price Net_price which version is called Net_price will depend on the arguments passed to print_total print_total Bulk_item Bulk_item Net_price item_base item_base the version defined.

In C + +, dynamic binding occurs when a virtual function is called through a reference (or pointer) to a base class. The fact that a reference (or pointer) can point either to a base class object or to a derived class object is the key to dynamic binding. A virtual function called with a reference (or pointer) is determined at run time (the functions inJava are bound at run time, and C + + must be declared as virtual To be bound at run time), the function being called is defined by the actual type of the object referred to by the reference (or pointer).

L Define base classes and derived classes

ü The root class of the inheritance hierarchy is generally defined as a virtual destructor, i.e. Virtual~item_base () {}

ü The purpose of the reserved word virtual is to enable dynamic binding. Members default to non-virtual functions, and calls to non-virtual functions are determined at compile time. To indicate that the function is a virtual function, precede its return type with the reserved word virtual. In addition to the constructor, any non- Static a member function can be a virtual function ( Static functions cannot be overridden, so defining a virtual function is meaningless! )。 Reserved words appear only in member function declarations inside the class and cannot be used on function definitions that occur outside the body of the class definition.

ü In a base class, public and private labels have a common meaning: User code can access the public members of a class without accessing private members, and private members can only be accessed by members and friends of the base class. derived classes have access to the public and private members of the base class as any other part of the program: it can access public members and cannot access private members. Sometimes a class that is a base class has some members, and it wants to allow derived classes to access but still prevent other users from accessing those members. For such members, the protected Access designator should be used. Protected members can be accessed by derived class objects but not outside the scope of the class.

U derived classes can only access the protected members of their base classes through derived class objects , and derived classes have no special access to the protected members of their base class type objects, that is, they cannot be accessed.

VOIDBULK_ITEM::MEMFCN (const Bulk_item &d, const item_base &b)

{

Attempt to use protected member

DOUBLE ret = Price; Ok:uses This->price

ret = D.price; Ok:uses price from a Bulk_item object

ret = B.price; //Error:no access Toprice from an item_base

}

U derived classes cannot access the private members of the base class.

ü To define a derived class, use the class derivation list to specify the base class. The class-derived list specifies one or more base classes that have the following form: Class Classname:access-label Base-class

ü Although you do not have to do this, derived classes typically redefine inherited virtual functions. A derived class does not redefine a virtual function, the version defined in the base class is used.

The declaration of a virtual function in a derived class must exactly match the way it is defined in the base class, with one exception: a virtual function that returns a reference (or pointer) to a base type. A virtual function in a derived class can return a reference (or pointer) to a derived class of the type returned by the base class function. There are also virtual destructors!!

ü Once a function is declared as a virtual function in the base class, it is always a virtual function, and the derived class cannot change the fact that the function is a virtual function. When a derived class is redefining a virtual function, you can use the virtual reserved word, but you do not have to do so.

ü A defined class can be used as a base class. If you have declared the Item_base class, but you do not define it, you cannot use Item_base as the base class.

ü If a derived class needs to be declared (but not implemented), the declaration contains the class name but does not contain a derived list. For example, the following forward declaration causes a compile-time error:

ERROR:A forward declaration must not include the derivation list

Class Bulk_item:public item_base;

The correct forward declaration is:

Class Bulk_item;

Class Item_base;

ü C + + the function call in does not use dynamic binding by default. To trigger dynamic binding, satisfy two conditions: first, only member functions that are specified as virtual functions can be dynamically bound, the member functions default to non-virtual functions, non-virtual functions are not dynamically bound, and second, function calls must be made through a reference or pointer to a base class type .

ü If a non-virtual function is called, the function defined by the base class type is executed regardless of the actual object type. If you call a virtual function, you will not be able to determine which function is called until run time, which is the version of the type definition of the object to which the reference is bound or the pointer is pointing.

ü the object is non-polymorphic-the object type is known and unchanging. The dynamic type of an object is always the same as a static type, as opposed to a reference or pointer. A function that runs (a virtual or non-virtual function) is defined by the type of the object. A virtual function is determined at run time only by a reference or a pointer call. Only in these cases will the dynamic type of the object be known until run time.

#include <iostream>

UsingNamespace std;

Class n{

Public

virtual void A () {

cout<<1<<endl;

}

};

Classm:public n{

Public

void A () {

cout<<2<<endl;

}

};

Intmain () {

n I=m ();

I.A ();       // Output 1

return 0;

}}

ü Cover virtual function mechanism

Item_base*basep = &derived;

Double d = basep->item_base::net_price (42);

Why would you want to override the virtual function mechanism? The most common reason for deriving a class virtual function is to call the version in the base class. in this case, the base class version can complete all types of public tasks in the inheritance hierarchy, and each derived type only adds its own special work. When a derived class virtual function calls a base class version, you must explicitly use the scope operator. if the derived class function ignores this, the function call is determined at run time and will be a self-invocation, resulting in infinite recursion.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Polymorphism in C + +

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.