SomeWittyUsername SomeWittyUsername - 1 year ago 58
C++ Question

Unclear type conversion/promotion

The below code compiles and runs without warning.
It's not clear to me what kind of conversion goes on in the call to

. The function expects a reference to type
, yet it accepts a pointer to type
. When removing the constructor
the compilation fails, claiming failure to initialize reference type:

Invalid initialization of reference of type 'const B&' from expression of type 'PA {aka A*}'

I don't see why the constructor is invoked in the first place instead of compilation failure. Any explanation to this?

#include <iostream>

typedef struct A
int x;
int y;
} *PA;

class B
B(PA pa):m_pa(pa){}
int getPa() const{return m_pa->x;}
PA m_pa;

void func(const B& b)
std::cout << b.getPa();

int main()
A a = {5,7};
PA pA = &a;

func(pA); //Why does this compile and what is the outcome??
return 0;


Answer Source

As explained here:

Single-argument constructors: allow implicit conversion from a particular type to initialize an object.

Hence, there is an implicit conversion option from PA to B due to the constructor:

    B(PA pa)

So when you called:


the pA pointer converted to B object and then used by func

(similar SO post)