Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Default value for parameter of class where value is another class

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading