Connecting Tech Pros Worldwide Forums | Help | Site Map

How to define variable with polymorphism like this? Doable?

well_doing@yahoo.com
Guest
 
Posts: n/a
#1: Oct 31 '07
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;
...
}


Jim Langston
Guest
 
Posts: n/a
#2: Oct 31 '07

re: How to define variable with polymorphism like this? Doable?


<well_doing@yahoo.comwrote in message
news:1193845462.482762.238270@y42g2000hsy.googlegr oups.com...
Quote:
>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.


newstar
Guest
 
Posts: n/a
#3: Oct 31 '07

re: How to define variable with polymorphism like this? Doable?


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.

Jim Langston
Guest
 
Posts: n/a
#4: Oct 31 '07

re: How to define variable with polymorphism like this? Doable?


"newstar" <well_doing@yahoo.comwrote in message
news:1193846640.889604.191260@z9g2000hsf.googlegro ups.com...
Quote:
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.


Closed Thread