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;
friendvoid Derived::f();
protected:
Base();
};
class Derived : public Base
{
public:
void f();
};
void Derived::f()
{
cout << this->i << "; " << this->j << endl;
}
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
{
virtualvoid 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.
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:
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
}
};