C ++ Calling a private / protected function of a common base class

Is there a good way to call A::foo()from B::bar()in the following example?

class A {
protected:
  void foo() {}
};

class B : public A {
public:
  void bar(A& a) { // edit: called with &a != this
    a.foo(); // does not work
  }
};

I can't think of anything other than declaring Bas a friend A, but it can get pretty ugly with some other classes.

Any ideas?

+3
source share
3 answers

Yes, you can use the base class function.

class A {
protected:
  void foo() {}
  void do_other_foo(A& ref) {
      ref.foo();
  }
};

class B : public A {
public:
  void bar(A& a) { // edit: called with &a != this
    this->do_other_foo(a);
  }
};
+4
source

Why are you passing an object of type A? You can do the following:

class B : public A {
public:
  void bar() {
    foo();
  }
};

or like this

class B : public A {
public:
  void bar() {
    A::foo();
  }
};
+3
source

"" , . , :

struct A
{
protected:
    //Zero sized struct which allows only derived classes to call privileged methods
    struct DerivedOnlyAccessToken{};

public:     //public in the normal sense :
    void foo() {}

public:     //For derived types only :
    void privilegedStuff( DerivedOnlyAccessToken aKey );
};

struct B: A
{
    void doPrivelegedStuff( A& a )
    {
        //Can create a token here
        a.privilegedStuff( DerivedOnlyAccessToken() );
    }
};

int _tmain(int argc, _TCHAR* argv[])
{

    A a;
    a.foo();
    a.privilegedStuff( A::DerivedOnlyAccessToken() ); // compile error.

    B b;
    b.doPrivelegedStuff( a );

    return 0;
}

This is not my idea. I read it in some place. Sorry, I don’t remember what an idea it was.

I expect the compiler to be able to exit the aKey parameter.

+1
source

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


All Articles