views:

134

answers:

4

Is there any tool that generates set and get methods for a class automatically.

Just I create classes very frequently and would like to have a tool which for each class-member wil generate the following functions automatically:

Member_Type getMemberName() const; //in header file
Member_Type getMemberName() const //in source file 
{
    return member;
}

void setMemberName(const Member_Type & val); //in header
void setMemberName(const Member_Type & val) //in source file 
{
    member = val;
}

I have met a macro like this but did not like the idea:

#define GETSETVAR(type, name) \
private: \
    type name; \
public: \
    const type& get##name##() const { return name; } \
    void set##name##(const type& newval) { name = newval; }

May be someone knows how to do that with MS Visual Studio, or eny other tool?

+5  A: 

Not the tool actually, but you could use Encapsulate Method in Visual Assist X, for example, which makes getter / setter methods for some private class member.

Sure, many of tools that work similiar as VAX do have the same methods.

Also, if you have to do this action for a huge amount of classes, you could implement your own command-line tool and lauch it for every source file that you have.

Kotti
Could you make clear? Add some details, please.
Narek
My own script is a way :)!
Narek
+3  A: 

Why do you want to be generating these methods?

Generally a better approach is to make an actual use interface that defines operations on the object, not just sets of individual attributes. By creating a class interface, you avoid the need to write a bunch of getters and setters.

If you really need to generate public getters and setters for all (or even most) of your attributes, probably better is to just make it a struct, then no such generation is needed.

Mark B
+1  A: 

If you're using Visual Studio, my AtomineerUtils add-in will do this - it converts a member variable declaration into get/set methods.

Jason Williams
+1  A: 

Agree with Kotti - Visual Assist (and other addins) provide this functionality.

The actual source code should have the getters / setters, because you probably want to add validation and change notification to the setters as needed.

Using a macro for that is just... facepunchable. (willing to elaborate on request).

peterchen