Good day It does not work out with one example.

void fnc(); class CLASS1 { public: int r; }; class CLASS2 : private CLASS1 { friend void fnc(); }; class CLASS3 : public CLASS2 { }; void fnc() { CLASS3 cl3; CLASS1 cl1; cl1 = cl3; } int main() {} 

There are no compilation errors on VS2008, however, if CLASS3 is not inherited as public, but as protected, an error occurs that the conversion is not available. Remove friend - also not available. In the book, Lippman says that it is available if you can access the public field of the class to which the conversion is going, but in CLASS3 the base class (CLASS1) is not available (because CLASS2 inherits private), but the conversion is. How does a friend affect this and in general, how in such a situation does the compiler determine whether a conversion is available or not?

Sincerely, Victor

    1 answer 1

    • In the line cl1 = cl3 , you have a call to the assignment operator.

    Because for CLASS1 compiler automatically generated an assignment statement that takes an argument of type const CLASS1 & , in your example, the string cl1 = cl3 results in a call to CLASS1::operator=(const CLASS1 &) .

    • Further, the compiler tries to substitute an object of type CLASS3 in a call to CLASS1::operator=(const CLASS1 &) .
    • Since this call occurs within the fnc, function fnc, which is marked as a friend in the CLASS2, class CLASS2, the entire CLASS3 -> CLASS2 -> CLASS1 type conversion chain is available within this function.

    • Accordingly, the conversion 'const CLASS3 & -> const CLASS1 &', so this code does not result in a compilation error.

    • See also https://stackoverflow.com/questions/5128908/c-type-conversion-faq

    • one
      Only not the copy constructor, but the assignment operator. - atwice
    • one
      @atwice Yes, of course, it's in the evening :) Thank you. - Costantino Rupert
    • Thank. Those. it turns out that if it is not directly converted, then the compiler does the conversion via CLASS2, in which there is a friend? But if so, he could have done it without a friend, since CLASS3 sees public 2 classes, and he sees public 1st. On the other hand, if CLASS3 inherits as protected or private, there will be an error, although fnc is still A second-class friend and, as you said, a chain of conversions is available in fnc. I just can’t understand the logic