3

I see this code and I can't understand what it mean. I know how we use default constructor but this is not default constructor. What is this?

class X
{
        ...
};

int main()
{
     X f();
}
wilx
  • 17,697
  • 6
  • 59
  • 114
Aryan
  • 159
  • 1
  • 2
  • 6

4 Answers4

8

It declares a function f which takes no parameters and returns a type X.
This is also known as Most Vexing Parse in C++. It is a byproduct of the way the C++ standard defines the interpretation rules for declarations.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • +1. However, this is usually just called a "Vexing parse." Most of the time, I've seen "Most vexing parse" refer to `X f(X())`. – Angew is no longer proud of SO Mar 27 '13 at 07:13
  • 1
    @Angew: Let me be a little more specific, `X f(X())` has always been classically designated as the *Most Vexing Parse*, some consider `X f()` to be as vexing as the former and consider it similar and name it likewise, Some consider `X f()` to be more predictable as a function declaration than the original vexing parse and hence do not consider it as the *Most vexing parse* at all. It is more of an perception based nomenclature than standerdese terminology and so there is no uniformity per se. Glad you brought that up.Thank you. – Alok Save Mar 27 '13 at 07:19
  • @Angew - it's funny, after almost 20 years of C++ development, I just ran afoul of the _most_ vexing parse yesterday. I guess until now I've never tried that construct and I expected it to work, knowing all about the vexing parse. – Edward Strange Mar 27 '13 at 07:20
3

Assume you declare a function:

int Random();

And use it:

int main()
{
   int n;
   n = Random();
}

But implement the Random function after main. Or assume that Random function is defined in some header. You need to instruct the compiler that Random is a function implemented in some other source file, or in some library.

Therefore, an expression like:

T foo();

Would always mean a instruction to compiler that there is a function named foo which returns T. It cannot be an object of type T.

Ajay
  • 18,086
  • 12
  • 59
  • 105
2

Its function declaration of name f

  X          f();
  ^          ^ function   
  return type 

function f() takes no arguments and returns a X class object.

for example its definition can be like:

class X{
   int i;
   // other definition
}

X f(){ 
    X x;
    // some more code
    return x; 
}  

In main you can use like:

int main(){

 X a = f();
 int i = f().i;
}
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
1

This is a function which doesn't take any argument and returns an object of class X

Yogi
  • 3,578
  • 3
  • 35
  • 56