On 5/11/07, Gopi Krishna Komanduri <[EMAIL PROTECTED]> wrote:
> Hi All,
> Consider a following snippet
> class exm
> {
> int *i;
> public:
> exm()
> {
> }
> };
> void main()
> {
> eam obj;
> cout<<sizeof(obj); // o/p will be 4 bytes (ofcourse according to
> compiler. Mine is MSVC)
> };
> similarly..
> I understood that this pointer will be assigned with the address of the
> object which comes as parameter in copy constructor. But to assign , "this"
> pointer has to exist. That means , it must be declared (probably hidden) . So
> the size of the class should carry the size of this hidden pointer also.
> Please correct me. I understood that I am in wrong way. But Didn't understand
> where I missed the track.
For some reason you assume that an object has to know where it resides
somehow, and has to has a pointer to itself, which is not true.
Consider:
[EMAIL PROTECTED]:~$ cat proba.cpp
#include <iostream>
using namespace std;
class A
{
public:
void print ()
{
cout << "My size is: " << sizeof (*this) << endl;
}
};
int main ()
{
A a;
a.print ();
return 0;
}
[EMAIL PROTECTED]:~$ g++ -Wall -o proba proba.cpp
[EMAIL PROTECTED]:~$ ./proba
My size is: 1
In the above example when a.print () is called, in the background it
translates to something like:
print (&a);
Where the 'this' pointer will be supplied from &a, the object we
created in main. Class A doesn't need to have a pointer to itself,
because all member functions will get the this pointer like above
explicitly. Even if print would call another member function, the
pointer will be passed along, it is not needed to be stored in the
object itself.
--
Tamas Marki