Search code examples
c++visual-studio-2008oop

How to generate automatic properties (get, set) for Visual Studio 2008 C++


Having read this question on generating getters and setters in Visual Studio and tried (somewhat) the techniques described, I have failed miserably to graduate beyond the longhand way of writing Getters and Setters.

While I recognize the conceptual advantage of encapsulation (private members of a class in this case), writing 25 getters and setters is a waste of space and my time.

Why 25? Well apart form the exageration factor (approx 2.5) I just don't know at what point I will need access to that one variable in the future. I guess I could write a function that returns all of them and fish out the one I need, but if I add more members (often do) then the function must be changed throughout the code.

I like the form suggested here for VS 2008:

string sName { get; set; }

But it won't compile in C++. Is this just for .NET and C#?

Is there some tidy way to simulate this in C++?


Solution

  • Thanks @Dan for pointing out this trick in Microsoft Compiler (non-portable)

    Here is the way:

    struct person
    {
        std::string m_name;
        void setName(const std::string& p_name)
        {
            m_name = p_name;
        }
        const std::string& getName() const
        {
            return m_name;
        }
        // Here is the name of the property and the get, set(put) functions
        __declspec(property(get = getName, put = setName)) std::string name;
    };
    int main()
    {
        person p;
    
        p.name = "Hello World!"; // setName(...)
        std::cout << p.name;     // getName(...)
    }
    

    After creating your member variables plus the getters and setters of these member variables, you create a property for each getter/setter pair. You can call it whatever you want, because you have to specify the getter and setter for this property.


    Just for fun :)

    #define property(Type, Variable) private: Type Variable; \
          public: const Type##& get##Variable() const { return Variable; }; \
          void set##Variable(const Type& Variable##_) { Variable = Variable##_;}
    
    
     struct Test
     {
         property(int, x); property(int, y);
         property(std::string, text);
     };
    
    int main()
    {
        Test t;
    
        t.setx(10);
        t.sety(10);
        t.settext("Hello World at: ");
        std::cout << t.gettext() << " " << t.getx() << ", " << t.gety();
    }