*this pointer question

Hello, I am trying to get better understanding programming, so i found someone elses code online, so i could read it through and try and understand it, however there is a part I am struggling with involving an this pointer. (code below - I know most of this code is old, but its mostly just to learn to read code i am using it for). So I know when a *this is used in a a class for instance, it is referring to a variable that was passed in, so it can be assigned in the constructor. That is where i have seen it most. But I have not seen *this used somewhere like below. What is *this in regards to the file and tellg. Is the the get pointer? Or is a what the get pointer is referring to in the file? By the looks of the code, it is getting the size of the file and dividing by the size of what ever the *this is.

line i am struggling with
 
 int count = infile.tellg()/sizeof(*this);



full code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  void account_query::search_rec()
{
    int n;
    ifstream infile;
    infile.open("record.bank", ios::binary);
    if(!infile)
    {
        cout<<"\nError in opening! File Not Found!!"<<endl;
        return;
    }
    infile.seekg(0,ios::end);
    int count = infile.tellg()/sizeof(*this);
    cout<<"\n There are "<<count<<" record in the file";
    cout<<"\n Enter Record Number to Search: ";
    cin>>n;
    infile.seekg((n-1)*sizeof(*this));
    infile.read(reinterpret_cast<char*>(this), sizeof(*this));
    show_data();
}
Last edited on
The this pointer is a pointer to the object that the method was called on.
In this case it would be an account_query object.
sizeof *this yields the size in bytes (chars, actually) of the object.
Dividing the total number of bytes in the file by the size of the objects yields the number of objects stored in the file.
Non-static member function has implicitly generated pointer to object.

1
2
3
4
5
6
7
8
9
struct T {
  void func(int arg);
};

// is similar to
struct U {
};

void lone_func( U* this, int arg );

When you call them:
1
2
3
4
5
6
7
8
9
T aa;
T bb;
aa.func(42); // this == &aa
bb.func(7);  // this == &bb

U cc;
U dd;
lone_func( &cc, 42 ); // this == &cc
lone_func( &dd, 7 );  // this == &dd 


*this dereferences the pointer (this) and is thus the pointed to object.
Topic archived. No new replies allowed.