2

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 };
}

3 Answers3

3

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.)

Community
  • 1
  • 1
Keith M
  • 853
  • 10
  • 28
1

You can always overload constructors or create methods that "set multiple different object properties in one statement":

class Animal {
public:
  Animal() {

  };

  Animal(int a, int b, int c) {
    x = a;
    y = b;
    z = c;
  }

  void setMembers(int a, int b, int c) {
    x = a;
    y = b;
    z = c;
  }

private:
  int x;
  int y;
  int z;
};

int main() {
  // set x, y, z in one statement
  Animal a(1, 2, 3);

  // set x, y, z in one statement
  a.setMembers(4, 5, 6);

  return 0;
}
0

Solution 1 for Animal (http://ideone.com/N3RXXx)

#include <iostream>

class Animal
{
    public:
        int x;
        int y;
        int z;
        Animal & setx(int v) { x = v; return *this;}
        Animal & sety(int v) { y = v; return *this;}
        Animal & setz(int v) { z = v; return *this;}
};

int main() {
    Animal anml;
    anml.setx(5).sety(6).setz(7);
    std::cout << anml.x << ", " << anml.y << ", " << anml.z << std::endl;
    return 0;
}

Solution 2 for any class with x, y (https://ideone.com/xIYqZY)

#include <iostream>

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


template<class T, class R> T& setx(T & obj, R x) {  obj.x = x;  return obj;}
template<class T, class R> T& sety(T & obj, R y) {  obj.y = y;  return obj;}

int main() {
    Animal anml;
    sety(setx(anml, 5), 6);
    std::cout << anml.x << ", " << anml.y << std::endl;
    return 0;
}
Alexey Malistov
  • 26,407
  • 13
  • 68
  • 88