Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing Temporary variables to reference arg in Constructor works. but not for functions in general. Why? [duplicate]

Tags:

c++

Consider the following code.
Here, A a(B()) compiles even though the constructor is A(B& b); But print(B()) does not work. But print is also declared as print(B& b); Why this inconsistency?

#include <iostream>
using namespace std;

class B{
    public:
            char b;
};

class A {
    public:
            B b;
            A(B& b);
            A() { }
};

A::A(B& b) {
    this->b = b;
}

void print(B& b) { }

int main(){
    print(B());
    A a(B());
}
like image 649
user855 Avatar asked Dec 23 '22 07:12

user855


2 Answers

It compiles because it's not creating an instance of A. It's declaring a function named a that returns an A and receives one unnamed parameter of type pointer-to-function-returning-B. Since it's just a declaration, it compiles. If you're referred to a elsewhere in the code, you'd have seen additional problems. For why that's a function declaration instead of an object definition, the term to look up is most vexing parse.

like image 65
Rob Kennedy Avatar answered Dec 24 '22 22:12

Rob Kennedy


This:

A a(B());

isn't doing what you think. It is actually parsed as a function declaration. This is commonly referred to as the "most vexing parse" in C++ (there are many posts here about it, if you search for that phrase).

like image 34
James McNellis Avatar answered Dec 24 '22 20:12

James McNellis