Jump to content
  • Advertisement
Sign in to follow this  

How does this work?

This topic is 3306 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!