How can an object be passed as an argument to a member function in c plus plus?

Objects can be passed to member functions in C++ in a variety of ways. The function's parameter determines how the object is handled by the function. The following examples show all the possible parameter variations (the same variations apply to member functions as well as external functions):

By reference:

void foo(const MyObject& o);

void foo(MyObject& o);

By value:

void foo(const MyObject o);

void foo(MyObject o);

By pointer:

void foo(MyObject* p);

void foo(const MyObject* p);

void foo(MyObject* const p);

void foo(const MyObject* const p);

The pointer variations can be extended to include pointer to pointer variants and so on. However, it is not possible for any one function in the same namespace to be overloaded with all eight of these variations unless the return values are altered or dummy parameters are employed to eliminate the ambiguities. Under normal circumstances there will only be two overloads provided, one of which must accept a pointer. If additional overloads are provided, they must be pointer to pointer variants.

Which variations are actually provided depend upon how the function interacts with the object. If the parameter is declared const then the function can only call the object's const member functions and access its mutable member variables. In the case of the pointer variations, this means those that declare const MyObject*parameters. Those with const p parameters only mean the pointer will always point at the same object within the function body.

Passing objects by reference is the preferred method of passing objects to functions whenever an object is guaranteed to be known to exist. Passing by pointer is often provided as an overload to cater for those cases where an object may not exist; in some cases this may in fact be the only function provided. Regardless, passing by reference or by pointer is effectively the same as passing the object itself. Thus if the parameter is declared non-const, any changes made to the function's parameter will be reflected in the original object.

Passing objects by value is rarely used and should be avoided as much as is possible. When you pass an object by value, the object's copy constructor is automatically invoked. This is often unnecessary and can have an enormous impact upon your program's performance and memory consumption, especially with complex object's that contain embedded objects and/or inherit from other classes, each of which must be copied. However, there will be occasions where a function needs to modify an object where those changes would be undesirable. Thus passing by value would be deemed acceptable. The alternative would be to manually copy your object and then pass the copy by reference or by pointer instead.