Page 1 of 1
What's rong with this code
Posted: Fri May 13, 2005 11:20 pm
by B.E
I wanted to test the contractor using the following code
class Test
{ public:
Test(int y) {}
};
int main()
{ int x;
Test(x);
}
Why does it not work?
Re:What's rong with this code
Posted: Sat May 14, 2005 12:58 am
by AR
Probably because you aren't calling a constructor, merely a non-existant function called Test()
Code: Select all
class Test
{
public:
Test(int y)
{
cout << y;
}
};
int main()
{
Test *t = new Test(36);
delete t;
return 0;
}
Re:What's rong with this code
Posted: Sat May 14, 2005 1:08 am
by B.E
but why doesen't the other code work. it's called the with the requied params for the constructor
Re:What's rong with this code
Posted: Sat May 14, 2005 1:13 am
by Colonel Kernel
This is probably an example of C++'s "most vexing parse" (named so by Scott Meyers in Effective STL).
http://archives.devshed.com/a/ng/468-18 ... -operators
BTW #1, new and delete aren't necessary to make this work (if you're looking for the shortest version):
Code: Select all
int main()
{
Test t(36);
return 0;
}
BTW #2, it would help if you define "not working" better next time. You did mean you got a compile error, right?
Re:What's rong with this code
Posted: Sat May 14, 2005 12:32 pm
by Candy
B.E wrote:
I wanted to test the contractor using the following code
class Test
{ public:
Test(int y) {}
};
int main()
{ int x;
Test(x);
}
Why does it not work?
It doesn't work since you don't give the object a name.
Code: Select all
class Test
{ public:
Test(int y) {}
};
int main()
{ int x;
Test n(x);
}
will work.
Re:What's rong with this code
Posted: Sat May 14, 2005 5:04 pm
by B.E
But why does
Test ((int) x); work?
x is raady an int.
Re:What's rong with this code
Posted: Sat May 14, 2005 10:59 pm
by Colonel Kernel
Because it's the "most vexing parse". The compiler is getting confused about whether you're declaring an object instance or declaring a local function. The cast disambiguates it.