How to define variable with polymorphism like this? Doable?

W

well_doing

I have something like this in declaration.

union allInOne{
struct simple_s {
int a;
int b;
} s;
struct complex_s {
int a;
int b;
int rec[10];
} c;
} *p;

In my code, how to implement something like this,

if ( condition A ) {
struct simple_s *ptr = &p->s;
} else {
struct complex_s *ptr = &p->c;
}

ptr->a = 0;
ptr->b = 1;
if ( !condition A) {
ptr->rec[1] = 1;
...
}
 
J

Jim Langston

I have something like this in declaration.

union allInOne{
struct simple_s {
int a;
int b;
} s;
struct complex_s {
int a;
int b;
int rec[10];
} c;
} *p;

In my code, how to implement something like this,

if ( condition A ) {
struct simple_s *ptr = &p->s;
} else {
struct complex_s *ptr = &p->c;
}

ptr->a = 0;
ptr->b = 1;
if ( !condition A) {
ptr->rec[1] = 1;
...
}

I see no need any of this in the code you supplied. From what I see of the
structure you will have two int, a and b and an optional array of 10 ints.
In this case, either of the a or b should take the same offset into the
union. So why can't you simply do:

struct allInOne {
int a;
int b;
rec[10];
};

and only use the rec array if !condition A

Perhaps if you explain what you are trying to achieve a good algorithm could
be shown.
 
N

newstar

The actual structures are a lot more complicated and like in the
example above, I don't want to use the rec[] in error when it is under
Condition A. Simply to be error proof in this regard.
 
J

Jim Langston

newstar said:
The actual structures are a lot more complicated and like in the
example above, I don't want to use the rec[] in error when it is under
Condition A. Simply to be error proof in this regard.

Your stucture/class should probably then keep track of what type it is and
then you can encapsulate the data and only allow access to the rec[] if it
is the correct type.

Or you could go with polymorphism but most likely you would have to check
the result of dynamic_cast being null to see what type it is.

Polymorphism is usually used, I think, for this.
 

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

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top