What is Pointer to Object in C++?
In C++, a pointer to an object is like a special kind of variable that holds the memory address of an object. It provides a way to indirectly reach and work with the object, permitting us to use and interact dynamically. Pointers to objects come in handy when dealing with memory allocated dynamically, allowing us to use memory flexibly and create objects dynamically as needed.
How to use pointers?
- First, we have to define a pointer variable.
- After defining a pointer variable, we can assign the address of a variable to a pointer by using a unary operator (&).
- To access the given variable’s value, we can use the pointer variable with the help of the unary operator (*). A unary operator is used before the pointer variable to get the value of that address stored in the pointer variable.
Also see, Literals in C, Fibonacci Series in C++ and, Unary operator overloading in c++.
Syntax of pointer
data_type *variable_name;
Here type is defined as the datatype, and variable_name is the pointer’s name in which you want to store the address of a given variable.
Implementation
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
int data = 20;
// declaration pointer variable
int * ptr;
// assigning the address of given variable to the pointer
ptr = & data;
// gives the address that stored in pointer
cout << "Address in ptr=" << ptr << endl;
// value of the given variable
cout << "Value of data=" << data << endl;
// value of the given variable
cout << "Value at *ptr=" << * ptr << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Address in ptr=0x7ffe96baeaec
Value of data=20
Value at *ptr=20
Types of Pointers in C++
There are five types of pointers in C++ -
- Null Pointer
- Void Pointer
- Array Name as a Pointer
- Wild Pointer
- Dangling Pointer
Null pointer
The null pointer is a pointer that does not point to any memory location. It represents an invalid memory location. When we assign a NULL value to a pointer, then that pointer refers to a null pointer.
Implementation
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// declaration pointer variable
int * ptr;
// assigning NULL Address to the pointer
ptr = NULL;
// gives the address that stored in pointer
cout << "Address in ptr=" << ptr << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Address in ptr=0
Void pointer
The pointer with no associated data type is known as a void pointer. A void pointer can hold addresses of any type and can be typecast to any type.
Implementation
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
int var = 10;
// declaration of void pointer variable
void * ptr;
ptr = &var;
// gives the address that stored in pointer
cout << "Address in ptr=" << ptr << endl;
// typecating the pointer
cout << "Value at ptr=" << * (int * ) ptr << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Address in ptr=0x7ffeca383a9c
Value at ptr=10
In the above code, you can see that we have defined a void pointer. This pointer has no associated data type. So, it can point to any type of data. In the ‘cout’ function, you can see that we have first typecasted the pointer into an integer pointer then dereferenced it.
Array name as a pointer
The array's name contains the address of the first element of the array, so you can not change the address stored in the array name. The array's name acts as a constant pointer. You can assign the address of an array to a pointer without using an ampersand (&).
Implementation
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[4] = {12,15,20,50};
// declaration of void pointer variable
int * ptr;
// assign the address of arr[0] to ptr
ptr = arr;
for (int i = 0; i < 4; i++) {
cout << * ptr << endl;
// increment pointer ptr by 1
ptr++;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
12
15
20
50
With the help of the above example, you can clearly understand how we can print the elements of the array with the help of the pointer.
Wild Pointer
A wild pointer in C++ is a pointer variable that hasn't been initialized to a valid memory address. It points to an unknown or random location in memory, potentially leading to program crashes, unexpected behavior, or security vulnerabilities.
Implementation
#include <iostream>
using namespace std;
int main() {
// Declare a pointer to an integer, but don't initialize it
int* ptr;
// Dereferencing a wild pointer (causes undefined behavior)
cout << *ptr << endl; // This will likely cause a segmentation fault
return 0;
}
Output
Attempting to dereference a wild pointer in C++ will typically result in a segmentation fault, which terminates the program abnormally. The exact output may vary depending on your system and compiler.
Dangling Pointer
A dangling pointer is a pointer that refers to a memory location that has been deallocated using delete or delete[] for arrays. The memory is no longer accessible, and attempting to dereference the pointer leads to undefined behavior, similar to a wild pointer.
Implementation
C++
#include <iostream>
using namespace std;
int main() {
int* ptr = new int(10); // Allocate memory for an integer
// Deallocate the memory pointed to by ptr
delete ptr;
// Dereferencing a dangling pointer after deallocation (undefined behavior)
cout << *ptr << endl; // This may cause a segmentation fault
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
The output of this code is also undefined behavior. Dereferencing the pointer ptr after the memory it pointed to has been deallocated might result in a segmentation fault or crash.
You practice by yourself with the help of online c++ compiler.
Advantages of using Pointers in C++
Some advantages of using Pointers are given below:
- Pointers are the variables that are used to store the address of other variables in C/C++.
- Pointer allows us to allocate and deallocate the memory dynamically.
- Pointers help us in simplifying the complexity of the program.
- With the help of pointers, we can improve the execution speed of a program.
- With the help of pointers, we can modify and return more than one variable from a function.
Disadvantages of using Pointers in C++
There are some disadvantages of using Pointers. They are as follows:
- Normal variables are faster than pointers.
- A segmentation defect may arise from an uninitialized pointer.
- Incorrectly updating pointer bugs can result in memory degradation.
- Handling pointer bugs is difficult, so using pointers effectively and correctly is important.
Frequently asked questions
How do you initialize a pointer to an object in C++?
In C++, initialize a pointer to an object using, nullptr (C++11+) to indicate no memory allocation and & operator with an existing object's address.
Why use pointer to object instead of object C++?
Pointers to objects offer:
- Dynamic memory allocation (using new).
- Passing objects by reference (functions modify original object).
- Polymorphism (treating derived class objects as base class).
What is a pointer to a derived class object in C++?
A pointer to a derived class object can hold the address of a derived class object (base class pointer can also point to it).
What is pointer to object member function in C++?
A pointer to an object member function points to a specific member function of an object (used with the ->* operator).
How do I create a pointer to an object in C++?
In C++, we can create a pointer to an object by declaring a variable with the object's type followed by an asterisk (*) and the object's name. The syntax can be the class name along with the object pointer name.
How do you dereference pointers to class objects C++?
When a pointer is dereferenced, it becomes an alias for the object it points to. If 'a' is a pointer of type ABC, then *a represents the object of type ABC that 'a' points to. You can perform all operations applicable to an object of type ABC on *a.
How do you access a pointer to an object?
We can access data members and member functions operating the pointer name with an arrow -> symbol. For instance, if you keep a pointer called "x" to an object with a member function "happyCoding()," then you can access it using "x->happyCoding." Likewise, you can access the object's member variables by operating the arrow operator, such as "x->MemberVaribles."
Conclusion
Set in C++ are a powerful and efficient container for managing collections of unique elements. They provide automatic sorting, prevent duplicates, and allow fast insertions, deletions, and lookups with logarithmic time complexity. Their use is ideal for scenarios where uniqueness and order matter, making them a valuable tool in optimizing code and improving performance.
Learn more: Data Structure