Fed up of wriing getters and setters for all the variables in a class? Here is a one step solution using a macro (generously contributed by my friend Jibin Raju). See the following code segment.
#define GETSET(type, var) \
private: \
type _##var; \
public: \
type Get##var() \
{\
return _##var; \
}\
void Set##var(type val) \
{\
_##var = val; \
}
The above macro GETSET will automatically expand any variable defined using var to two public functions.
1. void Setvar(type val) and
2. type Getvar()
For example, if I declare GETSET(int, MyInt), in the class it will be expanded as
public:
int GetMyInt() {return _MyInt;}
void SetMyInt(int val) {_MyInt = val;}
private:
int _MyInt;
An example using the above macro is given below.
#include <iostream>
#include <string>
using namespace std;
class CMyClass
{
GETSET(int,MyInt)
GETSET(float,MyFloat)
GETSET(string,MyString)
};
int main()
{
CMyClass MyClass;
MyClass.SetMyInt(10);
MyClass.SetMyFloat(23.35f);
MyClass.SetMyString("This is my string");
cout << MyClass.GetMyInt() << '\n';
cout << MyClass.GetMyFloat() << '\n';
cout << MyClass.GetMyString() << '\n';
return 0;
}
Posted by cppkid