Re: Class wide object declaration question
On May 15, 6:27 pm, jeff_j_dun...@yahoo.com wrote:
Hello,
Whenever I need class wide access to an object, I declare it
dynamically:
class myClass
{
...
myObject* obj; // declared dynamically
...
Then I usually create an instance of the object within the
constructor:
myClass::myClass()
{
...
string str = "whatever";
obj = new myObj(str); // parameter passed to obj
...
Doing this, I am able to access myObj::obj anywhere from within my
class. Is it possible to declare obj as a static member variable? If
so, I have not been able to figure out how to do it.
When you say "statically", what do you mean. If you mean the old
(somewhat deprecated) meaning of local to the compilation unit, then
you can't do that for a class. If you mean that there is one instance
per class, then that's the meaning of static in a class/struct.
I think this code below covers all the sorts of "storage class" that
exist.
static int s;
namespace { int y; /* anonymous namespace for y */}
// for most purposes, s and y are the same storage class - i.e.
visible in this
// compilation unit only.
struct A
{
int a; // one a per instance of A
static int b; // one b - ever
const static int c = 5; // only allowed to do this for integral
types.
A * instance()
{
int f; // created every time execution passes this point.
(auto)
static A v; // only one v in the entire program
// and only created once - the first time
through.
return &v;
}
};
int A::b = 2; // need to define b somewhere. usually in one place only
// special ones - these may show up in the new revision of the
standard
void f()
{
register int i; // this is like auto but you can't take the address
of i
// which allows the compiler to do optimizations
for i
}
__thread int t; // one instance of t per thread.
.... did I miss one ?