Jump to content
  • Advertisement
Sign in to follow this  
Nanook

structs vs class

This topic is 3253 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

When to use struct and when to use a class? I thought for a while that structs couldnt have methods, but I've realized aftr reading some articles that they can.. or is it just the operator that you can have? Like in the example below:
    struct Vector
    {
         float x,y,z;

         Vector operator+(const Vector &other)
         {
              Vector result;
              result.x = x + other.x;
              result.y = y + other.y;
              result.z = z + other.z;
              return result;
         }

         Vector operator*(float scalar)
         {
              Vector result;
              result.x = x * scalar;
              result.y = y * scalar;
              result.z = z * scalar;
              return result;
         }
    };

Share this post


Link to post
Share on other sites
Advertisement
The only difference in C++ between struct and class is that by default struct members(functions and variables) are public, and by default class members are private.

A decent guide is that if you have any private member variables, use a class. struct generally implies to the programmer: "oh here's a thing where I'm responsible for managing the state of it's variables because it won't do that itself"

-me

Share this post


Link to post
Share on other sites
In C++ there are no differences between structures and classes except that:
1. A structure inherits from it's base publicly by default, whereas a class inherits privately by default

struct Derived : Base { // equivalent to class Derived : public Base

2. A structure's members are public by default, whereas a class's members are private by default

struct Something {
int i;
};
// equivalent to:
class Something {
public:
int i;
};

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!