Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

A Brief Word About Structures

Before we dive into writing games with LlamaWorks2D, which is the subject of the next chapter, there's one more topic I'd like to touch on briefly. That topic is structures.

Occasionally you will want to create a class that is so simple that it doesn't seem worth it to write member functions to get and set its values. If that's the case, you should not make it a class. Instead, you should make it a structure.

A structure is almost exactly the same as a class. A structure can have member functions, constructors, destructors, and member data just like classes. It can have public data, private data, public functions, and private functions just the same as a class. The only difference between classes and structures is the default for all class members is private while the default for structures is public.

For example, suppose I define a class like this:

class bitmap_region
{
    int top,left,bottom,right;
};

This class does not contain the keywords public or private. By default, the four data members are set to private access. That means only member functions can access them. However, there are no member functions. If I change this to a structure, the scope changes as well. Here's the same thing as a structure:

struct bitmap_region
{
    int top,left,bottom,right;
};

As shown here, all structures begin with the keyword struct. This structure does not contain the keywords public or private. By default, its members are public. They can be accessed by any function in the program that has a bitmap_ region variable.

In general, you should not use many structures in your program because their members are public by default. Whenever you can, it's better to use classes that keep their data private and their functions public.

  • + Share This
  • 🔖 Save To Your Account