Reputation: 251
Why GCC 4.7 complains when instantiate a class inside a function (with a pointer)?
Bad:
#include "foo.h"
int fn () {
Foo *foo;
foo->method();
return 0;
}
main.cpp: In member function 'int foo()': main.cpp:21:52: warning: 'fn' may be used uninitialized in this function [-Wuninitialized]
Good:
#include "foo.h"
Foo *foo;
int fn () {
foo->method();
return 0;
}
Good:
#include "foo.h"
int fn () {
Foo foo;
foo.method();
return 0;
}
Upvotes: 5
Views: 9245
Reputation: 78343
The first (bad) one, foo is pointing to a garbage pointer. You could remove the warning by initializing it like Foo* foo = NULL;
but then you'd get an error when you tried to dereference it (runtime error).
The second (good) one doesn't complain because C automatically initializes variables in the translation unit scope to NULL or 0 or the appropriate equivalent if they're not already initialized.
The last (good) one doesn't complain because you are calling a method on the object and the assignment of the function pointer is done by the compiler, similar but not the same as number 2. So the compiler already knows the address of the method method
and has assigned that address to the appropriate location on the Foo
struct.
Upvotes: 5
Reputation: 2777
because, just as the warning says, it's uninitialized. there's no object yet. actually the value of foo in your first example is undefined. it will have the value that resides in the memory where foo lives.
to clarify, foo (which you see as a Foo*) is actually an int. the value of the int is supposed to be the address to an object of type Foo. to make it such, you have to assign it the address of a foo. one of doing this is to instantiate it with new:
Foo* foo = new Foo;
new
returns the address where the new Foo object was created. this will remove your warning :)
Upvotes: 2
Reputation: 41617
In your bad example foo
is a local variable with pointer type, which is not initialized automatically. The class Foo
, in your correct example, is initialized using the default constructor.
Your first »good« example initializes the pointer with 0
, because foo
is a global variable. It will result in undefined behavior at runtime, since foo
does not point to an object.
Upvotes: 2
Reputation: 131789
Foo* foo; foo->method()
is never good. foo
is an uninitialized pointer that potentially points to garbage and as such your code exhibits undefined behaviour. The best you can hope for is that the compiler warns or errors out on you. If not that, then atleast hope that the running programm crashes.
Upvotes: 2
Reputation: 11976
There's a difference between Foo * foo;
and Foo foo;
The first declares a pointer to a Foo, the second declares & invokes the default-constructor of a Foo.
EDIT: Maybe you meant to write Foo * foo= new Foo();
, in order to allocate a Foo
on the heap which can outlive the function call.
Upvotes: 6