Variable declaration taken as a function pointer declaration

B

Bolin

When compiling the following code:

Code:
#include <iostream>

struct B {};

struct A
{
  A(B b1, B b2) {};
  void foo() { std::cout << "foo called" << std::endl; }
};

int main(int argc, char * argv[])
{
  A a(B(), B());
  a.foo();
  return 0;
}
[\code]

the compiler will interprete the first line of the main function as a
function pointer declaration, and thus will fail at the next line. Does
somebody know why this is so, and if there is an elegant way to solve
this problem that does not involve temporary variables?

B.
 
V

Victor Bazarov

Bolin said:
When compiling the following code:

Code:
#include <iostream>

struct B {};

struct A
{
A(B b1, B b2) {};[/QUOTE]
..                  ^^^
Trailing semicolon is extraneous here.
[QUOTE]
void foo() { std::cout << "foo called" << std::endl; }
};

int main(int argc, char * argv[])
{
A a(B(), B());
a.foo();
return 0;
}
[\code]

the compiler will interprete the first line of the main function as a
function pointer declaration, and thus will fail at the next line. Does
somebody know why this is so, and if there is an elegant way to solve
this problem that does not involve temporary variables?[/QUOTE]

It is so because the language designers had to make a decision and they
picked the "If it looks like a declaration, it is a declaration" solution.

You can work around it by adding an extra set of parentheses around the
arguments:

   A a((B()), (B()));

V
 
D

deane_gavin

Bolin said:
When compiling the following code:

Code:
#include <iostream>

struct B {};

struct A
{
A(B b1, B b2) {};
void foo() { std::cout << "foo called" << std::endl; }
};

int main(int argc, char * argv[])
{
A a(B(), B());
a.foo();
return 0;
}
[\code]

the compiler will interprete the first line of the main function as a
function pointer declaration, and thus will fail at the next line. Does
somebody know why this is so, and if there is an elegant way to solve
this problem that does not involve temporary variables?[/QUOTE]

It is so because your code could either be read as a function
declaration or a variable definition and the rule to disambiguate this
is "if it could be a function declaration, it is a function
declaration". The solution is to change the line that defines a to

A a((B()), (B()));

Gavin Deane
 
B

Bolin

Thanks for your answer and your solution -- the thing that surprised me
is that a bare B() could be interpreted as a function pointer.

B.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top