Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does A a() mean? [duplicate]

Tags:

c++

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()?

like image 642
minicaptain Avatar asked Jul 18 '13 01:07

minicaptain


2 Answers

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.

like image 78
Pixelchemist Avatar answered Dec 07 '22 14:12

Pixelchemist


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

like image 34
jerry Avatar answered Dec 07 '22 15:12

jerry