Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to specify the data type again when we define a static variable outside of the class

Tags:

c++

oop

static

I've been solving hackerrank questions. I've encountered with a virtual function question and I've been asked to create a class named Student . This class must have a int variable named cur_id ( current id). Here is the class;

class Student: public Person{

    public:

    static int id;

    Student(){
        cur_id = ++id;
    }


};

int Student::id = 0;

I've been asked to increase the cur_id +1 while every new object of the class is being created. So that, i decided to increase the cur_id in the constructor. As you can see, I've declared a static int variable in the class as static int id. Then I wanted to initialize its value with zero out of the class. But when I tried it as Student::id = 0;, I couldn't access the id variable. I needed to specify its datatype one more time like I am declaring the variable again as int Student::id = 0;. What's the reason of it, why do I need to declare a static variable two time ? I know that it's a newbie question and may have an easy answer, but I couldn't find my answer in another topics. Thanks in advance.

like image 205
Ozan Yurtsever Avatar asked Dec 10 '18 09:12

Ozan Yurtsever


People also ask

Why do we initialize static variables outside the class?

They are initialized through a constructor or other member functions. This happens when an object is instantiated. However for static members, the objects need not be instantiated. Hence they need to be initialized once outside of the class.

Why is static data member defined outside the class definition?

Because static member variables are not part of the individual class objects (they are treated similarly to global variables, and get initialized when the program starts), you must explicitly define the static member outside of the class, in the global scope.

Can static variables be declared outside the class?

Difference between static variables and global variablesStatic variables can be declared both inside and outside the main function while the global variables are always declared outside the main function.

Why do we need to declare a variable as static?

A variable is declared as static to get the latest and single copy of its value; it means the value is going to be changed somewhere.


1 Answers

The second time you do not declare it. You define it. This is why this is typically done in an implementation file (.cpp) while the class declaration is done in a header file (.h).

like image 78
Benjamin Bihler Avatar answered Oct 02 '22 10:10

Benjamin Bihler