To understand the topic of pointers to objects, we need to know what is an object , pointer and class. A class is defined in C++ using keyword class followed by the name of class.
The body of class is defined inside the curly brackets and terminated by a semicolon at the end.
What is object?
Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
As discussed above when object is created memory is allocated. So how do we declare an object.
How to declare Objects ?
When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName;
How to access data members and access functions ?
The data members and member functions of class can be accessed using the dot(‘.’) operator with the object.
For example if the name of object is obj and you want to access the member function with the name printName() then you will have to write obj.printName() .
Example:
//To demonstrate accessing of data members
#include <bits/stdc++.h>
using namespace std;
class Example
{
// Access specifier
public:
// Data Members
string Testname;
// Member Functions()
void printname()
{
cout << " Testname is: " << Testname;
}
};
int main() {
// Declare an object of class example
Example obj1;
// accessing data member
obj1. testname = "Arjun";
// accessing member function
obj1.printname();
return 0;
}
Output:
Testname is: Arjun
Output:
Testname is: Arjun
Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them.
As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined.
Example #2
#include <iostream>
using namespace std;
int main () {
int var1;
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
}
Output:
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
What are Pointers?
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is –
type *var-name;
Example #3
string *student;
Here, type is the pointer’s base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to assign a variable as a pointer. Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
How do we use Pointers in C++?
There are few important operations, which we will do with the pointers very frequently.
- We define a pointer variable.
- Assign the address of a variable to a pointer.
- Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations .
Example #4
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *work; // pointer variable
work = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << work << endl;
// access the value at the address available in pointer
cout << "Value of *work variable: ";
cout << *work << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows :-
Output:
Value of var variable: 20
Address stored in work variable: 0xbfc601ac
Value of *work variable: 20
As we seen above example , you can access an object either directly, or by using a pointer to the object. To access an element of an object when using the actual object itself, use the dot operator.
To access a specific element of an object when using a pointer to the object, you must use the arrow operator.
To declare an object pointer, you use the same declaration syntax that you would use for any other pointer type.
When to use ‘This’ Pointer ?
To better understand ‘this’ pointer, it is important to know how objects look at functions and data members of a class.
- Each object gets its own copy of the data member.
- All-access the same function definition as present in the code segment.
Meaning each object gets its own copy of data members and all objects share a single copy of member functions.
This is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++.
- It can be used to pass current object as a parameter to another method.
- It can be used to refer current class instance variable.
- It can be used to declare indexers.
Then now question is that if only one copy of each member function exists and is used by multiple objects, how are the proper data members are accessed and updated?
The compiler supplies an any suggested pointer along with the names of the functions as ‘this’.
The ‘this’ pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
When do we use “this” keyword:
When local variable’s name is same as member’s name.
Example #5
#include<iostream>
using namespace std;
/* local variable is same as a member's name */
class Test
{
private:
int m;
public:
void setM (int m)
{
// The 'this' pointer is used to retrieve the object's m
// hidden by the local variable 'm'
this->m = m;
}
void print() { cout << "m = " << m << endl; }
};
int main()
{
Test obj;
int m = 20;
obj.setM(m);
obj.print();
return 0;
}
Output:
m = 20
Final Notes
In the above example program we can see when an ‘this’ keyword is used for local variable(m) and member name(M) is same.
We learnt how to use pointer and declare pointers and access member functions. Also now we understand when to use this keyword and advantage of it.