Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct place to initialize class variables?

Tags:

Where is the correct place to initialize a class data member? I have the class declaration in a header file like this:

Foo.h:

class Foo { private:     int myInt; }; 

Then I try to set a value to myInt in the corresponding .cpp file:

Foo.cpp:

int Foo::myInt = 1; 

I get a compiler error for redefining myInt. What am I doing wrong???

like image 840
Tony R Avatar asked Apr 06 '09 19:04

Tony R


People also ask

Where do you initialize variables?

Variables can store strings of text and numbers. When you declare a variable, you should also initialize it. Two types of variable initialization exist: explicit and implicit. Variables are explicitly initialized if they are assigned a value in the declaration statement.

Can you initialize variables in a class?

You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.

How do you initialize a class variable in C++?

In C++, class variables are initialized in the same order as they appear in the class declaration. Consider the below code. The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.


1 Answers

What you have there is an instance variable. Each instance of the class gets its own copy of myInt. The place to initialize those is in a constructor:

class Foo { private:     int myInt; public:     Foo() : myInt(1) {} }; 

A class variable is one where there is only one copy that is shared by every instance of the class. Those can be initialized as you tried. (See JaredPar's answer for the syntax)

For integral values, you also have the option of initializing a static const right in the class definition:

class Foo { private:     static const int myInt = 1; }; 

This is a single value shared by all instances of the class that cannot be changed.

like image 132
Eclipse Avatar answered Oct 04 '22 04:10

Eclipse