4pie0
4pie0

Reputation: 29724

static const int in class definition & initialization

If(and only if) you use an initialized member in a way that requires it to be stored as an object in memory, the member must be (uniquely) defined somewhere.

from "The C++ Programming Language"

I have a class

class Bingo{
      std::string name;
    public:
      Bingo(){}
      int i;
      static const int i89=89;
};

and I don't need to have definition like:

const int Bingo::i89;

which is described as necessary. Therefore I don't understand apparently. Could you explain the meaning of that quotation please?

Upvotes: 3

Views: 2466

Answers (2)

Alok Save
Alok Save

Reputation: 206508

When you define a member inside the class it is known as In-class Initialization.

Note that such members can be treated as compile time constants by the compiler because it knows that the value will not change anytime and hence it can apply its own optimization magic and simply inline such class members i.e, they are not stored in memory anymore. Since they are not stored in memory one cannot take the address of such members.The vice versa applies.

The above follows from Bjarne's rationale that each C++ object needs unique definition and hence each object needs to be stored in memory so that they can have unique address and be uniquely identified.

Hence the quote,

If(and only if) you use an initialized member in a way that requires it to be stored as an object in memory, the member must be (uniquely) defined somewhere.

Upvotes: 2

ashcliffe
ashcliffe

Reputation: 138

As far as I remember you need :: to access the static variable when it is defined as it is in your class

Upvotes: 0

Related Questions