What is the difference between member and nonnember functions in c++.
相关问题
- how to define constructor for Python's new Nam
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Keeping track of variable instances
- Why does const allow implicit conversion of refere
相关文章
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
There are several differences between a member function (which I will now call method) and a free function (which I will now call function).
First, let's just state that they are not so different. Object code can generally be compiled down to C (or assembly) which are procedural languages with no notion of methods. Both methods and functions are then called like subroutines.
Now that this is out of the way, let's look at the differences. They can be classified in two categories: conceptual and syntactic.
Syntactically
The syntax is the obvious part of any language, so it's the easiest to get out of the way.
First note: there are two different kinds of methods in C++ (and a number of other languages), the
static
methods and regular methods.Both kinds of methods have full access to the class internals (
protected
andprivate
sections) as well (of course) as access to the classpublic
interface.static
methods are equivalent tofriend
functions (apart from some scoping differences).Within a regular method, a special keyword (
this
in C++) allows access to the current object on which the method has been invoked (via the.
,->
,.*
or->*
operators).A regular method may be
const
and/orvolatile
qualified, enabling it for (respectively)const
and/orvolatile
qualified objects. For example, a non-const
method cannot be called on aconst
object. This can be seen as qualifyingthis
within the method, ievoid Foo::bar() const
has athis
of typeFoo const*
.A regular method may be marked as
virtual
. Virtuality enables runtime polymorphism by enabling overriding. I won't extend on this mechanism here, let's just note that functions cannot be virtual.One often ignored point, is that methods (both
static
and regular) are scoped within the class. This is important for name lookup (of other methods or attributes/variables) as it means that the elements of the class have priority during lookup from a method on the elements declared outside of the class.Since the qualification using
this->
before attribute or methods is not mandatory, this comes handy in regular methods, though it may introduce subtle bugs. In static methods, it avoids qualifying by the class name the static attributes and methods one whishes to access.Now that the main syntactic differences have been asserted, let's check the conceptual differences.
Conceptually
OOP is generally about tying together state and behavior (of this state). This is done by creating classes which group attributes (state) and behavior (methods) and (in theory) stating that only the methods can act on the state. Therefore, in OOP, the methods are responsible for implementing the behavior of the class.
The methods participate to the encapsulation of state (freeing clients from the implementation detail) and to the preservation of the class invariants (statements about the class state that hold true from its birth to its death, whatever you do with it).
C++
In C++, as we have seen previously, this is done by using different access levels (
public
,protected
andprivate
) and granting access to the non-public
levels to a restricted portion of the code. Generally attributes will be private and thus only accessible to the class methods (and maybe some friends, for syntax quirks).Note: I urge you not to use
protected
attributes, it's hard to track down their modifications and since the set of derived classes is unbounded... their implementation cannot be changed easily afterward.However, beware that C++ discourages from bloating the interface with lots of methods.
The trouble is that because methods are responsible of maintaining invariants, the more there are and the more the responsability is spread, making it more difficult to track down bugs and ensure correctness. Also, since methods depends on the class internals, it makes change more costly.
Instead, in C++, it is generally advised to write a minimal set of methods and delegating the rest of the behavior to non-
friend
functions (as long as it doesn't increase the cost too much).std::string
in Monolith Unstrung.This answer is becoming rather long-winded, yet I suspect that I have overlooked differences that other would find critical... oh well.
A non-
static
member function is invoked on objects of the class it belongs to. It has implicitly access to thethis
pointer representing the current object. Through this pointer, it may access other members easily and with full access privileges (i.e. accessprivate
members).A non-member function has no implicit
this
. In the sample below,bar
is a member function whilefreebar
is not. Both do more or less the same, but note howbar
gets an implicit object pointer viathis
(also onlybar
has privileged access tofoo
's members,freebar
only has access to public members).Semantically a member function is more than just a function with an implicit this parameter. It is meant to define the behaviour of an object (i.e. a car object would have
drive()
,stop()
as member functions).Note that there are also
static
member functions which have full privileges but don't get an implicitthis
nor are they invoked through an instance of the class (but rather through the full name of the class).A (non-static) member function has an implicit
this
argument, a non-member doesn't.Syntactically, you pass that implicit argument on the left of the
.
or->
operatorlike.so()
orlike->so()
, instead of as a function argumentso( like )
.Likewise, when declaring a member function, you need to do so in the class of which it is a member:
Non-member functions are instead declared outside any class (C++ calls this "at namespace scope").
(Non-static) member functions can also be virtual, but non-member functions (and static member functions) cannot.
Member functions get called on instances and have a
this
pointer available; non-members don't.A member function is invoked on an object and has access to the fields of the class.
Member functions can be polymorphic (via the
virtual
keyword) which is essential for OOP.In the following code,
f()
is a member function of classSample
, andg()
is a non-member function:Its very simple. Since
f()
is a member of the classSample
, so its called member function (of classSample
). And sinceg()
is not member of any class, so its called non-member function.