tags:

views:

157

answers:

4

Hi Friends,

What will be solution in the fallowing code

Class A{}
void func(){}

printf("%d,%d",sizeof(A),sizeof(func));

Thanks in advance

Prashant Dubey

A: 

Why don't you just test it out? The function will be probably be promoted to a pointer.

ninjalj
You can't "test it out". The code is ill-formed - it won't compile. Which kinda makes the original question meaningless, unless "won't compile" is the answer the OP is looking for.
AndreyT
+3  A: 

You are taking the size of a function which cannot be done. You need to preceede the name with a & to take the size of a pointer to that function. You also need to cast the sizeof value to be of type int, which is what printf expects for the d specifier

printf("%d,%d", (int)sizeof(A), (int)sizeof(&func));

As for the concrete values ---- It's not known what they are beyond that are greater or equal to 1. It depends on the compiler.

Johannes Schaub - litb
+4  A: 

Size of an empty class is non zero(most probably 1), so as to have two objects of the class at different addresses.

http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty explains it better

 class A{};
 void func(){}

 std::cout<<sizeof(A)<<std::endl<<sizeof(&func));// prints 1 and 4 on my 32 bit system
Satish
A: 

By sizeof(func), you probably mean sizeof(&func), which is the size of a function pointer in bytes.

As far as what the size of an A object is, the standard only says:

Complete objects and member subobjects of class type shall have nonzero size.

which is qualified by footnote 94:

Base class subobjects are not so constrained.

The reason for the footnote is to allow for a compiler optimization known as empty member optimization, which is commonly used in template libraries to access routines of a class type (e.g. allocator routines of an allocator class type) without needing a member object of that class type.

Daniel Trebbien
Pointers to differing types aren't guaranteed to be the same size (although they usually are in practice).
Oli Charlesworth
@Oli Charlesworth: Wow, I was unaware that pointer sizes can be different. Indeed, looking through the C and C++ standards, I can't find anything that forces the sizes of two pointer types to be equal. There was, however, this line from [5.2.10] Reinterpret cast: "A pointer to a function can be explicitly converted to a pointer to a function of a different type". I think that this means the sizes of two *function* pointer types are the same at least.
Daniel Trebbien
@Daniel: One example of where the size of a data pointer and a function pointer *might* differ is on a platform with a Harvard architecture (i.e. separate instruction and data memories).
Oli Charlesworth
@Oli Charlesworth: Interesting info. Thank you.
Daniel Trebbien