polfosol ఠ_ఠ
polfosol ఠ_ఠ

Reputation: 1898

Calling static methods in constructor

This seems a bit strange to me. Since a static method can have an instance of the class, one naturally expects that the compiler should not allow calling static methods inside the constructor. But I have tested the following code with every compiler and ironically, none of them gave me a single warning. Although in execution time they all throw exceptions. Am I missing something here?

#include <iostream>

class Foo
{
public:
    inline Foo()
    {
        std::cout << "testing: var = " << bar() - 1 << '\n';
    }
    ~Foo(){}

    static int bar()
    {
        Foo f;
        f.var = 10;
        return f.test();
    }
private:
    int var;
    int test()
    {
        return var + 1;
    }
};

int main()
{
    Foo foo;
    return 0;
}

Live example

Upvotes: 0

Views: 6606

Answers (3)

Aconcagua
Aconcagua

Reputation: 25516

It is not illegal to call static functions from within the constructor. Only, you are getting a stack overflow, if you do it like you do. This results in

Foo() calls bar(); bar() calls Foo(); Foo() calls bar(); bar() calls Foo(); ...

Until no stack is left.

This is exactly the same as if you had:

void f1();
void f2()
{
    f1();
}
void f1()
{
    f2();
}
int main(int, char*[])
{
    f1();
    return 0;
}

Only two global functions, nothing more. Would have been all the same in C, too (but you have do declare void f(void) there), or Java, C#, perl, python, ...

Upvotes: 5

Smeeheey
Smeeheey

Reputation: 10316

There is no reason not to call a static (or in fact a non-static) member function in a constructor (although it is not recommended to call virtual functions).

Upvotes: 1

ixSci
ixSci

Reputation: 13698

What warnings are you expecting? What you've written is an infinite recursion which has nothing to do with static member functions. You can do it with any other function inside or outside a class.

Static functions are not much different from the free ones. So free functions should also be banned from constructor? There is no point in forbidding to call static functions from constructors.

Upvotes: 2

Related Questions