I must admit that I'm completely new to C++, but I'm used to Java and somewhat C, so I don't consider myself to be completely in the middle of nowhere.
Anyway, the problem is that I have an class that I would like to use in several classes, some places as a return type, other places to create an object of that type. But I keep getting new errors every time I fix an old one, and I've been looking on the internet on how to fix this and that error, and have finally given up, and decided to come here and beg for help.
My class is as simple as it gets. Since I want to fix this problem first, the class contains no attributes or functions. All I have is this:
Image.h:
class Image
{
};
Now, what I want to do is to be able to use this in more than just one class. Hence, I #include Image.h everywhere I need to use the Image object. But I get a "redefinition of 'class Image'" error.
Fair enough, I read up on it, and find out that I need to add some defines (I don't recall what they're called). So I change my header like this:
Image.h:
#ifndef IMAGE_H
#define IMAGE_H
class Image
{
};
#endif
Now I get the error "'Image' does not name a type". Again I read up on this error, and find out that I need to add a forward declaration of my class. From what I can figure out, this is because once IMAGE_H has been defined, it skips that entire section in the other files that have included Image.h, and so those other files do not know that the class exists. So I change my code like this:
Image.h:
class Image;
#ifndef IMAGE_H
#define IMAGE_H
class Image
{
};
#endif
Now I think everything is good. But no. Now I get the error "variable 'Image img has initializer but incomplete type". This error occurs in one of those files where I try to assign an Image object by using a method to return one.
Then I think that maybe I just need to move the defines to after the class, i.e. inside the curly brackets. Like this:
Image.h:
class Image;
class Image
{
#ifndef IMAGE_H
#define IMAGE_H
#endif
};
Then of course, I get the redefinition error. And this is where I throw in the towel. I have looked in books, and online, I have found examples that use headers, that use objects, but I have not been able to find an example that use the same object in multiple classes. And the books and sites I have seen that use headers, do it this way. So I'm at a loss for what I'm doing wrong here.


Sign In
Create Account


Back to top









