0

I am trying to add an additional argument into a constructor:

e.g. adding the argument 'y'

public Object(int x, int y) {
  int x1;
  int y1;
  x1=x;
  y1=y;
}

the original constructor was

public Object(int x) {
  int x1;
  int y1;
  x1=x;
  y1=(default number);
}

I know in Java, you could do something like this(x, 1) to set y to 1 if y is not given, but I think I read that constructors calling constructors doesn't work in C++?

Is there a way to initialize y when it's not given, i.e. making sure that (1) and (2) both work?

Object o1 = new Object (5);   // (1)
Object o2 = new Object (5,3); // (2)
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
user262476
  • 27
  • 4

1 Answers1

1

Note: For starters you are confusing the syntax of java with that off C++, what you have in your post is not valid C++. In either case; what you are looking can be solved using default arguments, or constructor delegation* (c++11).


ALTERNATIVE #1: DEFAULT ARGUMENTS

Adding a default argument to a function declaration will make it possible to call the function, in this case a constructor, without specifying a value.


#include <iostream>

class Obj {
  public:
    Obj (int x, int y = 123) {
       std::cout << "x: " << x << ", y: " << y << std::endl;
    }

    ...
};

Obj a (1);
Obj b (2, 3);

Output

x: 1, y: 123
x: 2, y: 3


ALTERNATIVE #2: CONSTRUCTOR DELEGATION

In C++11 you can call another constructor from one constructor using the mem-initializer, as in the below example. The output will be identical to the example using default arguments.

class Obj {
  public:
     Obj (int x, int y) { // (1)
       std::cout << "x: " << x << ", y: " << y << std::endl;
     }

     Obj (int x)
       : Obj (x, 123)     // call (1)
     { }
};

Obj a (1);
Obj b (2, 3);
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196