about inheritance

  • Thread starter Thread starter e-mid
  • Start date Start date
E

e-mid

i have a class, lets say myclass and 2 derived classes(derived1, derived2)
from myclass. i do the following:

myclass a;

then i will instantiate according to user choice.

a = new derived1( );

or

a = new derived2( );

but i can not reach the members of derived1 or derived2 using the object a.

what should i do?
 
Hi e-mid,

No, you need to cast a to (derived1) or (derived2) depending on which one you want to use. 'a' will only have access to myclass members.

If derived1 has a method call Method1(), and derived2 has a method called Method2()


myclass a = new derived1();

derived1 d = (derived1)a;
d.Method1();

or just

((derived1)a).Method1();

derived d = (derived2)a; // CRASH and BURN, since a is derived1.

Depending on what you are actually trying to do, you might want to consider an interface instead of common inheritance.
 
e-mid said:
i have a class, lets say myclass and 2 derived classes(derived1, derived2)
from myclass. i do the following:

myclass a;

then i will instantiate according to user choice.

a = new derived1( );

or

a = new derived2( );

but i can not reach the members of derived1 or derived2 using the object a.

what should i do?

You can cast a to derived1 or derived2, and you need to do that before
accessing the members specific to those derived classes.
 
thnkz Morten, you helped alot today.

i didnt used interfaces before, i should do some practice with them.

thnkz again


Morten Wennevik said:
Hi e-mid,

No, you need to cast a to (derived1) or (derived2) depending on which one
you want to use. 'a' will only have access to myclass members.
If derived1 has a method call Method1(), and derived2 has a method called Method2()


myclass a = new derived1();

derived1 d = (derived1)a;
d.Method1();

or just

((derived1)a).Method1();

derived d = (derived2)a; // CRASH and BURN, since a is derived1.

Depending on what you are actually trying to do, you might want to
consider an interface instead of common inheritance.
 
Back
Top