Getters and Setters for a class using a Macro

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


   int GetMyInt() {return _MyInt;}

   void SetMyInt(int val) {_MyInt = val;}


   int _MyInt;

An example using the above macro is given below.



using namespace std;

class CMyClass







int main()


   CMyClass MyClass;



   MyClass.SetMyString(“This is my string”);

   cout << MyClass.GetMyInt() << '\n';    cout << MyClass.GetMyFloat() << '\n';    cout << MyClass.GetMyString() << '\n';    return 0;    } [/sourcecode]


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: