Sign in to follow this  
Sir Sapo

Functions in structs?

Recommended Posts

In C, no. In C++, yes. You would do it like this (assuming C++):

// In the header
struct SomeStruct {
int x, y, z;

void someFunction();
};

// In the source file
void SomeStruct::someFunction() {
// Code for someFunction...
}

Share this post


Link to post
Share on other sites
Can I define the function inside the typedef, like this:

struct SomeStruct {

int x, y, z;



void SomeStruct::someFunction()
{
x++;
y++;
x++;
}

};

Share this post


Link to post
Share on other sites
Quote:
Original post by Sir Sapo
Can I define the function inside the typedef, like this:

struct SomeStruct {

int x, y, z;



void SomeStruct::someFunction()
{
x++;
y++;
x++;
}

};


Not quite. You would do it like this:


struct SomeStruct {
int x, y, z;

void someFunction() // No leading SomeStruct::
{
x++;
y++;
x++;
}
};

Share this post


Link to post
Share on other sites
Quote:
Original post by Roboguy
Quote:
Original post by Sir Sapo
Can I define the function inside the typedef, like this:

struct SomeStruct {

int x, y, z;



void SomeStruct::someFunction()
{
x++;
y++;
x++;
}

};


Not quite. You would do it like this:


struct SomeStruct {
int x, y, z;

void someFunction() // No leading SomeStruct::
{
x++;
y++;
x++;
}
};


You can have the leading SomeStruct:: if you wish (at least it compiles on my version of MSVC, which doesn't say much). It isn't required, because it is implied that it is part of the struct because it is encapsulated in the struct.

Share this post


Link to post
Share on other sites
Quote:
Original post by Roboguy
In C, no. In C++, yes. You would do it like this (assuming C++):

// In the header
struct SomeStruct {
int x, y, z;

void someFunction();
};

// In the source file
void SomeStruct::someFunction() {
// Code for someFunction...
}


You can have functions in structs in a C but you have to use a function pointer
and set it.


struct Foo
{
void (*func)(void);
};


If you don't initialize func it will crash... but this is the foundation of OO
in C++ too, but C++ does the linking work for you and passes the this pointer for you. In C you have to pass the 'this' pointer manually:


struct FOO
{
void (*foo)(struct FOO * this, ... );
};


So clearly C++ is a much nicer solution. But in the old old days this is how C++ even worked, the C-Front compiler would translate C++ directly to C like this. Now we have real C++ compilers.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this