Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
May 2, 1997

Using macros to simulate "delphi" properties in C

Question:
Is there a way to do some macro magic with members of a given class so that when a designated name is called, it invokes 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 class
PROPERTY(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 the values of x_ and y_ so they can be accessed as read-only variables of the object. This of course only works for the simplest of cases and should 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.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date