User avatar
davef21370
Posts: 875
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Pass class instance by reference?

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.
Apple say... Monkey do !!

OtherCrashOverride
Posts: 582
Joined: Sat Feb 02, 2013 3:25 am

Re: Pass class instance by reference?

Mon Apr 01, 2013 2:14 pm

Code: Select all

void doit(Particle& p)

User avatar
davef21370
Posts: 875
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: Pass class instance by reference?

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.
Apple say... Monkey do !!

User avatar
davef21370
Posts: 875
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: Pass class instance by reference?

Mon Apr 01, 2013 2:37 pm

Sorry, small oversight, how do I pass an array of class instances?

Ta again.
Dave.
Apple say... Monkey do !!

OtherCrashOverride
Posts: 582
Joined: Sat Feb 02, 2013 3:25 am

Re: Pass class instance by reference?

Mon Apr 01, 2013 4:47 pm

Code: Select all

void doit(Particle& p[])

User avatar
davef21370
Posts: 875
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: Pass class instance by reference?

Mon Apr 01, 2013 5:56 pm

Thanks again.
Dave.
Apple say... Monkey do !!

Return to “C/C++”

Who is online

Users browsing this forum: 6by9 and 12 guests