Below C code works.
#include<iostream>
using namespace std;
class Complex{
private:
int real, imag;
public:
Complex(int r=0, int i=0){
real = r; imag = i;
}
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3;
}
When the parameterized constructor's variables r
and i
are uninitialized(eg: Complex(int r, int i)
), the compiler throws up the error
main.cpp:19:13: error: no matching function for call to ‘Complex::Complex()’ 19 | Complex c3; | ^~ main.cpp:10:5: note: candidate: ‘Complex::Complex(int, int)’ 10 | Complex(int r, int i){ | ^~~~~~~.
I understood this to be an issue with the statement Complex c3;
. Pardon me for being naive, but it's unclear why it works this way in the initial code snippet itself. Hope someone can clarify this.
CodePudding user response:
The Complex
constructor you show, with default arguments, can be called with two, one or zero arguments. If no arguments is used then the default values will be used.
But if you remove the default values, you no longer have a default constructor, a constructor that can be used without arguments.
It's really exactly the same as normal functions with default argument values...
Lets say you have this function:
void foo(int arg = 0)
{
// Implementation is irrelevant
}
Now this can be called as:
foo(123); // Pass an explicit argument
Or as:
foo(); // Equivalent to foo(0)
If you remove the default value:
void foo(int arg)
{
// Implementation is irrelevant
}
Then calling the function without any argument is wrong:
foo(); // Error: Argument expected
CodePudding user response:
The definition Complex(int r=0, int i=0)
allows for 0, 1 or 2 parameters. Complex c3;
is constructing a Complex
with 0 parameters.
You could instead have overloads, e.g.
class Complex{
private:
int real, imag;
public:
Complex() : real(0), imag(0) {}
Complex(int r, int i) : real(r), imag(i) {}
};
Note that it is better to use the member initialisers than assignment statements in the body of the constructor.