Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Possible VC++ bug concerning static functions vs. non-static variables

Status
Not open for further replies.

cra

Programmer
Sep 23, 2002
34
DE
Hi all,

what do you think of the following?

Example 1 compiles:
Code:
class MyClass
{
public:
	static void func();
private:
	bool itsFlag;
};

void MyClass::func()
{
	int i = itsFlag ? 0 : 1;
}

Example 2 does not compile:
Code:
class MyClass
{
public:
	static void func();
private:
	bool itsFlag;
};

void MyClass::func()
{
	bool b = itsFlag;
}

As far as I understand C++, the compiler must complain "error C2597: illegal reference to data member 'MyClass::itsFlag' in a static member function" for both examples, not only for the second, because itsFlag is a non-static variable used in a static function!

I am *slightly* confused.

P.S. Using MSVC++ 6.0 Enterprise + Service Pack 5
 
I have no idea why the first example works. It should produce the same error. Try a "Rebuild All" on the one that worked. I am curious if you will see the error.

// What is supposed to happen

Static functions can NOT access non static data members. Non-static functions can access both static and non-static data members.

When you declare a member variable as static, it is the same throughout all the classes. When you modify it in instance one, you modifiy int in instances two through n as well. On the other hand, non-static data members are different for each instance.

The static functions also only have one instance. They can not differentiate between which instance of the itsFlag to access.

Matt

 
Actually, I extracted both examples from a bigger IDE-based project and separately compiled them using the cl command line compiler, so there are no hidden temp files, pch files or whatever. The first one still compiles. And I just did a) a "clean"/"build" and b) a "rebuild all" on my original IDE project with the same "error" - it compiles!

Concerning your "what is supposed to happen": Exactly my thoughts!

In the meantime, I tried some other variants, and interestingly enough, VC++ incorrectly compiles it only if the ? : operator is used!

And the best is: The program does *not* (!) crash, and the boolean flag is always true (!).

Strange. Really.
 
very strange! It sounds more like the ? operator is the root of the problem.

Matt
 
I use VisualStudio 2003. In my environment no one of code samples are compilled. For both in gives the same error
error C2597: illegal reference to non-static member 'MyClass::itsFlag'

Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top