friendship from derived class method to base class members

I would like to know if there's a way to make a method from a derived class a friend of its base class. Something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Derived;
class Base
{
    int i, j;
    friend void Derived::f();
protected:
    Base();
};

class Derived : public Base
{
public:
    void f();
};

void Derived::f()
{
    cout << this->i << "; " << this->j << endl;
}

Thanks in advance!
closed account (10X9216C)
Do you mean you want the base class to call a method from a derived class? All friend does is give access to otherwise inaccessible information. In that case f() already is visible to the public so friend would really do nothing, everyone already has access to f().

You can instead us virtual functions that lets the derived class override it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Base
{
    virtual void DoSomething() = 0;
public:

    void Something() { DoSomething(); }

};

class Derived : public Base
{
    void DoSomething() override { std::cout << "something"; }
};


Is that what you need? If not, then i suggest reworking your structure as base classes shouldn't know too much about what the derived class is doing.
Hi myesolar,

I've got a good solution. The purpose is that assuming that I have two classes both derived from base class and having an identical private member. Why not saving some codes by putting that member in the base class and providing a friend access to both derived classes that need the member. Assuming that other derived classes won't be able to access that member at all. That's what I'm trying to achieve. I went to other forums in the meantime and came out with this:

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
26
27
28
29
30
31
32
33
34
class Base;
class Derived;

class Helper final
{
    friend class Derived;

    public:
        void f(Base* base);
    private:
        Helper() {}
};

class Base
{
    int i, j;
    friend class Helper;
protected:
    Base() {}
};

class Derived : public Base
{
public:
    void f();
private:
    Helper helper;
};

void Helper::f(Base* base)
{
    base->i = 10; base->j = 5;
    std::cout << "Help !" ;
}


And that solution is very helpful.

Thanks!
closed account (10X9216C)
That is not an ideal solution, what they came up with is such an ugly hack that just over complicates it.

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
26
27

class Base
{
protected: // allows derived class to access these members

    int i;
    int j;

};

class Derived : private Base // note private here
{
    void f()
    {
        i = 10;
        j = 5;
    }
};

class DoubleDerived : Derived
{
    void goo()
    {
        i = 10; // error access violation
    }
};
Last edited on
Topic archived. No new replies allowed.