-1

I tried to initialize a static member variable with a member initialization list. But I got errors like

static variable cannot be initialized via constructor

For example, my class sample has a static member variable y of type int. I couldn't do this:

sample(int a):y(a){}

Why is that so?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Deepika
  • 75
  • 4

2 Answers2

3

A static member variable does not belong to a single instance of your class. So when a constructor (which is a function that initializes an instance) runs, the static member already is initialized. You cannot initialize it again.

You can however assign to it in the constructor's body:

sample(int a) {y = a;}

though that will rarely be useful.

Again, remember: Every time a constructor runs, it constructs one instance, while static members exist across all instances.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
0

A static member is per-class, not per-instance, so a static member will only be constructed once in the lifetime of the program. A constructor is invoked every time you make an instance of the class.

What you want to do is initialize the static member inside of a .cc file that will be liked in.

Something like :

// Foo.h

class Bar {
    public :
       Bar(int) {
       }

};

class Foo {
  public:
         static Bar MrStatic;
};

// Foo.cc

Bar Foo::MrStatic(10);
abhishek_naik
  • 1,287
  • 2
  • 15
  • 27
D Hydar
  • 502
  • 2
  • 8