Search code examples
c++objectmember

How do I set multiple class members in one statement in C++?


Is it possible to set multiple different class members in one statement? Just an example of how this would be done:

class Animal
{
    public:
        int x;
        int y;
        int z;
};

void main()
{
    Animal anml;

    anml = { x = 5, y = 10, z = 15 };
}

Solution

  • To "convert" Barry's comment into an answer, yes, under the conditions here:

    An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

    Example:

    class Animal
    {
        public:
            int x;
            int y;
            int z;
    };
    
    int main() {
        Animal anml;
    
        anml = { 5, 10, 15 };
        return 0;
    }
    

    (This Community Wiki answer was added in accordance with this meta post.)