Jim Jeffries
Jim Jeffries

Reputation: 10081

C++ equivalent of Python properties

Is there an equivalent of Python properties in C++? Or would it just be better to do this using getters and setters?

Upvotes: 8

Views: 3196

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279315

In C++ you're either calling a member function, or you're accessing a data member. Python properties are essentially a way of doing the former using the syntax of the latter and there's no sensible way to do that in C++.

In theory you could hack together something with a macro, #define looks_like_data really_a_function() but it wouldn't be pretty. Or sensible. The only necessary reason to make a function look like data is to maintain compatibility with old calling code back from when it used to be data. But in C++ this won't give you binary compatibility, and it doesn't even really give you source compatibility given that the macro will break calling code that already uses the name looks_like_data for something else in another context. So there's not a lot of point.

Another thing you could do is to create an actual data member that acts as a proxy for the "logical" type of the data:

struct Proxy {
    Foo *foo;
    Proxy(Foo *foo) : foo(foo) { }
    operator int() const {
        // getter code goes here,
        // use (const Foo*)foo rather than foo
    }
    Proxy &operator=(int a) {
       // setter code goes here
    }
    // optionally also implement boilerplate +=, -=, etc.
};

struct Foo {
    // optionally 
    // friend class Proxy;
    Proxy looks_like_data;
    Foo() : looks_like_data(this) { }
};

This is almost, but not quite, sensible. Using an implicit conversion still breaks source compatibility, because there's a rule that there can only be one user-defined implicit conversion in a chain, so if a caller has written code back when looks_like_data really was an int, and their code implicitly converts that int to Bar, then once looks_like_data becomes a Proxy it will no longer implicitly convert to Bar and you've broken their code anyway.

So after all that, you're best using getter/setter functions if your class really needs something that looks like a read/write property.

Upvotes: 17

TeaWolf
TeaWolf

Reputation: 714

There are no properties in standard C++. However, if you're developing on the Microsoft platform you could use their language extension:

http://msdn.microsoft.com/en-us/library/yhfk0thd.aspx

Upvotes: 7

Diego Sevilla
Diego Sevilla

Reputation: 29021

Yes, explicit getter and setters would be the closest construct in C++.

Upvotes: 13

Related Questions