Pure virtual friend class

I have a class Athat has a pointer to an instance of a pure virtual class B. The class Cis inferred from Band will automatically have a pointer to A(which is its parent) and must gain access to its members. This can be achieved by adding friend class Cinside the class A, although then it is necessary for each class to be obtained from B.

Code example:

class A
{
public:
    friend class B; // This does not allow derived classes to be friends
    friend class C; // Now derived class B has access to `DoDomething`, but then this is needed for every single derived class

private:
    void DoDomething();
};


class B
{
    virtual void Tick() = 0;

protected:
    A* m_pointerToA; // <- is being set upon creating automatically
};


class C : public class B
{
    virtual void Tick()
    {
        m_pointerToA->DoSomething();
    }
};

Is there a way to force all derived classes from to Bhave access to the private and protected members of the class Athat they point to without having to add friend class Xfor each of them?

+4
1

, , , B. , B A, "":

class B {
    virtual void Tick() = 0;
protected:
    A* m_pointerToA; // <- is being set upon creating automatically
    void callDoSomething() {
        m_pointerToA->DoSomething();
    }
};


class C : public class B {
    virtual void Tick() {
        std::cout << "Class C is about to tick..." << std::endl;
        callDoSomething();
    }
};

class D : public class B {
    virtual void Tick() {
        callDoSomething();
        std::cout << "Class D has just ticked!" << std::endl;
    }
};

, B, .

+5

Source: https://habr.com/ru/post/1617139/


All Articles