How to enable warning for Deprecated Functions?

22 12 2008


If you port some of your old vc6 projects to Visual Studio 2005, you might have noticed that several function have become deprecated. Well, if you are a framework writer, its handy to notify user about the function which existed but deprecated. Well, how to do it?
depricatedfunction2


You can use #pragma deprecated or __declspec(deprecated) to mark the deprecated functions. Then, if the function is used, compiler will shoot a warning while compiling. Check the code snippet below for how to do it in different conditions.

1) Deprecated Functions

// If you want to set Fun1() and Fun2() as deprecated.
#pragma deprecated(Fn1, Fn2)
Fn1();   // C4995
Fn2();   // C4995

or

// If you use __declspec(deprecated), then you can
// provide an error message as well.
void __declspec(deprecated("Fn1 is not supported")) Fn1()
{}

2) Depricated Class

// If you want to set a class as deprecated.
#pragma deprecated( CFooBar )
CFooBar obj;   // C4995

or

// If you want to mark deprecated by using __declspec(deprecated)
class __declspec( deprecated("No Longer supported")) CFooBar
{};

3) Overloaded Member functions

class CFooBar
{
public:
    void Fun1()
    {}

    // Deprecating one of overloaded function.
    void __declspec(deprecated) Fun1( int a )
    {}
};
...
CFooBar obj;
obj.Fun1();        // Okay.
obj.Fun1( 0 );    // Error.

4) Error on deprecated function usage
If you enable – “Warning as errors” in Project settings, then the usage deprecated functions will halt the compilation which will be even more noticeable. Check the screenshot.
deprecatedfunctions1


Well, take care that this functionality is only available for visual studio 2005 and younger siblings.


Targeted Audience – Beginners.