Hi oldcrow,
Pointers or references are more efficient if the object is of any reasonable size, especially if passing the object to a function, because just the pointer or reference is passed, not the entire object.
Pointers are handy for things like a swap function, needs to change 2 things. Passing the objects (or a variable such as a plain old int) themselves, is no good because the function uses a local copy of the objects, so the result is the original objects don't get changed. If you pass pointers instead, then it works as expected.
One very handy thing in C++ is the fact that a pointer to a derived class is a valid pointer to a base class. This is very convenient because you can write a virtual base class function which takes a pointer to the base class. When you call the function, you can have a pointer to the derived class as an argument. This means that you can have 1 virtual base class function, instead of an overloaded one for each derived class. Of course you would redefine the function for derived classes that need it - the compiler calls the correct one because it knows what type the pointer was in the function call.
I used this to provide a units conversion facility for my larger surveying program.
I had this inheritance tree:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class CUnits {
public:
virtual CUnit * ToMetric(CUnit * )=0;
virtual CUnit * FromMetric(CUnit * )=0;
};
class CDistance: public CUnits {};
class CArea: public CUnits {};
class CAngle: public CUnits {};
class CMetres: public CDistance {};
class CFeet: public CDistance {};
class CYards: public CDistance {};
class CLinks: public CDistance {};
class CChains: public CDistance {};
|
I had a similar arrangement for all the different types of units.
Each class had it's own definition of the base class virtual functions, to carry out a conversion. I used a strategy of always doing 2 conversions: converting to 1 base unit - metres say, then convert from that to the target unit. That way, if I had n units, I would have 2(n-1) conversion functions instead of (n*n)-n functions.
So the advantage in all this is that I have 2 virtual base class functions which are inherited to all the derived classes (40 of them say), as opposed to 80. There are still 80 functions, but there are 2 in each class as opposed to 80 in each class (78 unused).
Now having said all of that, I might start a new thread to see if there is an easier way to this with templates.
Hop all goes well.