• 0

[C++] Passing objects into a function by reference


Question

How would I pass objects into a function by reference? If I wanted to pass 3 Student objects, stuch as S, T, Answer? If I put them in as reference whatever changes I make to them in the function will also change them in main right?

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

1. You would pass them in normally

// Prototype

void PassByRef( Student& s );

Student S;

PassByRef( S );

// or if you use dynamic allocation

Student* S = new Student();

PassByRef( *S );

2. yes, changes will be reflected in the calling function. If you don't want side effects but want by reference passing, have your parameters be constant references.

// prototype

void PassByRefNoChange( const Student& );

Edited by weenur
Link to comment
Share on other sites

  • 0

I have a program I have done. It is all finished. It uses a menu system such as:

A - add

P - print

C - change

D - delete

Q - quit

My professor wants me to use modular programming. Should I put each of these into functions? Such as an add, print, change, delete, quit function? And what if the class uses templates? would it be the same way as if it did not need templates? Basically I have an Index class that utilizes templates, and a Student Class that does not. Can I put both of them into a function at the same time and how would I do so?

Edited by saiz66
Link to comment
Share on other sites

  • 0

If the user picks "A" the add function should be called, if "P", the print function should be called.

If the class is templated, this should have absolutely no effect on how the functions are called. Templating is for using any data type with a given class.

Can I put both of them into a function at the same time and how would I do so?

functionName(studentVariable, indexVariable);

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.