2. Pointers
Pointers are variables that store the
address of another variable. Instead of
holding actual data, they point to the
location where the data resides.
To declare a pointer, you use the * operator.
For instance, to declare an integer pointer:
int *p;
This tells the compiler that p is a pointer to
an integer. However, this pointer doesn’t yet
point to any address.
3. Initializing Pointers
After declaration, it's crucial to initialize a
pointer before using it. An uninitialized
pointer can lead to undefined behavior.
You can initialize it with the address of a
variable:
int x = 10;
int *p = &x;
Here, p now contains the address of x.
The & operator fetches the address of
the variable. It’s called reference
operator.
4. Dereferencing Pointers
The process of retrieving the value
from the address a pointer is pointing
to is called dereferencing. To
dereference a pointer, use
the * operator again:
int y = *p; // y will be 10, as *p gives the
value stored at the address p is pointing
to
5. Pointer Types
Each pointer in C++ has a specific
type: the type of data to which it
points. For example, an int pointer can
only point to an integer, a float pointer
can only point to a floating-point
number, and so forth.
Type Pointer Declaration
int int* p;
float float* f;
char char* c;
6. Common Errors With Pointers
One common mistake is not initializing a
pointer before use. Always ensure a
pointer points to a valid location. Another
pitfall is going beyond the memory
bounds. This can corrupt data or crash
the program.
int arr[5];
int *p = arr; // Pointing to the start of
the array
*(p + 5) = 10; // Error! We’re
accessing memory beyond the array's
bounds
7. Pointer Arithmetic
C++ allows arithmetic operations on
pointers. However, one must be
cautious while doing so to avoid
accessing unintended memory
locations.
int a = 5, b = 10;
int *ptr = &a;
ptr++; // Now ptr points to b
8. Class Pointers
In C++, not only can you have pointers
to fundamental data types, but you
can also have pointers to classes.
These allow for more dynamic and
flexible object handling, especially
when dealing with polymorphism and
dynamic memory allocation.
9. Declaring Class Pointers
When you have a class, declaring a
pointer to it is similar to how you
declare pointers to basic data types.
Given a class named Car, you would
declare a pointer to it as follows:
class Car { // ... class definition ... };
Car *ptrCar;
After this, ptrCar can point to an
instance (object) of the Car class.
10. Initializing And Using Class
Pointers
To make your pointer useful, you should
make it point to an actual object. You can
either point it to an existing object or
allocate memory dynamically.
Car myCar;
ptrCar = &myCar; // Pointing to an existing
object
Car *dynamicCar = new Car(); //
Dynamically allocating memory for a Car
object and pointing to it
11. When accessing members (both data
members and member functions) of
the class through the pointer, use the
arrow (->) operator:
ptrCar->startEngine(); // Calls the
startEngine() method of the object
pointed to by ptrCar
12. Dynamic Memory And Class
Pointers
One of the key utilities of class pointers is in
dynamic memory allocation. When creating
objects at runtime based on program needs,
using new and delete becomes essential.
Car *dynamicArray = new Car[10]; // Allocates
memory for an array of 10 Car objects
delete[] dynamicArray; // Frees up the allocated
memory once done
Always remember to free up memory after
use to prevent memory leaks.
13. Polymorphism And Class
Pointers
One of the strengths of class pointers lies
in polymorphism. By having a base class
pointer point to a derived class object, you can
achieve runtime polymorphism.
class Base {};
class Derived : public Base {};
Base *bPtr = new Derived(); // Base pointer
pointing to derived class object
This feature enables more dynamic behavior,
especially with overridden functions and virtual
functions in C++.
14. Declaring And Initializing
Class Pointers
Working with objects in C++ often
requires understanding how to declare
and initialize pointers to those objects.
Handling class pointers correctly can
enable dynamic memory management
and more flexible object interactions.
15. Declaration Of Class Pointers
A class pointer declaration follows a
similar syntax as pointers to basic data
types. Let's say we have a class
named Robot. A pointer to this class
would be:
class Robot {
// ... class definition ...
};
Robot *ptrRobot; // Declaration of pointer
to Robot class
16. Initializing With Existing
Objects
Often, you might want a pointer to
reference an existing object. This can
be done using the address-of operator
(&):
Robot r2d2;
ptrRobot = &r2d2; // ptrRobot now
points to r2d2
17. Dynamic Memory Allocation
For more dynamic applications, C++ allows
for on-the-fly memory allocation using
the new keyword. This is especially useful
when the number or size of objects needed
is unknown at compile time.
Robot *dynRobot = new Robot(); // Allocates
memory and initializes a new Robot object
Always remember, for every new, there
should be a corresponding delete to free up
the allocated memory:
delete dynRobot; // Frees up the memory
18. Pointers To Class Arrays
You can also declare and initialize pointers
to arrays of class objects. This is useful for
creating collections of objects dynamically:
Robot *robotArray = new Robot[5]; //
Creates an array of 5 Robot objects
// Accessing members of the array
robotArray[2].activate(); // Activates the third
robot in the array
Again, remember to free the memory:
delete[] robotArray; // Deletes the entire
array
19. The Arrow Operator
The arrow operator (->) is your primary tool
for accessing members of a class via a
pointer. This operator is a combination of the
dereference (*) operator and the dot (.)
operator.
Given a class Vehicle:
class Vehicle {
public: void honk() {
// Honking logic
}
};
Vehicle *ptrVehicle = new Vehicle();
ptrVehicle->honk(); // Using the arrow operator
to access the honk function
20. Accessing Data Members
Just as with member functions, data
members of a class are also accessed
using the arrow operator when
working with pointers.
class Vehicle {
public: int speed;
};
Vehicle *ptrVehicle = new Vehicle();
ptrVehicle->speed = 60; // Setting the
speed data member via pointer
21. Dereferencing And The Dot
Operator
Though the arrow operator is more
common and direct, you can also
dereference the pointer and use the dot
operator to access class members:
(*ptrVehicle).speed = 50; // Dereferencing
the pointer and then using the dot operator
This method is less common because it's
more verbose, but understanding it
underscores the concept that the arrow
operator is just a shorthand for this
process.
22. Accessing Array Elements
Through Pointers
If you have a pointer to an array of objects,
you can combine pointer arithmetic with
member access:
Vehicle *fleet = new Vehicle[10];
(fleet + 3)->speed = 70; // Accessing the
speed of the fourth vehicle in the array
It's essential to remember the precedence
of operators here. The arrow operator will
act before the addition, so using
parentheses ensures the correct behavior.