1

In the example below I do

MyClass a ();

I've been told that a is actually a function that returns a MyClass but neither of the following lines work.

MyClass b = a();
a.a = 1;

So what is a and what can I do with it?

#include "stdafx.h"
#include "iostream"
using namespace std;

class MyClass {
    public:
        int a;
};

int _tmain(int argc, _TCHAR* argv[])
{
    MyClass a ();
    // a is a function? what does that mean? what can i do with a?

    int exit; cin >> exit;
    return 0;
}
user1873073
  • 3,580
  • 5
  • 46
  • 81
  • 1
    `MyClass b = a();` does work; it just won't link because you haven't provided a definition of `a`. – ecatmur May 09 '13 at 18:12
  • possible duplicate of [Most vexing parse: why doesn't A a(()); work?](http://stackoverflow.com/questions/1424510/most-vexing-parse-why-doesnt-a-a-work) – SomeWittyUsername May 09 '13 at 18:25

1 Answers1

8

I've been told that a is actually a function that returns a MyClass [...]

That is a function declaration. It just declares a function called a and makes the compiler aware of its existence and its signature (in this case, the function takes no arguments and returns an object of type MyClass). This means you may provide the definition of that function later on:

#include "iostream"

using namespace std;

class MyClass {
    public:
        int a;
};

int _tmain()
{
    MyClass a (); // This *declares* a function called "a" that takes no
                  // arguments and returns an object of type MyClass...

    MyClass b = a(); // This is all right, as long as a definition for
                     // function a() is provided. Otherwise, the linker
                     // will issue an undefined reference error.

    int exit; cin >> exit;
    return 0;
}

MyClass a() // ...and here is the definition of that function
{
    return MyClass();
}
A.H.
  • 63,967
  • 15
  • 92
  • 126
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451