Question regarding initializing base class object to derived class object,

A

archana

Hi all,

I am confuse in concept of inheritance. I am having following 2
classes
class base1
{
public void abc()
{
System.Console.WriteLine("base1 abc");
}
public void pqr()
{
System.Console.WriteLine("base1 pqr");
}

public void xyz()
{
System.Console.WriteLine("base1 xyz");
}
}

class derived1 : base1
{
public void abc()
{
System.Console.WriteLine("derived1 abc");
}

public void pqr()
{
System.Console.WriteLine("derived1 pqr");
}

public void xyz()
{
System.Console.WriteLine("derived1 xyz");
}

}

so when i am having code like following
base1 c = new derived1();
c.abc();c.pqr();c.xyz();

Here what exactly happen. Will object of derived class gets created and
its reference gets stored into c? If yes, then if my derived class has
more mothod will those also get initialize and can i access those
methods of derived class through base class object?

Please correct me if i am wrong.

thanks in advance
 
M

Marc Gravell

Will object of derived class gets created and
its reference gets stored into c?

Yes; however, c is typed as base1, so only the base1 methods will be
directly callable unless you cast into derived1 [this does not change
the actual object in any way].
If yes, then if my derived class has
more mothod will those also get initialize and can i access those
methods of derived class through base class object?

Methods aren't really initialised; objects are. If you mean
*additional* methods (generally new names), then they will not be
visible without casting. For methods of the same name (and signature)
there are two scenarios:
1 (polymoprphism): the base method can be marked as "virtual" allowing
the derived method to declare itself as "override"; there is then only
1 method, and "which is called" is determined by the object type -
i.e. it doesn't matter if you have a variable typed as base1 or
derived1: the "most recent" (if you see what I mean) override will be
called. This is the most common variant.

2: the derived method can be marked as "new"; this creates a
*duplicate* method of the same name on the object; "which is called"
is determined by the variable type; if the variable is typed as base1,
then the original version (or most recent override) is invoked. If the
variable is typed as derived1, then the newly declared version is
invoked. This is primarily used to make a method more specific, e.g.
to make a return type more context-appropriate (i.e. "SomeType"
instead of "object") while allowing callers who only know about base1
to work "as was".

Marc
 

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

Top