Reputation: 1027
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}
}
Upvotes: 0
Views: 154
Reputation: 62083
It's probably overkill for your example, but you might like to learn about the Named Parameter Idiom.
Upvotes: 0
Reputation: 6823
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=()).
Upvotes: 1
Reputation: 81349
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.
Upvotes: 1
Reputation: 12204
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
).
Upvotes: 0