Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ error when requesting member function

Tags:

c++

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?


2 Answers

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

like image 177
Nikos Athanasiou Avatar answered Mar 29 '26 05:03

Nikos Athanasiou


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;
like image 20
Some programmer dude Avatar answered Mar 29 '26 04:03

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!