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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With