Why does GCC 4.7 complain when creating an instance of a class inside a function (with a pointer)?
Poorly:
#include "foo.h" int fn () { Foo *foo; foo->method(); return 0; }
main.cpp: In the member function 'int foo ()': main.cpp: 21: 52: warning: 'fn', the function uninitialized in this can be used [-Uniminization]
Good:
#include "foo.h" Foo *foo; int fn () { foo->method(); return 0; }
#include "foo.h" int fn () { Foo foo; foo.method(); return 0; }
There is a difference between Foo * foo;and Foo foo;The first declares a pointer to Foo, the second declares and calls the default constructor Foo.
Foo * foo;
Foo foo;
EDIT: Perhaps you wanted to write Foo * foo= new Foo();to allocate Fooon a heap that could survive a function call.
Foo * foo= new Foo();
Foo
(), foo . , Foo* foo = NULL;, ( ).
Foo* foo = NULL;
() , C NULL 0 , .
() , , , , , 2. , , method Foo.
method
Foo* foo; foo->method() . foo - , , undefined. , , , . , , .
Foo* foo; foo->method()
foo
foo - , . class Foo .
class Foo
"" 0, foo . undefined , foo .
0
, , . . foo - undefined. , , foo.
, foo ( Foo *) int. int Foo. , foo. , :
Foo* foo = new Foo;
newreturns the address at which the new Foo object was created. this will remove your warning :)
new