C++ 48: This pointer

 Self referencing pointer /this pointer

  • This is the name given to a pointer variable

    the this pointer contains address for which function or constructor or destructor is currently called

    this points to the current object inside the class only

    by using this pointer class determines data of which object to be used for processing

    the expression in a class are replaced by using this pointer in the compiled code as follows

    it is generally used to access the members of the object inside the class it is used to return the object itself

    note

    remember that the copy constructor overloading assignment operator function and this pointer automatically added in the compiled code of class in C plus plus program is compiled


//The this pointer contains address of the object for which the
//currently the  function is called
#include <iostream>

using namespace std;
class Alpha
{
public:
    Alpha()
    {
        cout << "Inside the constructor:this" << this << endl;
    }
    void display()
    {
        cout << "Inside the function this = " << this << endl;
    }
    ~Alpha()
    {
        cout << "Inside destructor this=" << this << endl;
    }
};
int main()
{
    Alpha a;
    cout << "Address of obj-a = " << &a << endl;

    Alpha b;
    cout << "Address of obj-b = " << &b << endl;

    a.display();
    b.display();

    return 0;
}

Output:

Inside the constructor:this0x61fe0f
Address of obj-a = 0x61fe0f
Inside the constructor:this0x61fe0e
Address of obj-a = 0x61fe0e
Inside the function this = 0x61fe0f
Inside the function this = 0x61fe0e
Inside destructor this=0x61fe0e
Inside destructor this=0x61fe0f



Example 2:

//The this pointer contains address of the object for which the
//currently the  function is called
#include <iostream>
using namespace std;

class Circle
{
private:
    int R;

public:
    Circle(int r)
    {
        cout << "Constructor: this = " << this << endl;
        this->R = r;
    }
    void area()
    {
        cout << "\nArea fun: this = " << this << endl;
        float A = 3.14 * this->R * this->R;
        cout << "Area is: " << A << endl;
    }
    void circumference()
    {
        cout << "\nCircumference fun: this = " << this << endl;
        float C = 2 * 3.14 * this->R;
        cout << "Circumference is: " << C << endl;
    }
};
int main()
{

    Circle a(5);
    cout << "Address of a: " << &a << endl;

    Circle b(8);
    cout << "Address of b: " << &b << endl;

    a.area();
    b.area();

    a.circumference();
    b.circumference();

    return 0;
}

Output:

Constructor: this = 0x61fe1c
Address of a: 0x61fe1c
Constructor: this = 0x61fe18
Address of b: 0x61fe18

Area fun: this = 0x61fe1c
Area is: 78.5

Area fun: this = 0x61fe18
Area is: 200.96

Circumference fun: this = 0x61fe1c
Circumference is: 31.4

Circumference fun: this = 0x61fe18
Circumference is: 50.24





Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected