Programming & Scripting Tutorials

C++: Get and Set Functions





Get and Set functions in C++ pretty much do as they say, get and set variables in classes.
They are basically very simple functions which can be achieved in many ways.

This is a simple example of some get and set functions in action:


#include <iostream>
using namespace std;

class SetandGet
{
public:
	void Reset(){
	TheVariable = 0;
	}
	void Set(int x){
		TheVariable = x;
	}
	int Get(){
		return TheVariable;
	}
private:
	int TheVariable;
};


int main(){
SetandGet MyNum;
MyNum.Set(3);
cout << MyNum.Get() << endl;
MyNum.Set(21);
cout << MyNum.Get() << endl;
MyNum.Reset();
cout << MyNum.Get() << endl;
system("PAUSE");
return 0;
}


This should all be quite easy for you apart from maybe the simple returning the variable (we haven’t done much on this), I'm sure if you read through it again you will pick it up, it simply just does as it says and tells anything calling the function that value.

If we wanted to return a string for example instead of having an int function you would use a string function like so:

string Get(){
return StringVariable;
}



This C++ tutorial was written by


Back to C++

Advertisement: