Setting value to an static const unsigned int

I have a class that has a static constant unsigned int variable. I want to initialize this variable depending on the arguments passed when the program starts. I have created an example of what I want to do to try and figure out how to implement this.

main.cpp

int main() { const unsigned int legs = 4; Dog dog(legs); return 0;
}

Dog.h

class Dog {
public: Dog(const unsigned int legs); ~Dog();
private: static const unsigned int legs;
};

Dog.cpp

Dog::Dog(const unsigned int l) : legs(l) {
}
Dog::~Dog() {
}

In main, I created a variable to simulate the value being passed from the program when it runs.

The compiler gives the following errors:

/home/jota/ClionProjects/Caca/Dog.cpp: In constructor ‘Dog::Dog(unsigned int)’:
/home/jota/ClionProjects/Caca/Dog.cpp:7:34: error: ‘const unsigned int Dog::legs’ is a static data member; it can only be initialized at its definition Dog::Dog(const unsigned int l) : legs(l) { ^
make[2]: *** [CMakeFiles/ Error 1
make[1]: *** [CMakeFiles/ Error 2
make: *** [all] Error 2

I have been looking on the internet and a saw a few examples of a static const int working the way I used it, or I might be missing something. I'm compiling with -std=c++11.

2

3 Answers

static field is a member of the class, not member of the instance. In constructor initializer list you can only initialize members of the object (and super objects of course), therefore that error.

Change the definition to:

const unsigned int legs;

The constructor is used to initialize the fields of a concrete object. When you declare something as static, it belongs to the whole class, not one object in particular. That's why you cannot instantiate that value in a constructor.

You can either remove static, and have const unsigned int legs, but I'm guessing you don't want that since all dogs have 4 legs.

The other more logical thing you can do in your Dog.cpp file is this:

unsigned int Dog::legs = 4;
2

Unlike a non-static member such as this,

class A {
public: int a;
};
int main(void) { A a1, a2; a1.a = 10; a2.a = 20; return 0;
}

a static member of a class is not part of any instance of the class. This means that in the example above, if a were static, a1 and a2 would not each have their copy of a.

A static member of a class can be thought of as a "global" variable that exists within the scope of the class.

Therefore, to access a static member of a class, you do this:

class A {
public: static int a;
};
int A::a = 0; //A static member variable needs to be defined in a translation unit(or .c/.cpp file)
int main(void) { A::a = 50; return 0;
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like