1

how to correct it so I can display the static int by

cout<<A::a<<endl;

like in an example below?

#include <iostream>
using namespace std;
class A{
    public:
        static int a = 0;
};

int main()
{
    cout << A::a << endl;
    return 0;
}

2 Answers 2

5

Inside the class definition, the static members are only declared and not defined. By default, only definitions have initialization, with the exception that for static constants of integral types the declaration can have the initialization.

The problem in your program is that the static member is used (std::cout << A::a is odr-use for non-const static member attributes), but you have no definition. You need to define the variable in a single translation unit in your program by adding:

int A::a = value;

(Note that because the static member is not const, you cannot provide an initializer inside the class definition, so you need to remove the = 0 from the declaration in class definition. Also note that you can skip the = value in the initialization if value == 0, as static initialization will set A::a to 0 before any other initialization)

Sign up to request clarification or add additional context in comments.

1 Comment

+1 in this particular case making it const & initializing it inside the class would work.
5

Either:

class A{
    public:
        static const int a = 0;
};

(const integral types can be initialized inside the class definition)

or

class A{
    public:
        static int a;
};

int A::a = 0;

6 Comments

In the second example, why I have to redeclare 'a' as an int?
@RobertKilar previously you just declared it, now you're defining it. That's just the syntax.
but type NAME ... is declaration
@RobertKilar and definition. You can have as many declarations as you want, you can't have multiple definitions and you can't define something without specifying the type.
Note that for a static constant member you might still need to provide a definition (without initialization if the initialization is present in the declaration) if it is odr-used (you create a pointer or reference to the static member attribute)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.