James James - 18 days ago 5
C++ Question

How to use a class object in C++ as a function parameter

I am not sure how to have a function that receives a class object as a parameter. Any help? Here is an example below.


void function(class object); //prototype

void function(class tempObject)
//do something with object
//use or change member variables

Basically I am just confused on how to create a function that will receive a class object as its parameters, and then to use those parameters inside the function such as

Sorry if this is kind of confusing, I am relatively new to C++.


class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.


class ANewType
    // ... details

This defines a new type called ANewType which is a class type.

You can then use this in function declarations:

void function(ANewType object);

You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.

If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.

void function(ANewType& object); // object passed by reference

This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.

[* The class keyword is also used in template definitions, but that's a different subject.]