Jump to content
  • Advertisement
Sign in to follow this  
Akusei

Structure functions?

This topic is 2593 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'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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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.

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!