The Mask
The Mask

Reputation: 17427

Can a struct member(function) be defined before struct itself?

I'm new to C++, and I have a question: Can a member of struct that's a function, be defined before the struct itself?

Like this:

void foo_t::SayHello() {
    printf("Hello,World!\n");
}

struct foo_t {
    void SayHello();
};

Because by using this I split struct in a foo.h and SayHello() function in a C file.

EDIT:: And then include the .c in the top of .h file. Not in end of file.

I'm sorry for don't be more specific because I new to C++ and I don't know about C++'s terms.

Upvotes: 0

Views: 130

Answers (2)

user2249683
user2249683

Reputation:

No. (Point)

But you might do:

class foo_t;
void say_hello(const foo_t& foo) // defined in a source
struct foo_t {
    void SayHello() const { say_hello(*this); }
};

But: "And then include the .c in the top of .h file. Not in end of file." makes me shiver.

Upvotes: 2

orlp
orlp

Reputation: 117681

No, but you can make a function proxy:

void foo_t_SayHello() {
    printf("Hello,World!\n");
}

struct foo_t {
    void SayHello() { foo_t_SayHello(); }
};

A decent compiler will inline this, resulting in no overhead.

Upvotes: 1

Related Questions