Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ sizeof() of a class with functions

Tags:

I have a C++ question. I wrote the following class:

class c {     int f(int x, int y){ return x; } }; 

the sizeof() of class c returns "1". I I really don't understand why it returns 1.

Trying to understand better what is going on, I added another function:

class c {      int f(int x, int y){ return x; }      int g(int x, int y){ return x; } }; 

Now the following really got me confused! sizeof(c) is still 1 (!?!?!?!). So I guess that functions doesn't change the size of the class, but why??? and why does the size is 1 ? And is it compiler specific ?

Thanks! :-)

like image 309
TCS Avatar asked Jul 01 '11 19:07

TCS


People also ask

What is the use of sizeof () function in C?

What is the sizeof() function in C? The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in ​the computer's memory.

What is sizeof () in C with example?

It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.

What is the size of class with virtual function?

A virtual function is a pointer with 8 bytes.


2 Answers

The class contains no data members, so it's empty. The standard demands that every class have at least size 1, so that's what you get. (Member functions aren't physically "inside" a class, they're really just free functions with a hidden argument and a namespace and access control.)

like image 126
Kerrek SB Avatar answered Sep 19 '22 22:09

Kerrek SB


It's size is of 1, because it can not be 0, otherwise two objects of this type wouldn't be addressable (couldn't differentiate their addresses)

like image 27
BЈовић Avatar answered Sep 21 '22 22:09

BЈовић