static objects

Why do we need static objects. I have never used but was wondering if there is any scenarios where we need them?thanks.
A static variable runs for the entire time that the program is running. If you are writing a tax calculating program, rather than defining the annual percentage rate (APR) in every function that calls it, you can define/declare it at the top (or in main) and simply pass it down into the portions of the program that use it.

You can, for instance, assign

1
2
3
4
5
6
7
8
9
10
double TaxRate =  4.24%

double AnnualCost(TaxRate)
{

//function crap here

return 0.0;
}


See where the double "TaxRate" is passed down to "Annual Cost"?

This allows you to, for instance, change the annual tax rate once at the top of your program, instead of searching for every instance of it when you do an annual update/release.

Statics are typically reserved for something of that nature. Though many of us (especially in the first few weeks of learning to program) use them in our instructors classes before learning about scope.
im talking abt static objects like for eg:

1
2
3
4
5
6
class A
{
//whatever
};

static A obj;


and in your code if TaxRate is going to be constant throughout the program, then
cost double TaxRate = 4.24;

would be a safer alternative
Last edited on
unfortunately, static is overloaded in C++

if your example is in, say, test.cpp, then obj can only be seen by code inside test.cpp

this type of static is useful for limiting the scope of a variable (has been around since early C)
Another way of limiting the scope of something to a specific cpp file would be to put it in an anonymous namespace.

1
2
3
4
namespace { //no name
    int var;}

//var can only be accessed from within this file now 


Which way is better? Anonymous namespace or static?
The use of static to limit a variable to file scope is deprecated by the C++ standard. The preferred solution is to use an unnamed namespace.
Thanks! I kind of assumed that because namespaces weren't part of C but kfmfe04 said that static was.
Topic archived. No new replies allowed.