AMDG
AMDG

Reputation: 975

Call static method in global scope

I have a class that store a collection of types. This types are registered by other class using a static method from the first class.

Here is some code :

in file classA.h

class A {
    static void RegisterType(std::string name, bool (*checkType)(Json::Value toCheck));
}

In file classB.h

class B {
    static bool CheckType(Json::Value toCheck);
}

In file classB.cpp

// In global scope
A::RegisterType("B", &B::CheckType);

When I do this in classB.cpp my compiler (Visual Studio 2010) think I want to redeclare the A::RegisterType() function.

I try to change return type of A::RegisterType() from void to bool. And then assign the returned value to a variable in classB.cpp :

// In global scope
bool tmp = A::RegisterType("B", &B::CheckType);

This way it does work, but I add a variable in global scope and I don't want to.

How can I call A::RegisterType() from global scope without assign his result to a variable ?

Another question is how can I register the "B" type from classB.cpp ?

Upvotes: 3

Views: 7985

Answers (4)

Sankar
Sankar

Reputation: 41

Generally, CPP sees A::RegisterType("B", &B::CheckType); in global scope as declaration and not invoke it as function call.

So either you have to assign it to a global variable as you mentioned in bool tmp = A::RegisterType("B", &B::CheckType); or you have to do as suggested by quantdev

Upvotes: 0

Anton Savin
Anton Savin

Reputation: 41301

From language-lawyer point of view, 3.5 Program and linkage states:

A program consists of one or more translation units (Clause 2) linked together. A translation unit consists of a sequence of declarations.

So you can't have statements in global scope, you have to place your call inside main() or inside a constructor of some static variable as suggested by quantdev.

Upvotes: 1

JBL
JBL

Reputation: 12907

You can't call functions in the global scope of a file. It must have a scope that relates to the one of the main() function of your program (as in, if you go up in the call stack, you end up in your main() function), or to the scope of a constructor of a class/struct of which you create a static object.

A cpp file isn't executed. It just contains code that will be compiled.

In your case, you could create a static variable of a custom class in your cpp file whose default constructor calls this function.

Upvotes: 2

quantdev
quantdev

Reputation: 23793

There are no "freestanding" function calls in C++ : you can call RegisterType() from another static method (e.g., from main())

A workaround is to mimic a static constructor :

struct StaticInit
{
    StaticInit() 
    {
        A::RegisterType("B", &B::CheckType); 
    }
};

class B
{
    // ...
    static StaticInit si; // Will force the static initialization
};

Upvotes: 4

Related Questions