With private inheritance, when is it ok to raise?

I have a question about C ++ private inheritance. See the following code example:

#include <iostream>

class Foo {
  public:
    virtual void doSomething(int value) {
      std::cout << value << std::endl;
    }

};

void foobar(Foo& foo, int value) {
  foo.doSomething(value);
}

class Bar : Foo {
  public:
    Bar() {
      foobar(*this, 42);  // <--- is OK despite private inheritance
    }
};

int main() {
  Bar b;
  foobar(b, 42); // <--- is NOT OK because of private inheritance
}

At the moment, I cannot understand (or find the correct specification in C ++) why the function foobarcan be called in the constructor Barwith *this , despite private inheritance . If I try to call a function foobarwith Barobject bin a function main, the compiler will throw an error, as expected, due to private inheritance.

What is the difference between foobar(*this, 42)and foobar(b, 42)which I am missing?

+4
source share
3 answers

, foobar Foo , Bar (privatly) Foo. :

  • Bar, foobar *this ; , *this Bar Foo&, , .
  • main(), class Bar, foobar b, Bar, . Bar Foo , .

, . , . , , .

+2

, . , Bar . , Bar.

14.2 [class.access.base]
... , .
...
, , , . , , . . , .

0

The question boils down to another question: What does private inheritance mean? . And this means that in simplifying words no one except the inheriting class knows that inheritance is happening. So, right up to your example, it Barknows that it is derived from Foo, so there are no problems with the raise in the constructor. On the other hand, mainit is not part of inheritance Bar, and therefore it cannot implicitly drop Barin Foo.

0
source

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


All Articles