0

If i have two classes, for example like this

class A {
    ...
    protected:
        B* test;
        aFunction();
};

class B {
    ...
    protected:
        A* test1;

    public:
        bFunction();
};

can I do this inside bFunction() of class B:

bFunction(){
    test1->aFunction();
}

Basically, can I call a protected function of a certain class from the class that's not derived from that function?

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
idjuradj
  • 1,355
  • 6
  • 19
  • 31

3 Answers3

4

The "point" of the protected is that only classes that are derived from the baseclass can call those functions.

If you have a good reason to do this, then make the class a friend, e.g. add friend class B; inside class A.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
2

It is recommended to avoid such inevident mutual dependencies. A necessity to use friend functions often indicates bad architecture.

borx
  • 411
  • 4
  • 7
1

From cplusplus.com:

Private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rules does not affect friends.

You can call protected and privat methods from other classes, when those are 'friends':

In your case that would be:

Class A {
    ...
    protected:
        B* test;
        aFunction();
    friend class B;
}

Often that is considered bad practice, but for tightly coupled classes that is ok.

villekulla
  • 1,039
  • 5
  • 15