简体   繁体   中英

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 :

  • How is the caller known ?
  • There is a 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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM