Private friends

Hi,

I've got a problem with friend functionality. Hope you can help.

I've got two classes with private destructors. One of the destructors needs to call the other, so I need it to be friend. But, as the destructor is private, I cannot declare it as friend (the compiler complains about it). For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class LandMark;
class LandObject;

class LandMark
{
    private: 
    LandObject *pobj;

    /* whatever comes here */

    ~LandMark()
    {
        delete pobj;
    }
}

class LandObject
{
    private:

    ~LandObject();

    /* Below compiler complains about destructor being private */
    friend LandMark::~LandMark();
}


So the question is: what are my options here?

I need both destructors being private to give coherence to the program, so no point in suggesting to change this.

Thanks
Vic
I don't think friend declarations are affected by access labels but I'm no expert. What's your exact error message?
By the way thanks for having well indented code tagged code. It's... refreshing to see after so much otherwise.
Make LandObject a friend of LandMark
Bazzy, can you paste a working example of your proposal? I've tried this and does not work either:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class LandObject;
class LandMark;

class LandMark
{
    private: 
    LandObject *pobj;

    /* whatever comes here */

    ~LandMark()
    {
        delete pobj;
    }
}

class LandObject
{
    private:

    ~LandObject();

    /* Below compiler complains about destructor being private */
    friend class LandMark;
}


I can paste the compiler output, but this output is mixed english - spanish (maybe my locales, and don't know how to change it now). I have translated it (in ithalics translated messages):

1
2
3
4
5
6
7
vic@rapture:~/tmp$ g++ -c LandMark.cpp 
LandMark.cpp:13: warning: possible problem detected in delete operator call:
LandMark.cpp:13: warning: invalid use of incomplete type ‘struct LandObject’
LandMark.cpp:1: warning: forward declaration of ‘struct LandObject’
LandMark.cpp:13: note: Neither the destructor nor the class delete operator will be called even when the class is defined.
LandMark.cpp: At global scope:
LandMark.cpp:25: error: expected unqualified-id at end of input


BTW, the code is ready to compile (and fail with errors), just paste it to a file and run

g++ -c yourfile.cpp

you made LandMark to be a friend of LandObject, friendship isn't symmetric so you still need to make LandObject a friend of LandMark
Topic archived. No new replies allowed.