90% of the time when I use pointers it's to work with polymorphism. If you are coming from C# then you must understand how polymorphism works.
For a basic example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class Vehicle { };
class Car : public Vehicle { };
class Truck : public Vehicle { };
// Car and Truck are both derived from Vehicle
// now say we want to create either a Car or Truck depending on what the user inputs...
Car user; // this doesn't work if the user wants a truck
Truck user; // this doesn't work if the user wants a car
Vehicle user; // this doesn't work because it's not a Car or Truck
// so how can we do it? We use a pointer:
Vehicle* user;
if(user_wants_a_car) user = new Car;
if(user_wants_a_truck) user = new Truck;
|
Now in C# you could accomplish the same thing without pointers, but only because C# objects mimic being pointers behind the scenes. For example in C# you do the same thing without pointers:
1 2 3 4
|
// C#, but forgive me, my C# is rusty and I might be wrong
Vehicle user;
if(user_car) user = new Car;
if(user_truck) user = new Truck;
|
This of course doesn't work in C++ because of an important language detail:
- In C#, objects are actually references to other objects, and not objects themselves
- In C++, objects are objects. If you want a pointer or reference, you have to explicitly say so.
Take another example:
1 2 3
|
// C#
Truck t = new Truck;
Vehicle v = t;
|
Here, in C#, 'v' and 't' would both refer to the same object. Changes made to 'v' would also affect 't'.
In C++ this isn't the case. If you do something similar in C++ you have a problem:
1 2 3
|
// C++ (probably bad code)
Truck t;
Vehicle v = t;
|
Here, in C++, 'v' is a copy of 't', and is a separate object.
However only the Vehicle portion of the object has been copied. Any information specific to Truck has been lost in the copy.
To accomplish the same thing as the C# example in C++, you have to specifically tell C++ that you want a pointer/reference:
1 2 3 4 5 6 7
|
// C++ (using references)
Truck t;
Vehicle& v = t;
// C++ (using pointers)
Truck t;
Vehicle* v = &t;
|
The main difference between the two is that references can't be reseated (v will always refer to the t object), whereas with pointers you can reseat them (you can change v to refer to a different object if you like)