this pointer in C++

this pointer is pointer that is accessible only inside the member functions of a class and points to the object who has called this member function.

Applications of this pointer :

 

Method Chaining:

After returning the object from a function, a very useful application would be to chain the methods for ease and a cleaner code.

Example :

                        obj->setX(15)->setY(15)->setZ(15);

                


Here, the methods setX, setY, setZ are chained to the object, obj. This is possible because each method return *this pointer. This is equivalent to :

                  obj->setX(15);
                  obj->setY(15);
                  obj->setZ(15);

                 

 

Distinguish Data Members :

Another application of this pointer is distinguishing data members from local variables of member functions if they have same name. For example,

Lets take an example

            #include <iostream>
            #include conio.h>
            using namespace std;

            class sample
            {
                int a,b;
                public:
                    void input(int a,int b)
                    {
                        this->a=a+b;
                        this->b=a-b;
                    }
                    void output()
                    {
                        cout<<"a = "<<a<<endl<<"b = "<<b;
                    }
            };

            int main()
            {
                sample x;
                x.input(5,8);
                x.output();
                getch();
                return 0;
            }

         


Now see above code here we have declared a,b as member of class And at the same time in same class we declare function input which takes same a,b args . now how my code ,compiler will know which a,b i want to use

So thats why we use this pointer to distinguish the local variable of input() data member of class, this pointer is used. When input() is called, the data of object inside it is represented as this->a and this->b while the local variable of function is represented simply as a and b.

Output :
                a = 13
                b = -3
        



Return Object :

One of the important applications of using this pointer is to return the object it points. For example, the statement

                return *this;
        


inside a member function will return the object that calls the function. we will this in examples

Write a C++ program to display the record of student with highest percentage.



        #include<iostream>
        #include<conio.h>
        using namespace std;
        
        class student
        {
            char name[100];
            int age,roll;
            float percent;
            public:
                void getdata()
                {
                    cout<<"Enter data"<<endl;
                    cout<<"Name:";
                    cin>>name;
                    cout<<"Age:";
                    cin>>age;
                    cout<<"Roll:";
                    cin>>roll;
                    cout<<"Percent:";
                    cin>>percent;
                    cout<<endl;
                }
                student & max(student &s1,student &s2)
                {
                    if(percent>s1.percent && percent>s2.percent)
                        return *this;
                    else if(s1.percent>percent && s1.percent>s2.percent)
                        return s1;
                    else if(s2.percent>percent && s2.percent>s1.percent)
                        return s2;
                }
                void display()
                {
                    cout<<"Name:"<<name<<endl;
                    cout<<"Age:"<<age<<endl;
                    cout<<"Roll:"<<roll<<endl;
                    cout<<"Percent:"<<percent;            
                }
        };
        
        int main()
        {
            student s,s1,s2,s3;
            s1.getdata();
            s2.getdata();
            s3.getdata();
            s=s3.max(s1,s2);
            cout<<"Student with highest percentage"<<endl;
            s.display();
            getch();
            return 0;
        }



A class student is created with data members name, roll, age and percent and member functons getdata(), max() and display(). Data for each student is entered by calling getdata() function. Then, max() function is called by object s3 and s2 and s1 are passed as parameter in the function. The value of percent is compared and the object with highest percent is returned. If the object calling the method has the highest percentage then, it is returned by using this pointer as,

return *this; // see above prohram carefully 



Output :
                Enter data
                Name:aaa
                Age:22
                Roll:11
                Percent:89
                
                Enter data
                Name:bbb
                Age:22
                Roll:9
                Percent:87
               
                
                Student with highest percentage
                Name:aaa
                Age:22
                Roll:11
                Percent:89
        

 

 

Lets do some exercises :

 

1. Write a program in C++ to swap two numbers :

 

                    Input 1st number : 25                 
                    Input 2nd number : 39 
                    After swapping the 1st number is : 39 
                    After swapping the 2nd number is : 25
                



2. Write C++ program to check year is leap or nor

 

C++ Arrays

In programming, one of the frequently arising problem is to handle numerous data of same type.

Consider this situation, you are taking a survey of 100 people and you have to store their age. To solve this problem in C++, you can create an integer array having 100 elements.

An array is a collection of data that holds fixed number of values of same type. For example:

int a[100]; 

How to declare an array in C++? :

Simple lets check Syntax :

                        dataType arrayName[arraySize];
                
Example :
                    int a[20]
                    here int is data type
                    a is array name 
                    20 size array size 
                

 

How to access Elements of an Array ?

You can access elements of an array by using indices.

Suppose you declared an array mark as above. The first element is mark[0], second element is mark[1] and so on.

Key Notes : Exam will ask Objective on these

Arrays have 0 as the first index not 1. In this example, mark[0] is the first element.

If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4] is the last element.

Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d, address of a[2] will be 2128d and so on. It’s because the size of float is 4 bytes.

How to initialize an array in C++ programming :

Lets take an example :

                        int mark[5] = {19, 10, 8, 17, 9}; 
                        // This is called array initialize at the time declaration 
                        Also there is another menthos :
                        int mark[] = {19, 10, 8, 17, 9};
                        // Means if we are initializing array at the time declaration
                        no need to write size of array . 
                

Lets take an simple Programming example :

                        int mark[5] = {19, 10, 8, 17, 9}
                        // change 4th element to 9
                        mark[3] = 9;
                        // take input from the user and insert in third element
                        cin >> mark[2];
                        // take input from the user and insert in (i+1)th element
                        cin >> mark[i];
                        // print first element of the array
                        cout << mark[0];
                        // print ith element of the array
                        cout >> mark[i-1];
                

 

C++ program to store and calculate the sum of 5 numbers entered by the user using arrays.

 

                #include <iostream>
                using namespace std;
                int main() 
                {
                    int numbers[5], sum = 0;
                    cout << "Enter 5 numbers: ";
                    
                    //  Storing 5 number entered by user in an array
                    //  Finding the sum of numbers entered
                    for (int i = 0; i < 5; ++i) 
                    {
                        cin >> numbers[i];
                        sum += numbers[i];
                    }
                    
                    cout << "Sum = " << sum << endl;  
                    
                    return 0;
                }
                

 

Passing Array to a Function :

Arrays can be passed to a function as an argument.
We will explore this by taking an example :

Write a C++ Program to display marks of 5 students by passing one-dimensional array to a function.
                    #include < iostream >
                    using namespace std;
                    void display(int marks[5]);
                    int main()
                    {
                        int marks[5] = {88, 76, 90, 61, 69};
                        display(marks);
                        return 0;
                    }
                    void display(int m[5])
                    {
                        cout << "Displaying marks: "<< endl;
                        for (int i = 0; i < 5; ++i)
                        {
                            cout << "Student "<< i + 1 <<": "<< m[i] << endl;
                        }
                    }
                

The argument marks in the above code represents the memory address of first element of array marks[5].

And the formal argument int m[5] in function declaration converts to int* m;. This pointer points to the same address pointed by the array marks.

That’s the reason, although the function is manipulated in the user-defined function with different array name m[5], the original array marks is manipulated.

C++ handles passing an array to a function in this way to save memory and time.

 

Lets do some exercises :

1. Write a C++ program to find second largest element in an given array of integers :
2. Write C++ program to sort array in ascending and descending order
3. Write a C++ program to find the two repeating elements in a given array of integers.