Pass class instance by reference?


6 posts
by davef21370 » Mon Apr 01, 2013 2:06 pm
I need to write a simple particle engine but can't seem to pass an instance of the Particle to my "doit" function.

Here's what I have...

The header defining the Particle class...
Code: Select all
#ifndef _BASIC_H_
   #define _BASIC_H_

#include <iostream>
using namespace std;

class Particle {
   public:
      int      x, y;
};

#endif


The main program, simply sets the particle's x value to 8 then calls 'doit'...
Code: Select all
#include "basic.h"
#include <stdio.h>

#include "stuff.cpp"

int main() {
   Particle      p;
   
   p.x = 8;
   doit(p);
   cout << p.x;
}


The 'doit' function, change the particle's x value from 8 to 2...
Code: Select all
#include "basic.h"

void doit(Particle p) {
   p.x = 2;
}


But the x value stays at 8, how do I pass the Particle as a reference ??

Thanks in advance.
Dave.
Please feel free to tap into my abundant lack of knowledge.
User avatar
Posts: 515
Joined: Fri Sep 21, 2012 4:13 pm
Location: Up North
by OtherCrashOverride » Mon Apr 01, 2013 2:14 pm
Code: Select all
void doit(Particle& p)
Posts: 582
Joined: Sat Feb 02, 2013 3:25 am
by davef21370 » Mon Apr 01, 2013 2:24 pm
Thanks so much, I've tried every & and * combination in every part of my code and it's been driving me nuts!!!

That worked a treat, can crack on now and get results, and really need to buy a book (20+ years since using C on the Mac, forgot more than I could say.)

Cheers.
Dave.
Please feel free to tap into my abundant lack of knowledge.
User avatar
Posts: 515
Joined: Fri Sep 21, 2012 4:13 pm
Location: Up North
by davef21370 » Mon Apr 01, 2013 2:37 pm
Sorry, small oversight, how do I pass an array of class instances?

Ta again.
Dave.
Please feel free to tap into my abundant lack of knowledge.
User avatar
Posts: 515
Joined: Fri Sep 21, 2012 4:13 pm
Location: Up North
by OtherCrashOverride » Mon Apr 01, 2013 4:47 pm
Code: Select all
void doit(Particle& p[])
Posts: 582
Joined: Sat Feb 02, 2013 3:25 am
by davef21370 » Mon Apr 01, 2013 5:56 pm
Thanks again.
Dave.
Please feel free to tap into my abundant lack of knowledge.
User avatar
Posts: 515
Joined: Fri Sep 21, 2012 4:13 pm
Location: Up North