top of page
Search
  • Writer's pictureSrajan Ratti

This Pointer

This pointer is a pointer that refers to the class object for which the member function is called.This Pointer is not a member of the object itself so doing sizeof won't include the size. This Pointer acts as a member variable but is not and instead resides in a register.



#include <iostream>

class Donut
{
  public:
  void setDonuts(int donuts)
  {
    this->donuts = donuts;

    std::cout << "Mr D'Oh can eat = " << this->donuts << " in One Go ";
  }

  private:
  int donuts;

};

int main()
{
  Donut don;
  don.setDonuts(100);
}
 

In each of the non static member function calls, the address of the object is passed as a hidden variable and since there is no object involved in the static function, we cannot use this pointer in it.


For non cv(constant/volatile functions) the type of the this pointer would be X* (where X is class Name) and for cv functions, it would be cv X*.


  void getDonuts() const
  {
    return this->donuts; // This Not Required Here
  } 

Here this is a const pointer to a const object which obviously won't allow modification to member variables.








10 views0 comments

Recent Posts

See All

Comentarios


bottom of page