🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

(Un?)answerable Class Question

Started by
1 comment, last by Yanroy 24 years, 5 months ago
I have asked many people this, and no one knows the answer... Please look at this code and tell me if it will work... I will explain what for at the end. class CMyClass { public: int MyInt; static void MyFunc() {MyInt++;} } CMyClass Instance; Instance.MyFunc(); Will it work? What I want to know is if I call a static function from an instance of a class, will that static function know which instance I am calling it from, and will it use the correct variables that are in the instance I am calling it from. The reason for this is that I want to only have 1 function per class, but have that function work for all of the instances. If it doesn''t work, would passing the "this" pointer to the static function, and using that to access the variables help? www.trak.to/rdp

Yanroy@usa.com

--------------------

You are not a real programmer until you end all your sentences with semicolons; (c) 2000 ROAD Programming
You are unique. Just like everybody else.
"Mechanical engineers design weapons; civil engineers design targets."
"Sensitivity is adjustable, so you can set it to detect elephants and other small creatures." -- Product Description for a vibration sensor

Yanroy@usa.com

Advertisement
Hi there,

it will not work.
Passing the this pointer as a parameter will work however.

But why not just make it a non-static member function.
You compiler makes only one function for it that gets used for all the instances. So no prob there.

Jaap Suter
____________________________Mmmm, I''ll have to think of one.
No it won''t.

You are using a static function to access non-static data. Static function can only operate on static class data and member functions. Also your static class functions do not have a "this" pointer, see definition of static class member functions as to why.

I''m not going to pretend to understand what you are doing. But here are two possible ways of doing what you need:

If you want to make a reference count as to the number of object you instantiate, just make MyInt static. All instances of your class will increment data member MyInt regardless of which class you refer to when calling MyFunc().

If you want to call one function and have it operate on individual class instance data, forget about using static at all, as the mechanism of class operation provide the requirements to operate on individual class data on a per instance basis.

Don''t know if that''s what you were looking for, but there''s my opinion...

~deadlinegrunt

This topic is closed to new replies.

Advertisement