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

ApprenticeHacker picture ApprenticeHacker · Jul 9, 2011 · Viewed 19.7k times · Source

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?

Answer

Cody Gray picture Cody Gray · Jul 9, 2011

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.)