syntax semantics: instantiation without arguments: parentheses

J

John Goche

Hello,

I would like to know why the first three statements
produce output whereas the last one does not.
Also, should parentheses be included when
constructing such an instance on the heap?
What about on the stack? Why or why not.

Thanks,

JG

--- input code: ------------------------------------

#include <iostream>

class Foo {

public:

Foo() {

std::cout << "hello" << std::endl;

}

private:

int x;

};

int main() {
std::cout << "one" << std::endl;
Foo *foo = new Foo;
std::cout << "two" << std::endl;
Foo *bar = new Foo();
std::cout << "three" << std::endl;
Foo hello;
std::cout << "four" << std::endl;
Foo bye();
}

----- output: ------------------------------

$ ./hello
one
hello
two
hello
three
hello
four

-----------------------------------------------
 
D

David Harmon

On 14 Sep 2006 04:39:30 -0700 in comp.lang.c++, "John Goche"
Foo bye();

This is a declaration of a function named "bye" with no arguments
and a return type of "Foo".
 
S

Stuart Redmann

John said:
Hello,

I would like to know why the first three statements
produce output whereas the last one does not.
Also, should parentheses be included when
constructing such an instance on the heap?
What about on the stack? Why or why not.

Thanks,

JG

--- input code: ------------------------------------

#include <iostream>
class Foo {
public:
Foo() {
std::cout << "hello" << std::endl;
}
private:
int x;
};

int main() {
std::cout << "one" << std::endl;
Foo *foo = new Foo;

Okay, but memory leak.
std::cout << "two" << std::endl;
Foo *bar = new Foo();

Okay, but memory leak.
std::cout << "three" << std::endl;
Foo hello;

Okay.

std::cout << "four" << std::endl;

This syntax means that you define a function bye that takes no arguments
and returns a Foo. In contrast to dynamic creation, you must not supply
an empty pair of parentheses in this case. To avoid confusion, I'd leave
them out when using new, as well.
Foo bye();
}

Source didn't compile because of missing return statement.
----- output: ------------------------------

$ ./hello
one
hello
two
hello
three
hello
four

Regards,
Stuart
 
M

Marcus Kwok

Stuart Redmann said:
Source didn't compile because of missing return statement.

You may be using an old compiler. In the new standard, the return
statement in main() is optional, and will implicitly return 0 IIRC.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top