C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

this Pointer in C++

In this tutorial, we will learn about the this pointer in C++. The this pointer is an implicit pointer that points to the current object for which a non-static member function is called. It is useful when you need to refer to the calling object or disambiguate between local and member variables.

  • Basic usage of this pointer:

Here's an example demonstrating the use of the this pointer:

class MyClass {
public:
    int x;

    void setX(int x) {
        this->x = x; // 'this' pointer is used to differentiate between local and member variables
    }

    int getX() {
        return this->x; // 'this' pointer is used to refer to the calling object
    }
};

int main() {
    MyClass obj;
    obj.setX(42);
    std::cout << "Value of x: " << obj.getX() << std::endl; // Output: Value of x: 42
    return 0;
}

In this example, the this pointer is used to differentiate between the local variable x and the member variable x in the setX() function. It is also used in the getX() function to refer to the calling object.

  • Returning *this to enable chained function calls:

You can return *this (a reference to the calling object) from a member function to enable chained function calls:

class MyClass {
public:
    int x;

    MyClass& setX(int x) {
        this->x = x;
        return *this;
    }

    MyClass& incrementX() {
        ++(this->x);
        return *this;
    }

    int getX() {
        return this->x;
    }
};

int main() {
    MyClass obj;
    obj.setX(42).incrementX().incrementX(); // Chained function calls
    std::cout << "Value of x: " << obj.getX() << std::endl; // Output: Value of x: 44
    return 0;
}

In this example, the setX() and incrementX() functions return a reference to the calling object by returning *this. This enables chained function calls, like obj.setX(42).incrementX().incrementX().

  • Using the this pointer to check for self-assignment:

The this pointer can be used to check for self-assignment when overloading the assignment operator =:

class MyClass {
public:
    int x;

    MyClass(int x) : x(x) {}

    MyClass& operator=(const MyClass& other) {
        if (this == &other) {
            return *this; // Check for self-assignment
        }

        this->x = other.x;
        return *this;
    }
};

int main() {
    MyClass obj1(42);
    MyClass obj2(50);

    obj1 = obj2; // Overloaded assignment operator
    obj1 = obj1; // Self-assignment, no changes made

    return 0;
}

In this example, we use the this pointer in the overloaded assignment operator to check for self-assignment. If the address of the calling object (this) is equal to the address of the object being assigned (&other), we return *this without making any changes.

That's it for our C++ this pointer tutorial. Understanding the this pointer and its usage is crucial for writing clean and efficient code, especially when working with classes and objects. It can be useful for disambiguating between local and member variables, enabling chained function calls,

  1. How to use the 'this' pointer in C++:

    #include <iostream>
    
    class MyClass {
    public:
        void printAddress() {
            // Using 'this' pointer to get the address of the current object
            std::cout << "Address of the object: " << this << std::endl;
        }
    };
    
    int main() {
        MyClass obj;
        obj.printAddress();
    
        return 0;
    }
    
  2. Accessing class members using 'this' pointer in C++:

    #include <iostream>
    
    class MyClass {
    private:
        int data;
    
    public:
        void setData(int data) {
            // Using 'this' pointer to access class member
            this->data = data;
        }
    
        void printData() {
            std::cout << "Data: " << this->data << std::endl;
        }
    };
    
    int main() {
        MyClass obj;
        obj.setData(42);
        obj.printData();
    
        return 0;
    }
    
  3. Pointer to member functions and the 'this' pointer in C++:

    #include <iostream>
    
    class MyClass {
    public:
        void memberFunction() {
            std::cout << "Inside member function" << std::endl;
        }
    };
    
    int main() {
        MyClass obj;
        void (MyClass::*funcPtr)() = &MyClass::memberFunction;
    
        // Calling member function using 'this' pointer
        (obj.*funcPtr)();
    
        return 0;
    }
    
  4. 'this' pointer and function overloading in C++:

    #include <iostream>
    
    class MyClass {
    private:
        int data;
    
    public:
        void setData(int data) {
            this->data = data;
        }
    
        void setData(double data) {
            this->data = static_cast<int>(data);
        }
    
        void printData() {
            std::cout << "Data: " << this->data << std::endl;
        }
    };
    
    int main() {
        MyClass obj;
        obj.setData(42);
        obj.printData();
    
        obj.setData(3.14);
        obj.printData();
    
        return 0;
    }
    
  5. 'this' pointer and operator overloading in C++:

    #include <iostream>
    
    class Complex {
    private:
        double real;
        double imag;
    
    public:
        Complex(double real, double imag) : real(real), imag(imag) {}
    
        Complex operator+(const Complex& other) {
            Complex result(real + other.real, imag + other.imag);
            return result;
        }
    
        void display() {
            std::cout << "Real: " << real << ", Imaginary: " << imag << std::endl;
        }
    
        void addAndDisplay(const Complex& other) {
            Complex result = (*this) + other; // Using 'this' pointer
            result.display();
        }
    };
    
    int main() {
        Complex c1(1.0, 2.0);
        Complex c2(3.0, 4.0);
    
        c1.addAndDisplay(c2);
    
        return 0;
    }
    
  6. Passing 'this' pointer as a parameter in C++:

    #include <iostream>
    
    class MyClass {
    public:
        void printAddress(MyClass* ptr) {
            std::cout << "Address of the object: " << ptr << std::endl;
        }
    };
    
    int main() {
        MyClass obj;
        obj.printAddress(&obj);
    
        return 0;
    }
    
  7. Static member functions and the 'this' pointer in C++:

    #include <iostream>
    
    class MyClass {
    private:
        static int count;
    
    public:
        static void incrementCount() {
            // 'this' pointer is not available in static member functions
            count++;
        }
    
        static int getCount() {
            return count;
        }
    };
    
    // Initialization of static member variable
    int MyClass::count = 0;
    
    int main() {
        MyClass::incrementCount();
        std::cout << "Count: " << MyClass::getCount() << std::endl;
    
        return 0;
    }
    
  8. Lambda expressions and the 'this' pointer in C++:

    #include <iostream>
    
    class MyClass {
    private:
        int data;
    
    public:
        void setData(int value) {
            // Using 'this' pointer in a lambda expression
            auto lambda = [this, value]() {
                data = value;
            };
    
            lambda();
        }
    
        void printData() {
            std::cout << "Data: " << data << std::endl;
        }
    };
    
    int main() {
        MyClass obj;
        obj.setData(42);
        obj.printData();
    
        return 0;
    }
    
  9. Function chaining and 'this' pointer in C++:

    #include <iostream>
    
    class Calculator {
    private:
        int result;
    
    public:
        Calculator() : result(0) {}
    
        Calculator& add(int value) {
            result += value;
            return *this; // Returning 'this' pointer for chaining
        }
    
        Calculator& subtract(int value) {
            result -= value;
            return *this; // Returning 'this' pointer for chaining
        }
    
        void displayResult() {
            std::cout << "Result: " << result << std::endl;
        }
    };
    
    int main() {
        Calculator calc;
        calc.add(5).subtract(3).add(10).displayResult();
    
        return 0;
    }