0

I would like to do something like this

class foo{
private:
    double a,b;

public:
    foo(double a=1, double b=2){
        this.a=a;
        this.b=b;
    }
}

int main(){
    foo first(a=1);
    foo first(b=2);
}

Is such thing possible or do I need to create two new constructors?

Here comes the 2. question: What is the difference in those two constructors:

class foo{
private:
    int a;

public:
    foo(int in):a(in){}
}

or

class foo{
private:
    int a;

public:
    foo(int in){a=in}
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211
bios
  • 997
  • 3
  • 11
  • 20

4 Answers4

1
foo first(a=1);
foo first(b=2);

You cannot really have this in C++. It was once considered for standarization but then dropped. Boost.Parameter does as much as it can to approximate named parameters, see http://www.boost.org/doc/libs/1_47_0/libs/parameter/doc/html/index.html

foo(int in):a(in){}
foo(int in){a=in}

The first constructor is initializating a, while the second is assigning to it. For this particular case (int) there isn't much of a difference.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
1

In C++, the this pointer is a pointer not an object (in java, you would access it with the .). That said, you would need a dereferencing arrow (i.e. this->member or (*this).member).

In any case, this can be done. However, parameterization in C++ works in reverse order and cannot be named. For instance, int test(int a=2, int b=42) is legal as well as int test(int a, int b=42). However, int test(int a=2, b) is not legal.

As for your second question, there is no significant difference between the constructors in this example. There are some minor (potential) speed differences, but they are most-likely negligible in this case. In the first one you are using an initializer list (required for inheritance and calling the constructor of the base class if need be) and the second one is simply explicitly setting the value of your variable (i.e. using operator=()).

RageD
  • 6,693
  • 4
  • 30
  • 37
  • 1
    Worth noting for (2) that the speed differences will be more substantial were the type of `a` not a basic type. Using an initializer list ensures that `a` is constructed once, rather than default constructed and later assigned. For complex types this might well mean avoiding a call to `new` and `delete`. – Keith Sep 14 '11 at 01:30
0

C++ doesn't support named parameters so this:

int main()
{ 
  foo first(a=1); 
  foo first(b=2); 
} 

Is not legal. You also have multiple non-unique idenfiers (e.g. first).

sashang
  • 11,704
  • 6
  • 44
  • 58
0

It's probably overkill for your example, but you might like to learn about the Named Parameter Idiom.

Community
  • 1
  • 1
Fred Larson
  • 60,987
  • 18
  • 112
  • 174