Легенда:
новое сообщение
закрытая нитка
новое сообщение
в закрытой нитке
старое сообщение
|
- Напоминаю, что масса вопросов по функционированию форума снимается после прочтения его описания.
- Новичкам также крайне полезно ознакомиться с данным документом.
[C++] Final words 01.08.01 04:04 Число просмотров: 841
Автор: + (still can not login) Статус: Незарегистрированный пользователь
|
If the compiler has an object, it knows the exact type and therefore (in C++) will not use late binding for any function calls — or at least, the compiler doesn’t need to use late binding. For efficiency’s sake, most compilers will perform early binding when they are making a call to a virtual function for an object because they know the exact type. Here’s an example:
#include <iostream>
using namespace std;
class Base {
public:
virtual int f() const { return 1; }
};
class Derived : public Base {
public:
int f() const { return 2; }
};
int main() {
Derived d;
Base* b1 = &d;
Base& b2 = d;
Base b3;
// Late binding for both:
cout << "b1->f() = " << b1->f() << endl;
cout << "b2.f() = " << b2.f() << endl;
// Early binding (probably):
cout << "b3.f() = " << b3.f() << endl;
} ///:~
In b1–>f( ) and b2.f( ) addresses are used, which means the information is incomplete: b1 and b2 can represent the address of a Base or something derived from Base, so the virtual mechanism must be used. When calling b3.f( ) there’s no ambiguity. The compiler knows the exact type and that it’s an object, so it can’t possibly be an object derived from Base — it’s exactly a Base. Thus early binding is probably used. However, if the compiler doesn’t want to work so hard, it can still use late binding and the same behavior will occur.
P.S. tema zakryta.
|
|
|