C# .NET - OOPS - Asked By Krishna Madhu on 05-Mar-13 11:53 AM

class a
{

  public int var1;
  private string var2;
  protected decimal var3;
}
class b:a

{
    var1=10;
  var2;//Inherited but not  accessible.
   var3= 199.25;
 
}

a= new class b();---> Reference variable of class a is been given an object of class b .(Allowed)

Here i can access the parent class members but cannot access the child class members even though the object given is child class. why?

However in the above inheritance we get all all the members inherited in child class but private is not accessible. why cant this be possible in the case of

a= new class b();

b= new class a();---> Reference variable of class b is been given an object of class a .(Not allowed).--As a child class reference variable cannot refer to a parent class object.

Robbe Morris replied to Krishna Madhu on 05-Mar-13 12:44 PM
private means private.  It is not exposed to anything outside of its class.  Inherited or not. 
Krishna Madhu replied to Robbe Morris on 06-Mar-13 08:35 AM
a= new class b();---> Reference variable of class a is been given an object of class b .(Allowed)

Here I can access the parent class members but cannot access the child class members even though the object given is child class. why? If it cannot be accessed then what is the use of providing different objects in runtime? Instead we can give a=new class a(); why the facility has been provided to give different objects at runtime?

Robbe Morris replied to Krishna Madhu on 06-Mar-13 08:46 AM
Krishna Madhu replied to Robbe Morris on 07-Mar-13 08:25 AM
I am after dynamic binding(polymorphism-adhoc-polymorphism). why  a reference variable of a parent cannot access a child class inspite of been given a child class object during runtime.

a child class reference variable cannot refer to an object of parent class. but a parent class reference variable can  be given  a child class during runtime.
Robbe Morris replied to Krishna Madhu on 07-Mar-13 09:16 AM
You've explicitly defined var2 as being private.  In C#, that means that nothing outside the class, whether it is inherited or not, can access or have knowledge of var2.  You'd have to define var2 as at least being protected (assuming both classes are in the same assembly) or public like you did your other variables.