View Single Post
Old 02-19-2007, 06:03 PM   #2 (permalink)
forrestcupp
forrestcupp's Avatar
 
Ultra Techie

Join Date: Feb 2007

Posts: 588

forrestcupp is on a distinguished road

Default Re: problem with my C++ code

Here is a simple console program that demonstrates what you are wanting. I made a class called "data" with an integer called person. The constructor for this class sets person = 11. Then I made another class called "other" just to show that it is definitely out of scope of the data class. This class has a function that takes a pointer as an argument. When I called this function from the main function, I sent the reference of the integer "person" from the data object that I created. A reference is the address of a variable. A pointer is a variable that holds a reference address. In this "other" function, the value is changed to 52, which affects the original variable.

Code:
#include "stdafx.h"
#include <iostream>
using namespace std;

class data
{
public:
	int person;
	data()
	{
		person = 11;
		return;
	}
};

class other
{
public:
	other(){};
	void changeVariable(int *change)
	{
		*change = 52;
		return;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	data myData;
	other myOther;
	cout<<myData.person<<endl;
	myOther.changeVariable(&myData.person);
	cout<<myData.person<<endl;
	cin.get();
	return 0;
}

forrestcupp is offline