Home > Software design >  Default value for parameter of class where value is another class
Default value for parameter of class where value is another class

Time:11-24

Title may be a little bit confusing but basically I have a class 'Quaternion' which has 2 parameters, the first being another instance of a class Vector3 and the other being a float.

Vector3 takes 3 floats as parameters and assigns them to x, y, and z.

I want to set default parameters for the Quaternion class but I am unsure how to set default parameters with a class as a parameter.

Vector3

class Vector3 {
  public:
    float x, y, z;

    Vector3(float uX, float uY, float uZ) {
      this->x = uX;
      this->y = uY;
      this->z = uZ; 
    }
};

Quaternion

class Quaternion {
  public:
    Vector3 axis;
    float scalar;

    Quaternion(Vector3 uAxis, float uScalar = 0) {
      axis = uAxis;
      scalar = uScalar;
    };
};

I would like to have the default parameter for uAxis to be a Vector3 with x, y, and z set to 1, 0, 0 respectively, but i am unsure how i can do this.

CodePudding user response:

I think this is what you were looking for:

class Quaternion {
  public:
    Vector3 axis;
    float scalar;

    Quaternion(Vector3 uAxis = Vector3(1.0, 0.0, 0.0), float uScalar = 0) {
      axis = uAxis;
      scalar = uScalar;
    };
};

It is possible to call a constructor of a class to set a default parameter. Here is the corresponding cpp reference default arguments.

CodePudding user response:

This is what you want. Always use the initialisation list on the constructor unless you have to do something with the parameters docs. Also I am passing the uAxis as const reference which is always a good thing to do for ADT (Abstract Data Types) Unless you have special requirements.

 class Quaternion 
 {
    Vector3 axis;
    float scalar;

 public:
    Quaternion(const Vector3 & uAxis = Vector3(1.0, 0.0, 0.0), float uScalar = 0) :
      axis(uAxis),
      scalar(uScalar)
    {
    }
 };

CodePudding user response:

Another option would be to use default member initialization for axis within Quaternion. That way, just creating a Quaternion q{} would set axis to whatever you want. [Demo]

class Quaternion {
public:
    Vector3 axis{1.0, 0.0, 0.0};
    float scalar{};

    Quaternion() = default;
    ...
};

For the Quaternion(Vector3 uAxis, float uScalar) constructor, it would be preferable to use a member initializer list:

Quaternion(Vector3 uAxis, float uScalar) : axis{uAxis}, scalar{uScalar} {};

Also, you can remove Vector3's constructor, making Vector3 an aggregate:

struct Vector3 {
    float x{};
    float y{};
    float z{};
};

Vector3 v{1.1, 2.2, 3.3};
  • Related