0

I am wondering how come this code correct and how the compiler knows to first create an obj of class A, I would think it shouldn't compile since B's ctor request an argument of type A not int

    class A 
{
    int a1;
public:
    A(int i) { cout << i << "A"<<endl;}
    friend class B;
};

class B
{
public:
    B(A a) {cout <<"B" <<a.a1;}
};

void main() 
{
    B b(7);
}

output: 7A B7

Hillel
  • 301
  • 1
  • 11

3 Answers3

6

This has nothing to do with friend.

Because you haven't marked the A constructor explicit, an implicit conversion from int to A occurs.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
2

The compiler is smart enough to think Got an int .... need and A - Wait here is the constructor. Use that

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

As far as I know the compiler calls the constructor A implicitly (because A(int)), so your code is equivalent to:

B b(A(7));
Marco
  • 7,007
  • 2
  • 19
  • 49