C++ 虚函数和其他成员函数

来源:互联网 发布:招生网络咨询技巧 编辑:程序博客网 时间:2024/06/05 00:24

By default, function calls in C++ do not use dynamic binding. To trigger dynamic binding, two conditions must be met:First, only member functions that are specified as virtual can be dynamically bound. By default, member functions are not virtual; nonvirtual functions are not dynamically bound.Second, the call must be made through a reference or a pointer to a base-class type.To understand this requirement, we need to understand what happens when we use a reference or pointer to an object that has a type from an inheritance hierarchy.


Nonvirtual Calls Are Resolved at Compile Time

Nonvirtual functions are always resolved at compile time based on the type of the object, reference, or pointer from which the function is called. The type of itemis reference to const Item_base, so a call to a nonvirtual function on that object will call the one from Item_base regardless of the type of the actual object to which itemrefers at run time.


Overriding the Virtual Mechanism

In some cases, we want to override the virtual mechanism and force a call to use a particular version of
a  virtual function. We can do so by using the scope operator:
Item_base *baseP = &derived;
// calls version from the base class regardless of the dynamic type of baseP
double d = baseP->Item_base::net_price(42);

Best Practices: Only code inside member functions should ever need to use the scope operator to override the virtual mechanism.


Why might we wish to override the virtual mechanism?The most common reason is when a derived class virtual calls the version from the base. In such cases, the base-class version might do work common to all types in the hierarchy.Each derived type adds only whatever is particular to its own type.


Virtual Functions and Default Arguments

Like any other function, a virtual function can have default arguments. As usual, the value, if any, of a default argument used in a given call is determined at compile time. If a call omits an argument that has a  default value, then the value that is used is the one defined by the type through which the function is called, irrespective of the object's dynamic type.When a virtual is called through a reference or pointer to base, then the default argument is the value specified in the declaration of the virtual in the base class. If a virtual is called through a pointer or reference to derived, the default argument is the one declared in the version in the derived class.
Using different default arguments in the base and derived versions of the same virtual is almost guaranteed to cause trouble.Problems are likely to arise when the virtual is called through a reference or pointer to base, but the version that is executed is the one defined by the derived. In such cases,the default argument defined for the base version of the virtual will be passed to the derived version, which was defined using a different default argument.

0 0
原创粉丝点击