Search code examples
c++oopstatic-variablesstatic-initializationdefault-arguments

Default argument for a class function defined in constructor


Is there a possibility to define a variable that will be used as a default argument in the constructor?

#include <iostream>
class Foo
{
public:
    Foo(int x) { num = x;}
    void print(int y = num)
    {
        std::cout << y << std::endl;
    }
private:
    static int num;
};
int main()
{
    Foo f(5);
    f.print();
}

this compiles but I get linking errors LNK2001 unresolved external symbol "private: static int Foo::num" (?num@Foo@@0HA)


Solution

  • It's possible, you just have to declare/initialize the static variable outside the class:

    Live demo

    #include <iostream>
    
    class Foo
    { 
        //..
    };
    
    int Foo::num; //<-- or 'int Foo::num = 0;'
    
    int main()
    {
        //...
    }