Posts Tagged ‘friend’

Using friends

May 15, 2008

I am not referring to the punk next door whom at 2 years old has too much to say but none can be understood; not even the links on your social network account whose friends are really just the ones I want to see; or the people I usually get drank with. No, this is not about them. C++ talks of access and scope that are available when something is a friend [Stroustrup, 1997].

Why am I using it?
There is a limited framework that I have come across where the only easy way to hide controls is to make them delete themselves, and to be able to reuse such controls, I have to create another. Reuse here is an inappropriate term but it is used because in the context I am referring, they are class members. An issue arises then when a member calls delete this; and the compiler does not guarantee to set that pointer to null. Compilers today would be more standards compliant but this particular port of GCC I am using is not.

When am I using it?
There is no way then for checking for P’s validity if it were a member of a class C and when P deletes itself.


class P{};
class C {
    P* p;
public:
    void m()
    {
        if (p) /* is undefined */
        {/*...*/}
    }
    //...
};

Usually, this situation warrants setting P to null after deleting it. However, if this should happen in one of P’s methods this = NULL; is semantically incorrect. Making C::p public is easier but it will be exposing data unnecessarily.

Here comes friend. Declaring P to be a friend will make C’s private parts accessible to P:


class C {
    friend class P;
    P* p;
public:
    void m();
    //...
};

Now I can do something like this:


class P {
    C* c;
public:
    void doSomething()
    {
        //...
        c->p = 0; // c->p is actually this
        delete this;
    }
};

Should you use it too?
Honestly, I don’t know if what I am doing is right. It works for me and as I have said previously there is no other easy way. Well, there might be… 😉

References:

[Stroustrup, 1997] Bjarne Stroustrup: The C++ Programming Language

Advertisements