tags:

views:

220

answers:

3

Why having function in my class doesn't change size of this class? This info must be stored somewhere, but where?

A: 

Me think (and I tend to be wrong most of the time) that if you only declare a non-virtual function in a class but no implementation the linker will probably remove it all together.

class Toto
{
  int foo();
};

M.

Max
Even if you had an implementation, the size would not change. The member function (if its non-virtual) is not stored in a class instance. There is only one copy (ignoring static issues) in a program.
Yann Ramin
+8  A: 

You can think of a member function as being just like any other function, except that it has an extra, hidden parameter that takes a pointer to the instance on which the member function was called.

For example, this:

class C
{
    void f(int i) { }
};

might be implemented (at least conceptually) as:

void C_f(C* this, int i) { }

If it was a const member function, then the hidden parameter would have the type const C* instead. Note that the situation isn't nearly this simple for virtual member functions.

James McNellis
@Knowing: This information is statically linked into wherever a call to that method is used.
Yann Ramin
@Knowing: There's no need for name calling here. That's both rude and unprofessional.
James McNellis
@Knowing: The addresses are hardcoded by the compiler into the calling functions, there is no need to make it part of the object at runtime. In contrast virtual functions are only resolved at runtime and add a pointer to the virtual function table as overhead to each object.
josefx
+2  A: 

The sizeof(TheClass) is affected only by the data members within the class, plus the vtable if there is any, plus padding bytes if there is any. So adding a nonvirtual function to your class does not affect its size. And if the class already contains a virtual function, adding a second one would not change sizeof(TheClass) either.

Péter Török
@Knowing, within the code segment of the program, I guess.
Péter Török
@Knowing: The machine language instructions are stored in your executable binary file, just like they are for any other function in your program. And if you think you're being funny with your comment, you aren't.
Daniel Pryden
@Daniel thanks for your answer, and with with comment according to you I'm trying to be funny?
There is nothing we can do