Public Group

# Structure functions?

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

## Recommended Posts

I've seen a couple articles use structures kind of like classes. I understand putting a struct constructor but I'm a little confused as to why or even if this is good practice:

[source lang="cpp"]
struct test
{
enum { value1, value2 };
};

struct test2
{
void operator ()(something *obj)
{
//do something here
}
};

struct test3
{
void function1()
{
//do something
}
};
[/source]

I've even seen stuff like this

[source lang="cpp"]
template<>
struct get_id<CClass>
{
enum { id=30 };
};

template<>
struct get_class<30>
{
typedef CClass type;
};
[/source]

Is this all ok to do? Is there a really good reason to do this? I guess I just don't understand why this would be done and not put inside a class.

##### Share on other sites
To be honest with you, structs and classes are exactly the same thing, except that classes default to private access, whereas structs default to public access. Aside from that minor detail, they're the same, according to the C++ standard.

Classes are typically used for larger objects with member functions, whereas structs are typically used for PODs. But that is not enforced in C++ (nor is it really specifically encouraged by the C++ standard either, as the C++ standard doesn't really care). It's just kind how things have evolved in the programming world.

So doing
struct { private: // blah blah blah... };
Is exactly the same as doing
class { // blah blah blah... };

And doing
class { public: // blah blah blah... };
Is exactly the same as
struct { // blah blah blah... };

So to answer your question, there isn't anything inherently wrong with doing that. There isn't really a good, strict reason either, AFAIK. It's just a programming style.

##### Share on other sites
First, is this code C or C++. In C, structs were the old classes. If this is C++ code, generally a struct is used strictly for data with as you suggested, no functions etc. A constructor may still be used though, always a good idea to initialize.

##### Share on other sites

First, is this code C or C++.

It's obviously C++, as many of the features illustrated are not available in C.

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 16
• 15
• 9
• 11
• 15