Search code examples
c++parametersdefault-arguments

initializing default parameter with class member function/variable


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?


Solution

  • 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);
        }
    };