Member functions inside structure blocks?

J

james545

I saw some code written where member functions were written inside
struct definition blocks and was wondering if this is an advisable or
common style of programming in C/C++?
The type of code I saw compiled under the g++ compiler and looked like
this:

typedef struct A
{
int x;
int y;

A(int, int);
~A();
} a;

....

A::A(int q1, int q2)
{...}

A::~A()
{...}
 
V

Victor Bazarov

I saw some code written where member functions were written inside
struct definition blocks and was wondering if this is an advisable or
common style of programming in C/C++?

It depends.
The type of code I saw compiled under the g++ compiler and looked like
this:

typedef struct A
{
int x;
int y;

A(int, int);
~A();
} a;

This is not A GOOD IDEA(tm). What's the typedef for? Do you really need
the 'a' alias for the 'A' struct?

I suppose here in the '...' lies the boundary between the header file and
the compilation unit.
A::A(int q1, int q2)
{...}

A::~A()
{...}

Both methods (defining member functions inside the class definition or in
a separate translation unit) are acceptable and get used intermittently by
all C++ programmers, AFAICT.

If you like them separate (which improves the readability of the class
definition, IMO), but still want the member definitions to be in the same
header file as the class definition, the functions should [usually] be
declared 'inline' when defining them.

V
 
J

Jack Klein

I saw some code written where member functions were written inside
struct definition blocks and was wondering if this is an advisable or
common style of programming in C/C++?
The type of code I saw compiled under the g++ compiler and looked like
this:

typedef struct A
{
int x;
int y;

A(int, int);
~A();
} a;

...

A::A(int q1, int q2)
{...}

A::~A()
{...}

There is no such language as "C/C++", and your post is proof of it.
This code is legal, but of doubtful use in C++. It is totally illegal
in C.
 
J

Jaspreet

Hi

Is there really any use of the typedef ? Not sure.

This practice of putting functions inside a struct definition is valid
in C++ but illegal in C.

Just remember though in a class the default access specifier is private
while in a structure it is public.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top