In C++, we don't need to specify the static keyword in the declaration of the header and in the definition in the class.
It means that this keyword has to be added only in the header.
You probably know that using the static keyword means that the function is unique in program.
So if you add static in the .h and in the .cpp, you will have like two methods with the same name.
And the compiler won't appreciate it.
Let's take two examples, one not working and another yes.
We are going to implement 2 files:
#ifndef MYCLASS_H_ #define MYCLASS_H_ class MyClass { public: MyClass(); virtual ~MyClass(); static void myMethod(); }; #endif /* MYCLASS_H_ */
#include "MyClass.h" MyClass::MyClass() { } MyClass::~MyClass() { } static void MyClass::myMethod() { }
#ifndef MYCLASS_H_ #define MYCLASS_H_ class MyClass { public: MyClass(); virtual ~MyClass(); static void myMethod(); }; #endif /* MYCLASS_H_ */
#include "MyClass.h" MyClass::MyClass() { } MyClass::~MyClass() { } void MyClass::myMethod() { }
A really annoying problem that you've just solved.
Great job.
Comments
Neimad (not verified)
Tuesday, April 2, 2013 - 6:20pm
Permalink
Thanks!
Thanks!
I'm seeing that nobody said that, but may be this post has more visits than you think.
Neeraj (not verified)
Monday, August 4, 2014 - 11:21pm
Permalink
Thanks so much. I agree with
Thanks so much. I agree with Neimad. A very useful and well written post. Keep the good work going!
helioz2000 (not verified)
Wednesday, September 2, 2015 - 3:44am
Permalink
Thanks - short and to the
Thanks - short and to the point with no fluff.
v1per (not verified)
Saturday, June 30, 2018 - 1:00pm
Permalink
thx for clarifying that
thx for clarifying that
Denis (not verified)
Wednesday, December 19, 2018 - 6:24pm
Permalink
You have saved my life!
You have saved my life!
Husnu (not verified)
Friday, December 21, 2018 - 2:14pm
Permalink
Thank you very much.
Thank you very much.
Cordell (not verified)
Sunday, April 10, 2022 - 4:36am
Permalink
Appreciate the help
Appreciate the help
ForHire (not verified)
Friday, September 23, 2022 - 12:46pm
Permalink
Thank you so much stranger.
Thank you so much stranger.
Aditi (not verified)
Monday, December 5, 2022 - 2:00am
Permalink
I am so thankful for this
I am so thankful for this post.
still swamp (not verified)
Tuesday, January 3, 2023 - 12:22pm
Permalink
Thank you. It's simple but it
Thank you. It's simple but it's need to know.
kjr_nl (not verified)
Wednesday, April 26, 2023 - 3:43pm
Permalink
Thank you very much for the
Thank you very much for the clear and concise explanation.
Add new comment