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?
What's rong with this code
Re:What's rong with this code
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
but why doesen't the other code work. it's called the with the requied params for the constructor
- Colonel Kernel
- Member
- Posts: 1437
- Joined: Tue Oct 17, 2006 6:06 pm
- Location: Vancouver, BC, Canada
- Contact:
Re:What's rong with this code
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):
BTW #2, it would help if you define "not working" better next time. You did mean you got a compile error, right?
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;
}
Top three reasons why my OS project died:
- Too much overtime at work
- Got married
- My brain got stuck in an infinite loop while trying to design the memory manager
Re:What's rong with this code
It doesn't work since you don't give the object a name.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?
Code: Select all
class Test
{ public:
Test(int y) {}
};
int main()
{ int x;
Test n(x);
}
- Colonel Kernel
- Member
- Posts: 1437
- Joined: Tue Oct 17, 2006 6:06 pm
- Location: Vancouver, BC, Canada
- Contact:
Re:What's rong with this code
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.
Top three reasons why my OS project died:
- Too much overtime at work
- Got married
- My brain got stuck in an infinite loop while trying to design the memory manager