Chapter: Object Oriented Programming and Data Structure : Inheritance and Polymorphism

This Pointer

Every object in C++ has access to its own address through an important pointer called this pointer.

THIS POINTER

 

Every object in C++ has access to its own address through an important pointer called this pointer. The thispointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used torefer to the invoking object. Friend functions do not have a thispointer, because friends are not members of a class. Only member functionshave a this pointer.

 

Let us try the following example to understand the concept of this pointer:

#include <iostream>

 

using namespace std;

classBox

{

public:

// Constructor definition

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

{

 

cout<<"Constructor called." <<endl;

length= l;

 

breadth= b;

height= h;

}

doubleVolume()

 

{

returnlength * breadth * height;

}

intcompare(Box box)

{

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

}

private:

doublelength; // Length of a box

 

doublebreadth; // Breadth of a box

doubleheight; // Height of a box

};

 

intmain(void)

{

 

Box Box1(3.3, 1.2, 1.5); // Declare box1

Box Box2(8.5, 6.0, 2.0); // Declare box2

if(Box1.compare(Box2))

 

{

cout<<"Box2 is smaller than Box1" <<endl;

}

else

{

cout<<"Box2 is equal to or larger than Box1" <<endl;

}

return0;

}

 

When the above code is compiled and executed, it produces the following result: Constructor called.

Constructor called.

Box2 is equal to or larger than Box1

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Object Oriented Programming and Data Structure : Inheritance and Polymorphism : This Pointer |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

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