class SimpleCat
{
public:
SimpleCat();
SimpleCat(SimpleCat&);
~SimpleCat();
};
SimpleCat::SimpleCat()
{
cout << "Simple Cat Constructor.. \n";
}
SimpleCat::SimpleCat(SimpleCat&)
{
cout << "Simple Cat Copy Constructor ..\n";
}
SimpleCat::~SimpleCat()
{
cout << "Simple Cat Destructor! ... \n";
}
SimpleCat *FunctionTwo(SimpleCat *theCat);
void main()
{
cout << "Making a cat ...\n";
SimpleCat Frisky;
cout << "Calling FunctionTwo ..\n";
FunctionTwo(&Frisky);
system("pause");
}
SimpleCat *FunctionTwo (SimpleCat *theCat)
{
cout << "FunctionTwo, Returning... \n";
return theCat;
}
Ok, so what i don’t understand is, why do you need the * for FunctionTwo? If you really want to do me a favor, can someone please break down the code for me (the pointer part, because i seriously don’t understand when and why to use the * and &.
FunctionTwo returns a pointer to a SimpleCat object. As you can see there, it also accepts a pointer to a SimpleCat object as a parameter. It’s just accepting the pointer and then returning it in this case.
To call that function, you need to pass a pointer to it. If you want to pass Frisky to the function, you need to pass the address of the object Frisky. This is what is being done when &Frisky is written. A pointer is created with the address of the Frisky object.
However, when a similar statement is written in the parameter list of a function, i.e. SomeFunction(SimpleCat& Frisky) what it is telling you is that objects are passed to the function by reference. This basically allows you to use one of the advantages of pointers without worrying about pointer syntax. You would call the function normally by saying SomeFunction(Frisky), and within the function you would use Frisky with the same syntax as you would within the main function, but you should remember that the object is not copied. Both within main and within SomeFunction, you are performing operations on the exact same object. It is not copied. Only the information required to access Frisky is given to the function.