Reputation:
In a simple Python class
class Spam:
def __init__(self, num):
self.num = num
def printMsg(self, msg):
print (msg)
When I write the lines
gotAny = Spam(2)
gotAny.printMsg("We are the knights who say ni")
in each member function an implicit self
argument is passed as the instance that actually called the function, so the way the caller is known by the method is clear enough.
In C++ now, we never put that extra self
argument in method definitions, which troubles me in two ways :
this
pointer but it only makes things more mysterious. The this
pointer is neither a class member nor passed as an argument, so how does this
exist inside member function definitions to begin with ? Upvotes: 1
Views: 108
Reputation: 31549
Indeed an object's this
pointer is not part of the object itself. So in sizeof(Spam)
, the size of this
is not added to the size of the class.
What actually happens is very similar to Python's way of dealing with it (or IMHO better as it hides away this implementation details). When a nonstatic member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function.
So in your example
gotAny.printMsg("We are the knights who say ni");
can be read this way:
// corrected version by juanchopanza
Spam::printMsg(&gotAny, "We are the knights who say ni");
Upvotes: 1