c++compiler-errorsmember-functionsfunction-qualifier

Initializing member functions fields


While reading the a C++1z paper called Abominable functions I've found the following code:

class rectangle {
    public:
    using int_property = int() const;  // common signature for several methods

    int_property top;
    int_property left;
    int_property bottom;
    int_property right;
    int_property width;
    int_property height;

    // Remaining details elided
};

I've never seen code like that before (the paper itself states that it is very strange to find code like that) so I wanted to give a try to this approach and give a value to those int_property:

class rectangle {
    int f() const { return 0; }
    public:
    using int_property = int() const;  // common signature for several methods

    int_property top = f; // <--- error!
    int_property left;
    int_property bottom;
    int_property right;
    int_property width;
    int_property height;

    // Remaining details elided
};

In my modification above, the compiler complaints about the f saying that (only '= 0' is allowed) before ';' token; my other attempts were:

class rectangle {
    int f() const { return 0; }
    public:
    using int_property = int() const;  // common signature for several methods

        // invalid initializer for member function 'int rectangle::top() const'
        int_property top{f};
        int_property left{&f};

        // invalid pure specifier (only '= 0' is allowed) before ';' token
        int_property bottom = f;
        int_property right = &f;

        int_property width;
        int_property height;

        // class 'rectangle' does not have any field named 'width'
        // class 'rectangle' does not have any field named 'height'
        rectangle() : width{f}, height{&rectangle::f} {}
};

So the question is:


Solution

  • int() const is a function type with a cv-qualifier. The declaration int_property top; declares a function, not a variable. This declaration has just the same effect as int top() const;.

    As with other member functions, you define them by providing a function definition.

    int rectangle::top() const {
        return 0;
    }