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?

1
  • 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... Commented Aug 14, 2020 at 4:54

1 Answer 1

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);
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.