开发者

What does it mean to set the declaration of a function equal to 0? How can you assign an integer to a function?

I was browsing through the sources of a (prefer not to name) GUI Toolkit which wrapped up the Windows API when I found the following function 开发者_如何学运维definition in the window class:

 virtual LRESULT CALLBACK wndProc (HWND, UINT, WPARAM, LPARAM) = 0;

What is happening here? How can you assign a function to an integer? Or does it assign it to NULL? Do you need to do this if you want to use function pointers in the wndproc?


That line of code defines a pure virtual function in C++. It has nothing to do with the otherwise tricky Win32 API or GUI code in general.

A pure virtual function is a virtual function that is used when the designer of the class wants to force derived classes to override the function and provide their own implementation.

If a class contains any pure virtual functions, it is considered an "abstract" class and instances of that class cannot be instantiated.

C++ uses the special syntax = 0; to indicate pure virtual functions instead of adding a new keyword to the language (as languages like C# do). You can think of it as setting the function pointer to 0.

Also see the answers to this related question: What are the uses of pure virtual functions in C++?


(By the way, the Windows header files <windows.h> simply define NULL as 0. So the programmer technically could have written = NULL, but it's much clearer to use the numeric constant 0 and reserve NULL for pointer values.)


It is a pure virtual function.

The =0 is just the syntax used to indicate that it is a pure virtual function.

Presence of a Pure virtual function in a class makes the class an Abstract class. One cannot create an object of any abstract class. Although, a pointer or reference to such an Abstract class can be created. Your derived class needs to override that method.

What is the purpose of making a function pure virtual?

Usually, A function is made pure virtual so that the designer of the Abstract Base class can enforce the derived class to override that function and provide it's own implementation. Important to note though, that a pure virtual function can have a implementation of its own, so the derived class can call Base class version of the function.

Sometimes a pure virtual function is added just to make the base class Abstract (so it's instances cannot be created). Usually, in such a situation instead of adding a dummy function to make a class Abstract the destructor of the class is made pure virtual.


This is a "pure virtual" function that you need to override in a derived class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜