SomeWittyUsername SomeWittyUsername - 3 months ago 10
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

func
. The function expects a reference to type
B
, yet it accepts a pointer to type
A
. When removing the constructor
B(PA A)
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
{
public:
B(PA pa):m_pa(pa){}
int getPa() const{return m_pa->x;}
private:
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;
}


Live: https://ideone.com/y8Z2O9

Answer

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:

    func(pA)

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

(similar SO post)

Comments