1

I was just curious, does the creation of an object in C++ allocate space for a new copy of it's member functions? At the assembly or machine code level, where no classes exist, do all calls for a specific function from different objects of the same class actually refer to the same function pointer or are there multiple function blocks in memory and therefore different pointers for each and every member function of every object derived from the same class?

debanshu das
  • 141
  • 2
  • 9

2 Answers2

2

Usually languages implement functionalities as simply as possible.

Class methods are under the hood just simple functions containing object pointer as an argument, where object in fact is just data structure + functions that can operate on this data structure.

Normally compiler knows which function should operate on the object. However if there is a case of polymorphism where function may be overriden. Then compiler doesn't know what is the type of class, it may be Derived1 or Derived2. Then compiler will add a VTable to this object that will contain function pointers to functions that could have been overridden. Then for overridable methods the program will make a lookup in this table to see which function should be executed.

You can see how it can be implemented by seeing how polymorphism can be implemented in C: How can I simulate OO-style polymorphism in C?

oneat
  • 10,778
  • 16
  • 52
  • 70
0

No, it does not. Functions are class-wide. When you allocate an object in C++ it will contain space for all its attributes plus a VTable with pointers to all its methods/functions, be it from its own class or inherited from parent classes.

When you call a method on that object, you essentially perform a look-up on that VTable and the appropriate method is called.

Michael
  • 325
  • 3
  • 14