What's rong with this code

Programming, for all ages and all languages.
Post Reply
B.E

What's rong with this code

Post 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?
AR

Re:What's rong with this code

Post 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;
}
B.E

Re:What's rong with this code

Post by B.E »

but why doesen't the other code work. it's called the with the requied params for the constructor
User avatar
Colonel Kernel
Member
Member
Posts: 1437
Joined: Tue Oct 17, 2006 6:06 pm
Location: Vancouver, BC, Canada
Contact:

Re:What's rong with this code

Post 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?
Top three reasons why my OS project died:
  1. Too much overtime at work
  2. Got married
  3. My brain got stuck in an infinite loop while trying to design the memory manager
Don't let this happen to you!
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:What's rong with this code

Post 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.
B.E

Re:What's rong with this code

Post by B.E »

But why does
Test ((int) x); work?
x is raady an int.
User avatar
Colonel Kernel
Member
Member
Posts: 1437
Joined: Tue Oct 17, 2006 6:06 pm
Location: Vancouver, BC, Canada
Contact:

Re:What's rong with this code

Post 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.
Top three reasons why my OS project died:
  1. Too much overtime at work
  2. Got married
  3. My brain got stuck in an infinite loop while trying to design the memory manager
Don't let this happen to you!
Post Reply