5

Consider this code:

#include<iostream>
using namespace std;

class A
{
    public:
    A():age(12){}
    int age;
};

int main()
{
    A a();
    cout << a.age << endl;
    return 0;
}

When I compile it using g++, I get an error:

you can not see the member age, because a is not a class A()

Can someone explain this to me? What is A a()?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
minicaptain
  • 1,196
  • 9
  • 16

2 Answers2

12

This line

A a();

declares a function named a, returning A with no arguments. (See Most vexing parse).

What you want is

A a = A(); // value-initialization
A a{}; // the same but only valid in C++11 (and currently not supported by MSVS)

or

A a; // default initialization

C++11, §8.5/10

Note: Since () is not permitted by the syntax for initializer,

X a();

is not the declaration of a value-initialized object of class X, but the declaration of a function taking no argument and returning an X.

For your class, value-initialization == default-initialization (at least for the outcome). See my answer here: C++: initialization of int variables by an implicit constructor for Infos on value- vs. default-initialization for POD or built-in types.

Community
  • 1
  • 1
Pixelchemist
  • 24,090
  • 7
  • 47
  • 71
  • 9
    Er, why not just `A a;`? – GManNickG Jul 18 '13 at 01:47
  • Because newbies often try to initialize a new object on stack using the aboving syntax, `A a();`, wishing to call the default constructor. This, unfortunately, makes confusion. – xis Jul 18 '13 at 01:50
  • @GManNickG : Thanks. In this case `A a;` is the same as `A a(A());` but if A is a POD the first means non-initialized members, the second means zero-initialized members. I just added how to value-initialize. But in this case, default initialization has at least the same result (prbably at a lower cost). – Pixelchemist Jul 18 '13 at 01:56
  • `void who_would_ever_use_this() { void syntax(); } void syntax() {}` –  Jul 18 '13 at 01:58
  • 1
    Why did nobody complain about my second example still being a most vexing parse? Anyway... removed :) – Pixelchemist Jul 18 '13 at 02:00
  • @GManNickG somtimes you want value initialization. The C++11 way is `A a{};`. – bames53 Jul 18 '13 at 02:22
5

It defines a function called a that returns an object of type A. This is known as the "most vexing parse".

jerry
  • 2,581
  • 1
  • 21
  • 32