Advertisement

C++ quirk, let's see if you get it...

Started by December 13, 2000 01:39 PM
11 comments, last by felisandria 24 years, 1 month ago
To be honest I''m not sure why he was doing it... we''re kind of in a crunch time so I didn''t have time to look at or play with it. He''s doing heirarchical data sets so it''s probably something to do with that. Without the () it works fine, with the () it dies horribly.

-fel
~ The opinions stated by this individual are the opinions of this individual and not the opinions of her company, any organization she might be part of, her parrot, or anyone else. ~
quote:

I also tried it without pointers:
Type t1;
Type t2 ();

The second line isn't executed, but it doesn't give an error. However, if you try to do t2.any_member (), it doesn't recognize t2 as a Type.

So from this, I take it that the type for a pointer to the constructor for a class is the class name itself? Weird.



Actually it's not that wired, if you use some different names you should be able to see what's going on a little better:

int n;
int function();

The second line doesn't default construct an int, it's a forward declaration for a function. Somewhere in the C++ standard it says something like 'if something can be parsed as a function declaration, it is a function declaration'.

It makes sense in most cases, but sometimes it gets a little bit silly. e.g.

SomeClass type(int(float1), int(float2));

This might look like a call to a construction passing in two int values using function style casting, but it's actually a declaration of a function 'type' returning SomeClass and taking two ints as parameters. The extra () are ignored and it's parsed the same as:

SomeClass type(int float1, int float2);

Edited by - Wilka on December 13, 2000 7:08:37 PM
Advertisement
quote:
Original post by felisandria

Aww, only one person even cares? hehe.

The difference is that
Type *y = new Type;
returns a pointer to a Type object, whereas, in MSVC at least,
Type *y = new Type();
returns a function pointer to the constructor of a Type object. Now, while these resolve to the same thing at the end of the constructor, if you attempt to do recursion inside the constructor (which would be how we found it) you''re in deep trouble if you use Type *y = new Type();
So, only use ()''s when doing news if you''re calling something other than the default constructor.

-fel


Let me try get this straight.

Type *y = new Type(); returns a pointer to the constructor.

Does that mean the y will then not be of object Type but will be a function(constructor)? I''m confused...
==========================================In a team, you either lead, follow or GET OUT OF THE WAY.

This topic is closed to new replies.

Advertisement