Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

assign a base class to a derived class

1 view
Skip to first unread message

Mitja Semolic

unread,
Dec 8, 2003, 9:52:49 AM12/8/03
to
Could I get a comment how to assign a base object to a derived object?
Thanks, Mitja Semolic

public class B : A
{
public B: base()
{}

static void main()
{
// throws an exception 'System.InvalidCastException'
B derived = (B) new A();
}
}


Codemonkey

unread,
Dec 8, 2003, 10:13:56 AM12/8/03
to
You cannot assign a base class instance to a derived class variable unless
the instance is the derived type.

A derived type is a superset of the base type. If you try to assign the only
the base type (which is a subset of the derived type) to a superset
variable, then you'll get an error. Suppose you had a base class called
Person (Name, Age etc.) and a derived class called Employee (All of Person,
Employee No etc.). If you only create a person object, no space has been
allocated for the extra stuff needed by an Employee class, so you cannot
assign

For example:

Assume MyClassB inherits from MyClassA

The following will work:
MyClassB myVariableB = New MyClassB();
MyClassA myVariableA = (MyClassA) myVariableB;

The following is won't work:
MyClassA myVariableA = New MyClassA();
MyClassB myVariableB = (MyClassB) myVariableA;

The following will work because myVariableA is actually of type MyClassB:
MyClassA myVariableA = (MyClassA) New MyClassB();
MyClassB myVariableB = (MyClassB) myVariableA;


Sorry for sounding more complicated than this is. Someone else can hopefully
provide a better explanation of how inheritance works.

For your code to work, you'd need to do something like:

public class B : A
{
public B: base()
{}

static void main()
{
B derived = (B) new B();
}
}

Hope this helps,

Trev.

"Mitja Semolic" <mit...@hotmail.com> wrote in message
news:Ae0Bb.6425$2B6.1...@news.siol.net...

0 new messages