C/C++, doubt on Friend function
-
A Friend function can be avoided if get()(to read) and set()(to write) member functions(public) are provided on (private) data members of a class. Is it True or False. Can anyone help me clearing this doubt with an appropriate reason?
-
A Friend function can be avoided if get()(to read) and set()(to write) member functions(public) are provided on (private) data members of a class. Is it True or False. Can anyone help me clearing this doubt with an appropriate reason?
The friend keyword allows you to specify functions or other classes which will be able to access all member (public, protected or private) of the class in which the friend keyword is used. Thus one way to avoid using it would be to provide getters and setters. But this is not always a good approach because all your members will become 'visible' to everybody, which is not always what you want.
Cédric Moonen Software developer
Charting control [v1.5] OpenGL game tutorial in C++ -
A Friend function can be avoided if get()(to read) and set()(to write) member functions(public) are provided on (private) data members of a class. Is it True or False. Can anyone help me clearing this doubt with an appropriate reason?
dubeypankaj wrote:
A Friend function can be avoided if get()(to read) and set()(to write) member functions(public) are provided on (private) data members of a class. Is it True or False.
Well, you can do it with a friend function. You use getters-setters to access the read/write the private members. The same can be archived through friends but that would look raw.
He never answers anyone who replies to him. I've taken to calling him a retard, which is not fair to retards everywhere.-Christian Graus
-
A Friend function can be avoided if get()(to read) and set()(to write) member functions(public) are provided on (private) data members of a class. Is it True or False. Can anyone help me clearing this doubt with an appropriate reason?
A friend function basically gives access to the internal data members of a class to an external function. This can definitely be achieved using getters and setters. But in reality friend functions are not used for this purpose. For example, if you look at the
CStringT
class, the overloaded+ operator
is declared as a friend function. This is so that the+ operator
can be used to concatenate two string in the following 2 waysCString cs1 = L"Hello";
CString cs2 = L"World";
CString cs3 = L"";cs3 = cs1 + L" World";
cs3 = L"Hello " + cs2;If the
+ operator
was an ordinary member function of theCStringT
class, then only the first call would have been possible.«_Superman_» I love work. It gives me something to do between weekends.