Property implementation for C++

In programming, a property is treated like a field but works like a method. Basically the cast operator and assignment operator for the value type of a property is overridden by user-defined functions.

I’ve seen properties being implemented in C++ with either template classes or inline anonymous classes. But I think it’s a better idea to do it using preprocessor macros. Behold:

#include <iostream>
using namespace std;

#define Property(T) class { private: typedef T value_t; T value; public: void _()
#define Get } operator value_t ()
#define Set void operator = (const value_t &new_value)

class Student {
public:

Property(int) {
Get { return value; }
Set { value = new_value; }
} ID;

};

int main() {
Student s;
s.ID = 1234;
cout << s.ID << endl;
}

 

 

 

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: