WCGPR0
WCGPR0

Reputation: 789

How do I instantiate a variable in C++ only once?

In Java, static variables are only instantiated only once and behave like global variables.

In terms of efficiency and speed, is there a way to do this in C++? Since static, in C++, blocks don't exist.

If there's a constant like Foo = 17, and I'm making multiple instances of the class, how do I keep the constant from being instantiated that many times?

Would the same syntax apply to structs too?

Upvotes: 0

Views: 1418

Answers (2)

Ravi Verma
Ravi Verma

Reputation: 184

You can use the same keyword ie static in c/c++ See msdn document here.

The static keyword can be used to declare variables, functions, class data members and class functions. By default, an object or variable that is defined outside all blocks has static duration and external linkage. Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends. External linkage means that the name of the variable is visible from outside the file in which the variable is declared. Conversely, internal linkage means that the name is not visible outside the file in which the variable is declared.

Upvotes: 2

ChiefTwoPencils
ChiefTwoPencils

Reputation: 13930

It works the same way. You might have a function that you'd like to keep track of the number of times the function is called throughout the life of the program, well it's as easy as...

int foo()
{
   static int times = 0;
   ...
   return times;
}

Pretty pointless but nonetheless it does what you're describing. You can do the same thing in a class.

class myClass 
{
   public:
   static int many;
   ...
   int getMany() { return many; }
};

Here the function always returns the number of instances that exist.

Upvotes: 1

Related Questions