Can anybody explain to me the difference between Complex a; and Complex b();?
#include<iostream>
class Complex
{
public:
Complex()
{
std::cout << "Complex Constructor 1" << std::endl;
}
Complex(float re, float im)
{
std::cout << "Complex Constructor 2" << std::endl;
}
~Complex()
{
std::cout << "Complex Destructor" << std::endl;
}
};
int main()
{
Complex a;
std::cout << "--------------------------" << std::endl;
Complex b();
std::cout << "--------------------------" << std::endl;
Complex c(0,0);
std::cout << "--------------------------" << std::endl;
return 0;
}
Output:
Complex Constructor 1
--------------------------
--------------------------
Complex Constructor 2
--------------------------
Complex Destructor
Complex Destructor
As you can see, Complex a; does call its default constructor, Complex b(); doesn't and Complex c(0,0); calls an overloaded constructor.
What is going on here? I thought, that Complex b(); would create a stack-variable and call it's default constructor to initialize it?
Complex b();
is function declaration. That is function taking no arguments and returning Complex
object.
This is very common mistake and has its own name: most vexing parse
C++11 helped with this issue by introducing uniform initialization syntax
Complex b{};
Complex b();
declares a function that has no arguments and returns a Complex
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With