1

In c++ 17 when attempting to initialize a member pointer through the scope (not in the member initializer list) of the non-default constructor an error is thrown, as stated below:

error: expression cannot be used as a function

Why is this invalid? I understand from the error that the pointer has been implicitly initialized, hence the constructor cannot be called. I have read the relevant passage from the standard and it's still unclear, as it states that it should have indeed not been initialised yet and therefore my code should be valid.

class Container{
    private:
        int length;
        double* data;
    public:
        Container(): length(0), data(nullptr) {}

        Container(const int length): length(length) {data(nullptr)}
};

int main()
{
  Container a(2);
}
EmVee
  • 81
  • 6

2 Answers2

9

Initialization can only be in the constructor initialization list. In the function body data(nullptr) is parsed as a function call (as told by the compiler in the message).

If you want to set a value inside the function body you must use plain assignment:

data = nullptr;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

This:

    Container(const int length): length(length) {data(nullptr)}

Should be:

    Container(const int length): length(length), data(nullptr) {}
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Reason for my initialization structure is that there will be conditional statements within the constructor scope, the snipped I showed was to simplify the question. My question is why initialising it within the scope is invalid. Thanks! – EmVee Dec 02 '19 at 12:20
  • 2
    Because it is not valid syntactical element. `data` is not a function and cannot be used like `data(whatever)`. Member initializer list uses `member-name(init-value)` which is very specific and cannot be used elsewhere. – Tanveer Badar Dec 02 '19 at 12:23
  • 1
    Don't show otherwise-broken code "to simplify the question". Show a real, actual, concrete question, so as to avoid completely wasting our time. – Lightness Races in Orbit Dec 02 '19 at 12:35
  • @EmVee There is a notion here that you should present _a concrete problem_ so that we do not go in circles chasing ghosts. This is not "attitude", we get thousands of questions a day and you are _competing_ for our free time, so it's in your best interests to make it as easy as possible to give you the best help possible. If that's not a mission you're interested in, that's your choice! In this case, it would have been easier to understand what you were doing had you included this detail about conditionals to begin with; the solution in this answer does not actually allow for that..... – Lightness Races in Orbit Dec 03 '19 at 13:59