Markus Fjellheim
Markus Fjellheim

Reputation: 357

C++ defining static object inside class

I have a class A in "a.h":

#include "b.h"

class A {
public:
    static B b;
}

I want to initialize b in another function

In "main.cpp":

#include "a.h"
#include "b.h"

int main () {
    ....
    B A::b = B(arg1, arg2);

But the syntax checker give me the error: "member A::b cannot be defined in the current scope." What is the correct way of doing this?

Upvotes: 1

Views: 975

Answers (1)

user0042
user0042

Reputation: 8018

You may set the value in main() but the definition has to be in the global scope:

#include "a.h"
#include "b.h"

B A::b; // <<<<<<

int main () {
    ....
    A::b = B(arg1, arg2);
 // ^^^^

Upvotes: 4

Related Questions