Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why class size depend only on data members and not on member functions?

Tags:

c++

class

size

I want to know the detail description on the size of a class. I want to know if there is only data members & member function without any virtual keyword then why the class size depends only on data members. For an eg:

class A {
    int a;
public:
    int display() { 
    cout << "A=" << a << endl;
   }
};

When I check the sizeof(A) i found that it is 4 byte. Why it is so? Why member function has no effect on the size of class A?

Thanks

like image 918
Abhineet Avatar asked Feb 26 '12 07:02

Abhineet


People also ask

Is class member and member function same?

Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class. You can declare a member function as static ; this is called a static member function.

What is the difference between a member function of a class and a non-member function in Java?

A non-member function always appears outside of a class. The member function can appear outside of the class body (for instance, in the implementation file). But, when you do this, the member function must be qualified by the name of its class. This is to identify that that function is a member of a particular class.

What is the difference between normal function and member function of a class?

An ordinary function is nothing but a function with a return type and zero or more arguments. It can be called directly in the main or other functions. A member function is declared or defined within a class or structure. It is generally called with reference to the instance of the class or structure.

Why do we define member function outside the class?

Member functions and static members can be defined outside their class declaration if they have already been declared, but not defined, in the class member list. Nonstatic data members are defined when an object of their class is created. The declaration of a static data member is not a definition.


1 Answers

Because the class's functions are not saved inside the object itself. Think of it in terms of C programming, every function of class A takes one secret parameter, the this pointer, so in actuality they are just functions with one extra parameter.

For example imagine it like this:

int display(A* thisptr)
{
   //do something
   printf("%d",thisptr->a); 
   return;
}

So the display function is saved as just a simple function with one extra parameter. The name though is mangled depending on the compiler.

I believe that different rules apply for virtual functions which would involve function pointers but since I am not sure maybe someone else can enlighten us on this matter.

like image 133
Lefteris Avatar answered Oct 27 '22 22:10

Lefteris