learningCurve
learningCurve

Reputation: 109

Constructor with Default Arguments

What exactly is this piece of code doing?

This is a constructor in a c++ book I'm reading and it glosses over what exactly is going on.

Derived(int a=0, int b=0) : Base(a), dNum(b){
    cout<< "Derived constructor." <<endl;
}

So it passes a and b into the base constructor of the class that this code is derived from. But what is going on with the "int a=0, int b=0" ? Are we setting them to zero in the case that an object is created with only 1arg or no args? If so wont a and b just disappear once we leave the scope or does that happen after they are already passed into the base class so it doesn't matter that they are declared on the fly like that.

Upvotes: 0

Views: 690

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 62120

These are known as "default parameters" in C++. (And also in C#.)

Now that you know how they are called, you can google them.

In a nutshell, they allow the caller to omit supplying values for them, and if the caller does not supply values, then the given values will be used.

They are just syntactic sugar, meaning that a constructor coded as Derived(); will be compiled as Derived( 0, 0 );

Upvotes: 1

Related Questions