C++

How to accept objects as function arguments in C++ Programming3 min read

Like variables, objects can also be passed using pass-by-value, pass-by-reference, and pass-by-address. In pass-by-value we pass the copy of an object to a function. In pass-by-reference we pass a reference to the existing object. In pass-by-address we pass the address of an existing object. Following program demonstrates all three methods of passing objects as function arguments:

Returning Objects

We can not only pass objects as function arguments but can also return objects from functions. We can return an object in the following three ways:

  1. Returning by value which makes a duplicate copy of the local object.
  2. Returning by using a reference to the object. In this way the address of the object is passed implicitly to the calling function.
  3. Returning by using the ‘this pointer’ which explicitly sends the address of the object to the calling function.




Following program demonstrates the three ways of returning objects from a function:

Output:

this Pointer

For every object in C++, there is an implicit pointer called this pointer. It is a constant pointer which always points to the current object. Uses of this pointer are as follows:

  • When data member names and function argument names are same, this pointer can be used to distinguish a data member by writing this->member-name.
  • It can be used inside a member function to return the current object by address by writing return *this.

The this pointer cannot be used along with static functions as static functions are not part of any object. Following program demonstrates the use of this pointer:

Modify the area() function in the above program with the following code:

Take your time to comment on this article.

Leave a Comment