Question

What are security risks with friend functions? Will it compromise encapsulation and data-hiding in C++?

I am not able to get the proper answer in-spite a lots of research. Can someone give a concrete answer with example?

Was it helpful?

Solution

Here is an example ,the function FUNC will destroy the protection of the data in multiple thread enviroment.

# include <windows.h>
# include <iostream>

using namespace std;

void func();

class DataAdapter
{
    friend void func();
private:
    static volatile LONG _index;
public:
    static void incr() 
    { 
        InterlockedIncrement(&_index);
    }
};

void func()
{
    DataAdapter::_index += 1;
}

DWORD WINAPI threadproc(void *pdata)
{
    pdata = pdata;

    DataAdapter::incr();

    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{  
    HANDLE hThread = CreateThread(NULL , 0 , threadproc , 0 , 0 , 0);
    WaitForSingleObject(hThread , 5000);
    return 0;
}

OTHER TIPS

There are no particular security risks involved with friend functions. Friend functions are part of the implementation of the class, just like class members; whether a function is a member or a friend doesn't change anything with regards to the security risks (or anything else).

It's important to remember that encapsulation and security are two different things.

friend is a feature of the C++ language which acts as a sort of "exception" to data hiding.

It has nothing to do with security, because friend only exists at the language level, not at runtime where security issues are concerned.

I am putting this as an answer on behalf of @mankrase

It is always possible to legally access private members of any object. Furthermore, if your code contains undefined behaviour, absolutely anything can happen (regardless of the presence of friend functions). Friend functions do not represent a security risk; they are neutral with respect to security (and in the best case, are beneficial to security because they can make code simpler and better encapsulated).

Thanks Mankrase.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top