Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ private member declared in header vs static variable declared in cpp file

Tags:

c++

i have a variable that i prefer to declare in a cpp file instead of the header file. It should be accessible to objects of that class only. This variable should have a separate copy for every object of that class. Inheritance is not necessary.

Normally, I'd just declare it in the class definition.

A.h:

class A {
    private:
        int number;
}

But, can I do this instead?

B.h:

class B {
    private:
        // nothing
}

B.cpp:

static int number;
like image 804
Coder Avatar asked Nov 27 '22 07:11

Coder


1 Answers

No, if you take the second approach, you're making it a static variable, which means you won't have a different copy for each object of that class (they'll all share that variable).

Either way, if it should only be accessed by that class, it should go in the class declaration, and should not be a global variable. By making it a static global variable, you're restricting access just to the scope of the file, not to the class. As good programming practice, try using as few global variables as possible.

like image 132
K Mehta Avatar answered Dec 05 '22 11:12

K Mehta