Home | | Computer Science 11th std | C++: thisPointer

Example Programs in C++ - C++: thisPointer | 11th Computer Science : Chapter 16 : Inheritance

Chapter: 11th Computer Science : Chapter 16 : Inheritance

C++: thisPointer

'this' pointer is a constant pointer that holds the memory address of the current object.

thisPointer

 

'this' pointer is a constant pointer that holds the memory address of the current object. .It identifies the currently calling object.It is useful when the argument variable name in the member function and the data member name are same. To identify the datamember it will be given as this->data member name

 

Illutration 16.8.1 illustrates the use of this pointer

#include<iostream>

using namespace std;

class T

{

public:

int x;

void foo()

{

x = 6;  // same as this->x = 6;

this->x = 5; // explicit use of this->

cout<<endl<<x<<" "<<this->x;

}

void foo(int x) // parameter x shadows the member with the same name

{

this->x = x; // unqualified x refers to the parameter.'this->' required for disambiguation

cout<<endl<<x<<" "<<this->x;

}};

int main()

{

      t1,t2;

      t1.foo();

      t2.foo();

}

Ouput

5

5

--------------------------------

Process exited after 0.1 seconds with return value 0 Press any key to continue . . .

 

Another Example Program 16.8.1A using this pointer

#include <iostream>

using namespace std;

class Container {

public:

// Constructor definition

Container(double l = 2.0, double b = 2.0, double h = 2.0)

{

cout<<"Constructor called." << endl; length = l;

breadth = b;

height = h;

}

double Volume() {

return length * breadth * height;

}

int compare(Container container)

{

return this->Volume() >Container.Volume();

}

private:

      double length; // Length of a Container

      double breadth;        // Breadth of a Container

      double height; // Height of a Container

};

int main(void) {

Container Container1(3.3, 1.2, 1.5); // Declare Container1

Container Container2(8.5, 6.0, 2.0); // Declare Container2

      if(Container1.compare(Container2))

      {

      cout << "Container2 is smaller than Container1" <<endl;

      } else {

      cout << "Container2 is equal to or larger than Container1" <<endl;

      }

return 0;

}

Output

Constructor called.

Constructor called.

Container2 is equal to or larger than Container1

--------------------------------

Process exited after 0.09358 seconds with return value 0

Press any key to continue . . .

 

Tags : Example Programs in C++ , 11th Computer Science : Chapter 16 : Inheritance
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 16 : Inheritance : C++: thisPointer | Example Programs in C++


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.