Reputation: 3380
I found that the output of this answer varies from the version of the gcc compiler used.
#include<iostream>
using namespace std;
class ABC{
int x;
public:
void show(){
cout<<sizeof (this);
cout<<sizeof (*this);
}
};
int main(){
ABC ob;
ob.show();
return 0;
}
This code gives the output of 84 in the version 4.9.1 and the same gives the 44 in the previous version.
Can any one clearly explain me what the concept is behind the "this" pointer?
Upvotes: 0
Views: 822
Reputation:
The this
pointer is defined in N3337 [class.this]:
1
In the body of a non-static (9.3) member function, the keywordthis
is a prvalue expression whose value is the address of the object for which the function is called. The type ofthis
in a member function of a classX
isX*
.
So there's nothing special about sizeof(this)
. As pointed out by deviantfan, more than likely you are observing the effect of compiling a 32-bit program versus a 64-bit program.
GCC with -m32
outputs 44
and 84
without.
Upvotes: 1
Reputation: 876
Class is template which is not assigned any space in heap memory. Once you created a variable ob in main() function, memory is allocated to variable ob in heap memory based on definition of the class. There is also a header space to the memory location that contains metadata of the variable. "this" contains the address of the allocated memory.
Now different versions of compilers deal this memory allocation differently.
Look at the functions in the class definition. Those are same across all instances of variable of type ABC. So a version may allocated a shared space for functions where as another may allocated space for functions for each instance eating more space.
This could be one of the reason behind differences.
Upvotes: 0