Static Variables in Member Functions

Static variables in member functions

Since class A is a non-template class and A::foo() is a non-template function. There will be only one copy of static int i inside the program.

Any instance of A object will affect the same i and lifetime of i will remain through out the program. To add an example:

A o1, o2, o3;
o1.foo(); // i = 1
o2.foo(); // i = 2
o3.foo(); // i = 3
o1.foo(); // i = 4

Static variable inside of a function in C

There are two issues here, lifetime and scope.

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

static variable inside member function of base class

Static variables declared in member functions will keep their value between function calls. There will be only one copy over all instances, and all accesses to indicator from different instances will affect the same indicator. This means indicator will only be initialized once.

See here for more info: Static variables in member functions

Also this code does not toggle indicator, it always sets it to true if it's false (which I'm sure is the behaviour you want).

if(!indicator)
{
...
indicator=true;
}

making static variables in member functions independent for each instance

In circumstances where declaring data members become costly(need for sparse members that are not used so often), An instance indepent collection - normally an associative one - may come in handy. Knowing nothing more about the OP's intention, std::map family of classes can be used as first speculation. We need to have one counter per visited object in A::foo, but not for unvisited instances(i.e. A instances not calling A::foo). This was the the simplest first solution I came up with:

void A::foo(){
static std::map<A*,std::size_t> i;
++i[this];
//...
};

Upon call to std::map::operator[] on an object not in the map, the associated value is default constructed in a memory location already zeroed by the allocator( in short words 1st-timers are automatically initialized to 0).

C++ static member functions and variables

Static methods can't use non-static variables from its class.

That's because a static method can be called like Environment::display() without a class instance, which makes any non-static variable used inside of it, irregular, that is, they don't have a parent object.

You should consider why you are trying to use a static member for this purpose. Basically, one example of how a static method can be used is as such:

class Environment
{
private:
static int maxRobots;
public:
static void setMaxRobots(int max)
{
maxRobots = max;
}
void printMaxRobots();
};

void Environment::printMaxRobots()
{
std::cout << maxRobots;
}

And you would have to initialize on the global scope the variables, like:

int Environment::maxRobots = 0;

Then, inside main for example, you could use:

Environment::setMaxRobots(5);

Environment *env = new Environment;
env->printMaxRobots();
delete env;

Static class member variable and static variable in c++

The only reason is code cleanliness. You cannot restrict access to a global static variable like

static int globalValue=5;

it is (at least) visible in the source file you defined it.
With a class static, you can give a user of your class hints, how you wish to access it or be accessed. It is only visible within the class scope:

class myGlobalContainer
{
public:
static int myInt;
protected:
static float myFloat;
private:
static bool myBool;
};

the access of myInt is done by:

int x=myGlobalContainer::myInt;

the public modifier gives the user the hint that you see this value as part of the myGlobalContainer and wish him to use it. You do not polute the global namespace like you do with the globalValue.

The modifier protected and private shows that you do not wish that an "outsider" access those values.

protected and private static attributes are mostly used to share information between the instances of a class, for e.g. a instance counter:

class myGlobalContainer
{
public:
myGlobalContainer()
{
if(counter==0)
DoSomeSpecialGlobalInit();
counter++;
}
~myGlobalContainer()
{
counter--;
if(counter==0)
DoSomeSpecialGlobalUnInit();
}
private:
static int counter=0;
};

public static attributes are often seen with const. They mostly give a user a shortcut. For e.g.:

COLOR white=COLOR::WHITE;

instead of:

COLOR white=COLOR::FromAGBR(255,255,255,255);

Add least:
If you should use statics or not is a complete other discussion.

C++ static variable in member function

does C++ allocate memory for variable var even before foo is created?

Yes, it does, in the sense that the memory the value of var will eventually occupy is reserved upfront. When the constant value of 2 is written into var's memory is implementation-defined. The only thing the standard guarantees is that it is going to happen at some point before you call foo::bar().

If you initialize your static variable using an expression with side effects (say, by making a function call) this call will be performed the first time that you execute the function.

after foo has been destroyed, var will exist throughout the program.

var will exist independently of any instances of foo that your program may create. When you call foo::bar() at any time, you would get the last value of var that your program has assigned to it.

Trouble initializing and incrementing a static member variable

The two errors in your code are:

  1. Your call to display_total_no_of_student() doesn't provide either a class object or a class name for that function, so the compiler is looking for a 'free' function of that name/signature, which it doesn't find.

  2. Although you have provided a declaration for the static count_total_no_of_students_enrolled member, you haven't given an actual definition for it (which must be done outside the class definition).

For the first issue, you would most likely want to declare display_total_no_of_student as a static function (because it doesn't use or require any specific instance of the Student class). For the second issue, just provide a definition of the count_total_no_of_students_enrolled member, which should be initialized to zero.

Here is a 'working' version of your code, with these issues addressed:

#include <iostream>

using namespace std;

class Student {
public:
string student_name;
double CGPA;
string degree;
static unsigned int count_total_no_of_students_enrolled; // This DECLARES the variable but doesn't define it!
const string uni_name = "umt";

void setstudent(string a, double b, string c);
void displaystudent();
static void display_total_no_of_student(); // Declare this function as static!
};

unsigned int Student::count_total_no_of_students_enrolled = 0; // This is the REQUIRED definition and initial value!

void Student::setstudent(string a, double b, string c)
{
student_name = a;
CGPA = b;
degree = c;

count_total_no_of_students_enrolled++; //******THIS ISN'T WORKING******
}

void Student::displaystudent()
{
cout << "\n=> Student details:\n";
cout << " Name: " << student_name << ",CGPA: " << CGPA << "\n Degree: " << degree << ",University: " << uni_name;
}

void Student::display_total_no_of_student()
{
cout << "\n Total Students Enrolled: " << count_total_no_of_students_enrolled;
}

int main()
{
Student s1, s2, s3;

s1.setstudent("John Doe", 3.5, "CS");
s2.setstudent("Jane Doe", 3.9, "CS");
s3.setstudent("Jim Doe", 3.8, "CA");

s1.displaystudent(); s2.displaystudent(); s3.displaystudent();

Student::display_total_no_of_student(); // Specify the class name to access a static member function!

return 0;
}

Please feel free to ask for any further clarification and/or explanation.



Related Topics



Leave a reply



Submit