Reputation:
I have a class like so
class action {
int val;
// some other members
public:
action() : val(0) { } // default constructor initializes action type to 0
action(int val) : val(val) { }
// some other member functions
int getVal() { return val; }
};
and when used in a simple scenario
action obj1(), obj2(2);
cout << "Initial state : { " << obj1.getVal() << ", " << obj2.getVal() << " }\n";
I get a compilation error
error: request for member ‘getVal’ in ‘obj1’
What is going on here?
Upvotes: 3
Views: 94
Reputation: 310920
In this statement
action obj1(), obj2(2);
you declared function
action obj1()
that has return type action and has no parameters and an object of type action
action obj2(2);
Change this statement to
action obj1, obj2(2);
The other way to avoid such an error is to write
action obj1 {}, obj2(2);
provided that your compiler supports the list initialization.
The problem is that there is an ambiguity between function declarations and object definitions with empty lists of arguments. C++ resolves the conflict for benefit of function declarations.
Upvotes: 0
Reputation: 11431
To fix above mentioned error remove () in obj1 while declaring.
Upvotes: 0
Reputation: 31489
That's because you are not declaring an obj1
of type action
action obj1()
declares a function obj1 that takes no parameters and returns an action object. Prefer the c++11 brace initialization to call default constructor
action obj1{}
or just don't use those extra parentheses.
You can google for this issue, as c++ most vexing parse
Upvotes: 3
Reputation: 409136
It's because the declaration
action obj1();
actually declares obj1
to be a function which returns an action
object. Unless you need to pass arguments to the constructor, drop the parentheses:
action obj1;
Upvotes: 3