Is this a 'type variableofType ()' function or object?

#include<iostream> class name { public: int a; name():a(0){}; }; void add(name * pname) { pname = NULL; } int main() { name varName(); name * pName = new name(); add(pName); add(&varName);//error C2664: 'add' : cannot convert parameter 1 from 'name __cdecl *)(void)' to 'name *' } 
+4
source share
4 answers

I think it's worth telling you about a similar problem that also causes problems:

 struct foo { }; struct bar { bar(foo f); }; int main() { // does *not* create a bar object initialized by a default constructed // foo object. bar b(foo()); } 

Actually, this is a function that returns bar and takes as its first argument a pointer to a function that returns foo without arguments. This is the same as:

 bar b(foo(*)()); 

If you want to create a bar object initialized with the default built foo, put parentheses around the argument. This makes it no longer look like a function declaration, and the compiler will interpret it the way you want:

 bar b((foo())); 

There are also no obvious cases where a compiler error should be raised. GCC is wrong, but Como is recovering again. Consider the following snippet

 struct foo { static bool const value = false; }; int main() { int v(int(foo::value)); } 

You probably expect this to take a static constant and discard it to int , initializing the variable v to 0 ? No, this will not conform to the standard, because the initializer can be interpreted as a declaration according to purely parsing, as shown below:

 struct foo { static int value; }; // valid, parentheses are redundant! Defines `foo::value`. int (foo::value); 

Whenever an initializer can be interpreted as a declaration, in such a situation the whole declaration will declare a function. So, the line in main declares the next function, omitting the extra and meaningless parentheses

 int v(int foo::value); 

And this will cause a compiler error when parsing a function declaration, since the function parameter name may not be qualified.

+8
source

The error is in the first line of the main function:

 name varName(); 

You are not creating an instance of the class name using the default constructor, you are actually declaring a new varName function with no parameters, which returns an instance of the name.

Instead, you should write:

 name varName; 
+22
source

It's also worth noting that your add () function has no lasting effects - all it does is assign a pname value, which is a copy of the pointer you pass into it. If you want to actually have this destination binding, you will need to pass the pointer by reference as "name * & pname".

+1
source
 name varName(); 

interpreted as a declaration of a local function. To call the default constructor, use

 name varName; 

instead of this. Most unpleasant, yes.

0
source

All Articles