Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

parameters

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

#include<iostream>  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 tempObject.variable.

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

like image 552
James Avatar asked Dec 13 '09 12:12

James


People also ask

Can class objects be passed as function arguments?

Passing and Returning Objects in C++ In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so.

How do you pass a function as a parameter in C?

Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.


1 Answers

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.

e.g.

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.]

like image 131
CB Bailey Avatar answered Oct 12 '22 09:10

CB Bailey