Invoking constructor : Foo(var) and Foo ins(var)

A

Alex Vinokur

Hi,

What is wrong with this code?

====== C++ code : File t.cpp : BEGIN ======
#include <iostream>
using namespace std;

struct Foo
{
Foo (int n) { cout << n << endl; }
};

int main ()
{
int i = 100; // Line#11

Foo (i); // Line#13 : Compilation error
Foo f (i); // Compiled with no errors

Foo (200); // Compiled with no errors
Foo (int(300)); // Compiled with no errors

return 0;
}
====== C++ code : File t.cpp : END ========


====== Compilation : BEGIN ======

$ g++ -v
[--omitted--]
gcc version 3.3.1 (cygming special)

$ g++ t.cpp

t.cpp: In function `int main()':
t.cpp:13: error: conflicting types for `Foo i'
t.cpp:11: error: previous declaration as `int i'

====== Compilation : END ========


=====================================
Alex Vinokur
mailto:[email protected]
http://mathforum.org/library/view/10978.html
=====================================
 
A

Avinash

Alex,
Foo(i ) means 'i' is declared a variable of type Foo.
but 'i' is already defined and C++ do now allow redeclaration.

Thanks
Avinash
 
K

Karl Heinz Buchegger

Avinash said:
Alex,
Foo(i ) means 'i' is declared a variable of type Foo.


No it doe not.
It means to create an unnamed temporary object, initialize it with i
and destroy it afterwards.
 
J

jeffc

Karl Heinz Buchegger said:
No it doe not.
It means to create an unnamed temporary object, initialize it with i
and destroy it afterwards.

That doesn't help the OP with his compiler error msg.
 
R

Ron Natalie

Karl Heinz Buchegger said:
No it doe not.
It means to create an unnamed temporary object, initialize it with i
and destroy it afterwards.

No actually, Avinash is right. Syntactically this is ambiguous between
being a declaration (Avinash) and an expression (Karl). The semantic
rules say the declaration wins out. Foo (i) is the same as Foo i in this
case.
 

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

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top