user3316811
user3316811

Reputation:

Class instance calling a member function: C++ Vs Python syntax

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 :

Upvotes: 1

Views: 108

Answers (1)

Nikos Athanasiou
Nikos Athanasiou

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"); 

Source

Upvotes: 1

Related Questions