how to extend a struct in mingw

hey all.
i'm using g++, and want to extend a struct, like this:

typedef struct _first {
int a1;
} first;

typedef struct _second {
struct _first;
int b1;
} second;

so i can access first members from second, directly, like this:

second.a1 = 1;

this doesn't work for me in g++,
but works well on other compiler (pellesc),
from my memory, i think this is a standard,
so i wonder why it doesn't work in g++.

any idea ?

thanks ahead for any input.
I think you're interested in C++ inheritance.
http://cplusplus.com/doc/tutorial/inheritance/

Let me know if this helps, 'kay?

Fine print: In C++, structs are basically classes with public as their default access level.

-Albatross
Last edited on
In C++ you don't need all that typedef nonsense. You can just write
1
2
3
4
5
6
7
8
struct first {
	int a1;
};

struct second {
	struct first;
	int b1;
};


struct first; This doesn't really do anything. It's just a forward declaration of first.

When you say extend, do you mean that you want second to inherit from first? In that case you can write
1
2
3
4
5
6
7
struct first {
	int a1;
};

struct second : public first{
	int b1;
};

Last edited on
First of all you incorrectly defined struct second. Instead of

typedef struct _second {
struct _first;
int b1;
} second;

shall be like this

typedef struct _second {
first a1;
int b1;
} second;

Then you must create an object of type struct second and use its name to access members. For example

second s;

s.a1.a1 = 1;
vlad -1:
No code brackets.
vlad -1:
Bad code.
It depends on what you want, by your example output it looks like you want an "Is A" relationship.

"Is a" relationship:
1
2
3
4
5
6
7
8
9
10
11
struct First{
  int a1;
};

struct Second : public First{
  int b1;
};

//First is accessed like this...
Second obj;
obj.a1;  //This is an "Is a" relationship 


"Has a" relationship:
1
2
3
4
5
6
7
8
9
10
11
12
struct First{
  int a1;
};

struct Second{
  First first;
  int b1;
};

//First is accessed like this...
Second obj;
obj.first.a1;  //This is a "Has A" relationship 




Last edited on
thank you all.

the best i would like to know,
is how to inherit, for both compilers C/C++,
i'm quiet sure this is possible, since this is a standard C syntax,
which C++ should support.

anyway, if for some reason this is impossible,
then i can solve it with conditional compliation.

i didn't check your replies yet, so i let you know, later.

thank you very much
closed account (o1vk4iN6)
You'd best choose either C or C++, if you program in C than it'll work for C++ compilers as well, which would be pointless as you have C compilers.
Last edited on
no, i have both, and i need the same code to work on both, but it doesn't with G++.
the code is standard ANSI (i think), so the problem is with G++, not with my code,
since it compiles well with C Compiler.

(you can see my code in the first post)


Topic archived. No new replies allowed.