this
is only available in non-static member functions; they are called on an object, and this
points to that object. createImage()
is a non-member function; it's not called on an object, and so there is no this
pointer.
Presumably, it's supposed to create an image and return a pointer to that. Perhaps you want:
return new Image;
Remember that it's the caller's responsibility to delete
the object once it's no longer needed - there is no garbage collection in C++. You would be wise to study RAII to learn how to automatically manage dynamic objects in C++; in particular, a smart pointer would do the trick here:
std::unique_ptr<Image> createImage() {
return std::unique_ptr<Image>(new Image);
}
In general, you should forget any idioms you learned in Java, since that is a very different language. There are many good books on C++.
You should also avoid global variables, especially for things that logically belong to an instance of a class. It looks very much like IImage *image;
should be a member of Image
rather than a global variable (although perhaps it already is; I can't tell, since you haven't posted the definition of Image
).
UPDATE: you now say that createImage
is a member, and that the class should emulate the Java class you link to. In that case, it should be static
. For a class member, that has roughly the same meaning that it does in Java: it is associated with the class itself, not any particular object. Then the definition needs to qualify the name with Image::
to indicate that it is a member, not a different function declared in the namespace. So you want something like:
class Image {
public:
// some members
static Image * createImage(string); // Add "static" to match the Java class.
// Return a pointer (or a smart pointer)
};
Image * Image::createImage(string) { // Add "Image::" to indicate it's a member
return new Image;
}
// Usage example:
Image * image = Image::createImage("whatever"); // "::" rather than Java's "."
Note that returning Image
rather than Image *
(or a smart pointer) will return a copy of the Image
object, which is (probably) not what you want; that's another big difference from Java, where class objects are always passed by reference(*). Pointers are the closest things that C++ has to Java's object references.
(*) Note to pedants: by "passed by reference", I mean the object itself is not cloned; the object reference is passed by value.