Why does this not compile?

Started by
4 comments, last by swiftcoder 9 years, 10 months ago
test.cpp:

#include <iostream>
#include <string>

using namespace std;

class Test {
private:
	string str;
public:
	void Setstr(const string &st);
	void Getstr(string &st);
};

void Test::Setstr(const string &st) {
	this->str = st;
}

void Test::Getstr(string &st) {
	st = this->str;
}

int main() {
	string s;
	Test t();
	t.Setstr("Test");
	t.Getstr(s);
	
	cout << s << endl;
	return 0;
}
Result:
$ g++ -Wall -o test test.cpp
test.cpp: In function ‘int main()’:
test.cpp:25:4: error: request for member ‘Setstr’ in ‘t’, which is of non-class type ‘Test()’
  t.Setstr("Test");
    ^
test.cpp:26:4: error: request for member ‘Getstr’ in ‘t’, which is of non-class type ‘Test()’
  t.Getstr(s);
    ^
Well?
Advertisement

It's the most vexing parse.

Compiler thinks

Test t();

is a prototype for a function called t which returns a Test and takes no parameters. Omit the parentheses and it should work (i.e. use Test t; instead of Test t();).

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

Or use "Test t{}". That gives uniformity to how variables are declared and initialized.

Or use "Test t{}". That gives uniformity to how variables are declared and initialized.

Note that this is C++11 syntax, and may not yet be understood by all compilers, especially if you're using an older version (e.g., Visual Studio 2012 or older). So don't be surprised if you try it and get further compilation errors.

"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
Well, the OP uses g++, so worst case he needs to add --std=c++11 depending on what his defaults are. Unless his gcc is really old.

It's the most vexing parse.

And just in case anyone thought that was just odd phrasing on Paradigm Shifter's part, the Most Vexing Parse is an actual phenomenon.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

This topic is closed to new replies.

Advertisement