0

So I've been trying to implement the same type of get and set like in C#. But something generated some doubts about how the variables are declared under the hood in c++. Here's the code:

class foo {
    foo Getter() {
        return *this;
    }
    foo f; //this isn't allowed
    __declspec(property(get = Getter)) foo f2; // but this IS
};

What's really happening here?

Corelli
  • 21
  • 6
  • `__declspec(property)` is a compiler-specific extension and not standard C++. Please add a tag for your compiler (I guess `visual-c++`). C++ does not have properties. – walnut Dec 24 '19 at 15:00
  • The `foo f;` declaration is invalid, because `foo` is not a complete type at this point. You cannot have a type be member of itself (but you can have a pointer or reference to the type itself as member). – walnut Dec 24 '19 at 15:02
  • I get your point. But what specifically does `__declspec(property())` do to allow a non complete type to be declared here? – Corelli Dec 24 '19 at 15:06
  • 1
    Yes, it is visual-c++ (forgot to add the tag, adding now) – Corelli Dec 24 '19 at 15:08
  • `f2` is just syntactic sugar over `Getter()`, so there's no actual `Foo` member. Because of that, the incomplete declaration is enough to make it valid. – parktomatomi Dec 24 '19 at 16:07
  • I was surprised to learn this works in clang too with a flag: https://godbolt.org/z/FgkXsn – parktomatomi Dec 24 '19 at 16:16

0 Answers0