There are always pros and cons of using macros in your project.The advantage of using a macro is that it reduces the amount of coding you need to do , and the disadvantages of using a macro other than the fact that the size of the executable code is increased its also difficult to debug.
I personally try to stay away from macros but hey , you should always be familiar with things you never know when you might come across them , just like i did at work :(
#define IMPLEMENT_SET_GET_METHOD( type , name ) \
IMPLEMENT_SET_METHOD( type , name ); \
IMPLEMENT_GET_METHOD( type , name );
#define IMPLEMENT_SET_METHOD( type , name ) \
private: type name; \
public: void set_##name( const type& value ) { name = value; }
#define IMPLEMENT_GET_METHOD( type , name ) \
public: const type& get_##name() const { return name; }
class myclass
{
IMPLEMENT_SET_GET_METHOD( int , val)
} ;
void main()
{
myclass obj;
obj.set_val(34);
cout << obj.get_val();
cin.get();
}
I personally try to stay away from macros but hey , you should always be familiar with things you never know when you might come across them , just like i did at work :(
#define IMPLEMENT_SET_GET_METHOD( type , name ) \
IMPLEMENT_SET_METHOD( type , name ); \
IMPLEMENT_GET_METHOD( type , name );
#define IMPLEMENT_SET_METHOD( type , name ) \
private: type name; \
public: void set_##name( const type& value ) { name = value; }
#define IMPLEMENT_GET_METHOD( type , name ) \
public: const type& get_##name() const { return name; }
class myclass
{
IMPLEMENT_SET_GET_METHOD( int , val)
} ;
void main()
{
myclass obj;
obj.set_val(34);
cout << obj.get_val();
cin.get();
}
1. Reduces the code.
ReplyDelete2. It is up to the complier discreation that it would substitute the Macro/Inline code.
- If it has any loop statements (or) any return statements then Macro/Inline statement would be ignored.
3. If we are talking about the C++ then usage of const is much better then Macros/Inlines.
4. Macros increases the load on Pre-processor and in long term our objective should be reducing the Pre-processor load and increase the complier load.
5. Macro error at certain stage is not self explainatory.
Others - Please feel free to comment.
Not only can macro reduce & obfuscate (there by making it difficult to maintain and read) code, at times it can be used very effectively as boiler-plate code generator. See [http://www.boostpro.com/tmpbook/preprocessor.html] for such an example for an introduction and this [http://members.gamedev.net/sicrane/articles/metaprogramming.html] for further details
ReplyDelete@Jayanth and Mr.XYZ
ReplyDeleteI completely agree with you and personally recommend using Macros for get and set statement as both of you have correctly mentioned that debugging would be difficult if macros are extensively used