Sign in to follow this  
Hop chewer

How does this work?

Recommended Posts

I have the following header file:
#ifndef DISPLAY_H
#define DISPLAY_H

struct SDL_Surface;

//initialize SDL
void SDL_init();
//exit SDL
void SDL_exit();
//load files
void load_files();
//load the image
SDL_Surface *load_image(const char *filename);


If I have struct SDL_Surface; or class SDL_Surface; at the top, every thing compiles fine. If I remove:struct SDL_Surface; or class SDL_Surface; I get the following errors: g++ -O2 -Wall -Werror -ansi -c -o main.o main.cpp g++ -O2 -Wall -Werror -ansi -c -o display.o display.cpp In file included from display.cpp:1: display.h:13: error: expected constructor, destructor, or type conversion before ‘*’ token display.cpp: In function ‘void load_files()’: display.cpp:34: error: ‘load_image’ was not declared in this scope make: *** [display.o] Error 1 I don't understand what struct SDL_Surface; or class SDL_Surface; is doing. I know it works since I have used it but I don't know why. And why class as opposed to struct? Since SDL is written in C, I would think that class wouldn't apply.

Share this post

Link to post
Share on other sites
It's called a forward declaration. Simply put, you tell the compiler that a struct SDL_Surface is defined somewhere. Since you only use say that load_image returns a pointer to a SDL_Surface the compiler doesn't need to know more than that. However, when you want to use the SDL_Surface you need to include SDL.h where it's defined. Check this link for more information.

Share this post

Link to post
Share on other sites
In C++, class and struct are fairly similar. The differences are that members start as public in a struct and private in a class, and structs default to public inheritance and classes to private inheritance.

What you are doing is telling the compiler of the existence of a type called "SDL_Surface". This is a forward declaration. Remember, C++ is fairly pedantic about declaring everything in advance. After all, the purpose of the header file you are writing is to declare a set of functions that you want to use in multiple files.

There are limited things you can do with a forward declared types. You can alternatively include "SDL.h" rather than forward declaring such types.

Finally, I would advise against using the "SDL_" prefix for your own functions.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this