Static local variables inside instance members

S

Seb

Is this efficient for a header file and a class? Does a 'static local'
variable get created for each instance or include of the header file? Also,
'return _type().ToString();' does not seem to work.

The error states:
Object.h(16): error C2662: 'DataLib::Object::_type' : cannot convert 'this'
pointer from 'const DataLib::Object' to 'DataLib::Object &'


namespace DataLib
{
class Object
{
public:
virtual inline const char* ToString() const { return
_type().ToString(); }
virtual inline const DataType &GetType() { return _type(); }

protected:
virtual const DataType& _type()
{
static DataType type("Object","Object",0);
return type;
}
};
}
 
L

Leor Zolman

Is this efficient for a header file and a class? Does a 'static local'
variable get created for each instance or include of the header file?

For your first question: Before worrying about efficiency, get a complete
system that does what you want. Then perhaps we'd be in a position to
discuss whether it is implemented in an efficient manner or not.

2nd question: The mechanism of "statics local to a function" is not
directly related to classes and header files; you just have a local static
variable within a function that happens to be a member function. So if
there is one instance of that member function across your entire program,
which in this case it looks like there would be, then yes, only one
instance of the variable you've named "type" would exist.
Also,
'return _type().ToString();' does not seem to work.

That's because you've defined Object::ToString as a const member function.
This makes its "*this" object logically const. Then you're invoking
Object::_type() on that same object...but Object::_type is a /non-const/
member function. The compiler won't let you invoke a non-const member
function on an object that is (in this case, "logically") const. So to fix
it, make Object::_type() be a const member function to match ToString(). Or
make them both non-const. I don't know which is best for your application,
because I don't particularly understand what you're doing. Fortunately, I
don't need to in order to answer these questions.

HTH,
-leor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top