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


public:

   int GetMyInt() {return _MyInt;}

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

private:

   int _MyInt;

An example using the above macro is given below.

#include

#include

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;    } [/sourcecode]

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: