assign a base class to a derived class

M

Mitja Semolic

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();
}
}
 
C

Codemonkey

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.
 

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,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top