0

Here is my code

#include <iostream>

using namespace std;

class MyTestClass
{
    int MyTestIVar;

    public: 
        MyTestClass(void);
        int firstCallMethod(void);
        int secondCallMethod(void);
};

MyTestClass::MyTestClass(void)
{
    MyTestIVar = 4;
}
int MyTestClass::firstCallMethod(void)
{
    return secondCallMethod();
}
int MyTestClass::secondCallMethod(void)
{
    return MyTestIVar;
}

int main(int argc, char *argv[])
{
    MyTestClass mTC;
    cout << mTC.firstCallMethod() << endl;
    return 0;
}

If use use

MyTestClass mTC();

instead it will disallow me to call any member functions and display this error

./experiment.cpp: In function ‘int main(int, char**)’: ./experiment.cpp:31:14: error: request for member ‘firstCallMethod’ in ‘mTC’, which is of non-class type ‘MyTestClass()’

I read the posts on value-initialize etc, but this error still doesn't seem logical to me. Why would this affect member functions?

And help greatly appreciated :-)

rubixibuc
  • 7,111
  • 18
  • 59
  • 98
  • Are you *sure* this code example is enough to reproduce the error? Also do you mean that if you replace the line "MyTestClass mTC;" with "MyTestClass mTC();" only then the error occurs? – Ivaylo Strandjev Jan 17 '12 at 10:06

2 Answers2

5
MyTestClass mTC();    

Does not declare an object of the MyTestClass class, as you think.

It Actually, declares a function by the name of mTC which does not take any parameters and returns an MyTestClass object.

This is known as the Most Vexing Parse in c++.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Weird, isn't that an error on the parsers fault though because in c++ you can't declare functions within functions? Or is only you can't define a function within a function? – rubixibuc Jan 17 '12 at 10:09
  • @rubixibuc: It's one of the strange dark corners of C++,Which you only get to know when you get bitten by it & believe me most of us who know it have been bitten by it :) – Alok Save Jan 17 '12 at 10:13
3

You have stumbled upon the most vexing parse.

The line

MyTestClass mTC();

is parsed as a function prototype of a function named mTC which has no arguments and returns an instance of MyTestClass.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621