instantiating with/without parentheses

instantiating an object by calling it's default constructor such as with foo() seems to do something different than instantiating without the parentheses. can anyone tell me what the difference is? the program below illustrates what I'm talking about.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class foo {
public:
    // constructors
    foo( void ) : a(0) { };
    explicit foo( const int x ) : a(x) { };
	foo( const foo& other ) { a = other.a; }
	foo& operator=( const foo& other ) { a = other.a; return *this; }
    int a;
};

int main() {
    foo bar;
    foo b;
    foo c(1);
    foo d();
    
    bar=b; // works
    bar=c; // works
    bar=d; // doesn't work

    return 0;
}


compiler complains:
1
2
3
4
5
main.cpp: In function ‘int main()’:
main.cpp:19:9: error: no match foroperator=’ in ‘bar = d’
main.cpp:19:9: note: candidate is:
main.cpp:7:7: note: foo& foo::operator=(const foo&)
main.cpp:7:7: note:   no known conversion for argument 1 from ‘foo()’ to ‘const foo&’
Last edited on
I think the compiler sees foo c(); as a function declaration for a function named 'c' that returns a 'foo' and takes no arguements.
C++'s Most Vexing Parse. Really. That's what it's called.
Line 15 doesn't define an object named c of type foo constructed by calling its default constructor. It declares a function named c that takes no parameters and returns a foo.
Too slow helios :P You are getting mighty close to 10k posts...should save a special one to mark the occasion
thank you. although functions aren't even allowed inside another function, so why would it parse like that?

1
2
3
4
5
int main() {
    int d() { return 3; } //error
    
    return 0;
}
You can't define functions in local scope. Declaring them is perfectly legal.
On the other hand, if you had this in global scope:
 
foo c();

would you expect c to be a function or an object?
a function of course. is there ever a reason to declare a function within another function? I just don't see the usefulness of this:

1
2
3
4
5
6
7
8
9
10

int main() {
    int d();
    
    return 0;
}

int d() {
	return 3;
}

You can't define another function inside one, but you can forward declare.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main() {
    void hello();

    hello();

    return 0;
}

void hello() {
    std::cout << "hello!\n";
}
Last edited on
why is that useful, since we can just forward declare in global space?
Topic archived. No new replies allowed.