Saturday, October 24, 2009

C++ Examples: Returning a Pointer

C++ Examples: Returning a Pointer


Instead of a regular value or even a reference, a function can return a pointer. You can start to specify this by typing the * operator on the left side of the function's name. Here is an example:

double * GetSalary()

{

}

Then, use the body of the function to define it. Before the closing curly bracket of the function, remember to return a pointer to the return value. Here is an example:

double * GetSalary()

{

double salary = 26.48;

double *HourlySalary = &salary;



return HourlySalary;

}

Because a pointer by defining is a reference to the address where a variable resides, when a function is defined as returning a pointer, you can also return a reference to the appropriate type. Here is an example:

double * GetSalary()

{

double salary = 26.48;



return &salary;

}

After defining the function, you can call it. Remember that the asterisk is used to get the value of a pointer. This means that, when calling the function, if you want to access its value, make sure you include the asterisk on the left side of the name of the function. Here is an example:

//---------------------------------------------------------------------------

#include

using namespace std;



double & GetWeeklyHours()

{

double h = 46.50;

double &hours = h;

return hours;

}

//---------------------------------------------------------------------------

double * GetSalary()

{

double salary = 26.48;

double *HourlySalary = &salary;



return HourlySalary;

}

//---------------------------------------------------------------------------

int main()

{

double hours = GetWeeklyHours();

double salary = *GetSalary();



cout << "Weekly Hours: " << hours << endl;

cout << "Hourly Salary: " << salary << endl;

double WeeklySalary = hours * salary;

cout << "Weekly Salary: " << WeeklySalary << endl;



return 0;

}

//---------------------------------------------------------------------------


This would produce:

Weekly Hours:  46.5

Hourly Salary: 26.48

Weekly Salary: 1231.32

No comments:

Post a Comment

Popular Posts