devxlogo

Using macros to simulate “delphi” properties in C

Using macros to simulate “delphi” properties in C

Question:
Is there a way to do some macro magic with members of a given class sothat when a designated name is called, itinvokes the macro that called the class member,such as:

class Point{      int x,y;public:     void  Set_X(int n){x=n;}     int  Get_X(){return x;}    … etc …};#define PROPERTY(name,read,write)………..//use macro on point classPROPERTY(X,Get_X,Set_X);….  Point p;    //declare an object  int x;  x = p.X;    // macro inserts   p.Get_X() here  p.X = x;   // macro inserts   p.Set_X(x) here

Answer:
No, there is no way to make a macro do what you are looking for,but another technique can be used here if you absoulutely must do that.

class Point{public:	const int &x;	const int &y;	Point (int xc,int yc) : x(x_),y(y_),x_(xc),y_(yc)	{	}private:	int x_;	int y_;};
Here I have declared two references to integers that are initialized with thevalues of x_ and y_ so they can be accessed as read-only variables ofthe object. This of course only works for the simplest of cases andshould be avoided as much as possiable.

The C++ language does not provide a simple mechanism to do this, so it is necessary to write the get/set routines for properties of a class. If it is any consolation, you can choose to name the get/set method the same. For example:

class Point{public:	Point (int xc,int yc) : x_(xc),y_(yc)	{	}	void x(const int xc){x_ = xc;}	int x() const { return x_;}private:	int x_;	int y_;};
This looks a lot better than setX and getX.
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist