Does C++11 have C#-style properties?

Radim Vansa picture Radim Vansa · Dec 3, 2011 · Viewed 69.2k times · Source

In C#, there is a nice syntax sugar for fields with getter and setter. Moreover, I like the auto-implemented properties which allow me to write

public Foo foo { get; private set; }

In C++ I have to write

private:
    Foo foo;
public:
    Foo getFoo() { return foo; }

Is there some such concept in the C++11 allowing me to have some syntax sugar on this?

Answer

psx picture psx · Apr 16, 2014

In C++ you can write your own features. Here is an example implementation of properties using unnamed classes. Wikipedia article

struct Foo
{
    class {
        int value;
        public:
            int & operator = (const int &i) { return value = i; }
            operator int () const { return value; }
    } alpha;

    class {
        float value;
        public:
            float & operator = (const float &f) { return value = f; }
            operator float () const { return value; }
    } bravo;
};

You can write your own getters & setters in place and if you want holder class member access you can extend this example code.