2
class C {
private:
     int n{ 5 };

public:
    int return5() { return 5; }
    void f(int d = return5()) {

    }

    void ff(int d = n) {

    }


};

Why I can't initialize the functions default parameters with member class? I get an error: a nonstatic member reference must be relative to a specific object.

I think the problem because no object has been instantiated yet, but is there any approach to do it?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
slah Omar
  • 45
  • 1
  • 4
  • Are you sure you want `return5` and not `returnN`? As you can see, `return5` is not too bad. The `void f(int d = n)` hinted at in the question title... – user4581301 Aug 14 '20 at 04:54

1 Answers1

3

The default argument is considered to be provided from the caller side context. It just doesn't know the object on which the non-static member function return5 could be called on.

You can make return5 a static member function, which doesn't require an object to be called on. E.g.

class C {
    ...
    static int return5() { return 5; }
    void f(int d = return5()) {
    }
    ...
};

Or make another overload function as

class C {
private:
     int n{ 5 };
public:
    int return5() { return 5; }
    void f(int d) {
    }
    void f() {
        f(return5());
    }
    void ff(int d) {
    }
    void ff() {
        ff(n);
    }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405