I have a question about the following code in C++:
typedef struct {
int id;
int age;
} Group1;
typedef struct {
int id;
char name;
float time;
} Group2;
typedef union {
Group1 group1;
Group2 group2;
} ServiceData;
typedef struct {
ServiceData data;
} Time;
Then I have a variable:
Group1 * group1;
group1 = new Group1;
group1->id = 10;
group1->age = 20;
Then there are two methods defined like this:
void method1(ServiceData * data) {
//inside the method call method hello
hello(data);
};
void hello(Group1 *group1) {
printf("%d",group1->id);
}
I call method1 like this:
method1((ServiceData *)group1);
But inside method1, when the parameter group1 is passed to method hello(), I want to get the value of id inside of group1. Do I need to do any cast in hello method? Or inside of method1, do I need to cast it to (group*) before I pass it to hello()?
You don’t need a cast, just to access the correct field in the
union: