Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Strange constructor behaviour

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?

like image 961
user1816771 Avatar asked Nov 11 '12 22:11

user1816771


2 Answers

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{};
like image 174
PiotrNycz Avatar answered Nov 17 '22 01:11

PiotrNycz


Complex b(); declares a function that has no arguments and returns a Complex.

like image 4
Oswald Avatar answered Nov 17 '22 02:11

Oswald