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 tempObject.variable.

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

12/13/2009 3:23:06 PM

Accepted Answer

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

12/13/2009 12:43:48 PM

At its simplest:

#include <iostream>
using namespace std;

class A {
     A( int x ) : n( x ){}
     void print() { cout << n << endl; }
     int n;

void func( A p ) {

int main () {
   A a;
   func ( a );

Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow