The result is "4 Bytes". Why is that? Where is the space for the foo() function? Thank you for your comments.Code:class A{ public: int x; void foo() const{ cout<<"A Class"<<endl; } }; int main(){ cout<<sizeof(A)<<"Bytes"; return 0; }
The result is "4 Bytes". Why is that? Where is the space for the foo() function? Thank you for your comments.Code:class A{ public: int x; void foo() const{ cout<<"A Class"<<endl; } }; int main(){ cout<<sizeof(A)<<"Bytes"; return 0; }
I suspect it is just checking the size based on all the data types you have in the class. Since int is most likely 32-bit, it comes out at 4 bytes.
The size of a class is the sum of the sizes of its data members. The methods only exist once, they aren't duplicated for each object.
A class method is really a normal function that takes a hidden parameter, the address of the object you invoked it on ('this').
For example, the signature of A::foo is effectively this:
Code:void A::foo(A *this) const { //stuff }
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
> The size of a class is the sum of the sizes of its data members.
I believe that any class, even one with no data members, is required to have a size of at least 1 byte. Try
Code:#include <iostream> class A {}; int main() { std::cout << sizeof(A) << std::endl; }
Yes, that's also true, except for the special case of the empty base optimization, where a specific instance of a class may have size 0. (But there is no way to access this subobject in a way you can pass it to sizeof.)
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law