C++: Difference Between Non-Member Function and Static Member Function? [duplicate]
Asked Answered
A

3

7

Simple question, here: what is the difference between a static member function, i.e. a function that can be called without requiring an object to access it (simply using the class identifier), and a non-member function? Here, I am asking both conceptually and functionally.

Are non-member functions conceptually static?

Antennule answered 22/4, 2014 at 21:28 Comment(3)
Take a look at #7657551Improper
@40two that is a different question. Thank you, though.Antennule
The question is not very well organized the answers though are. In my humble opinion, the answers give you some insight considering your question (e.g., "Non-static functions accept additional parameter, this, which is the pointer to the class instance with the instance-specific variables. Static functions don't have this parameter (thus you can't use this in a static function and can only access static data members.") to name one.Improper
M
8

static member functions can access private and protected sections of a class. Non-member functions cannot do that as default. They can do that only if a class grants them friendship.

Another point to consider is that name of the static member functions are in the scope of the class. Multiple classes can have static member functions with the same name without worrying about names conflicting.

Marozas answered 22/4, 2014 at 21:32 Comment(1)
Thank you! Your answer is infinitely more clarifying than my textbook (Deitel) - and beyond that, more so than my teacher (and research into the question), particularly with regard to granting friendship and member visibility.Antennule
R
1

I would like to append the answer of @R Sahu that overloaded operators may not be static functions of a class.:)

Also static functions themselves can be protected and private. So they can be inaccesible outside the class where they are declared or its derived classes.

Renny answered 22/4, 2014 at 21:47 Comment(0)
P
0

The other advantage of a static member function is that it is the only way if you want to call it in a thread in Windows API. CreateThread requires a function either to be in the global space, or, if it is a member function it has to be static. And there is no way around it, at least to my knowledge.

Praemunire answered 22/4, 2014 at 22:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.