tags:

views:

41

answers:

3

Hi to all,

I have a question, I have a base class and an another class which derived from the base class. Can we access derived class in the base class.

Thanks in advance

A: 

No you can not. If you happen to know the an object declared as the Base class is actually the derived class, you can cast it. But within the base class you can not access the derived class's members.

Eric
+1  A: 

You can access the code in the derived class from the base class code, but only from within an object which is actually a derived class object, and then only if the methods involved are virtual methods.

If you have an object which is itself an instance of the base class, then from within that instance you cannot see derived class code from the base class .

example

   public class Baseclass
   {  
      public void Foo()
      {
          Bar();
      }
      public virtual void Bar()
      {
         print("I'm a BaseClass");
      }
   }
   public classs Derived: BaseClass
   {
      public override void Bar()
      {
         print("I'm a Derived Class");
      }
   }


   Main()
   {
       var b = new BaseClass();
       x.Foo()  // prints "I'm a BaseClass" 
       // This Foo() calls Bar() in base class

       var d = new Derived();
       d.Foo()  // prints "I'm a Derived Class" 
       // in above, the code for Foo() (in BaseClass)
       //  is accessing Bar() in derived class      
   }
Charles Bretana
A: 

There are a lot of ways that a base class can access members of a derived class (depending on programming language), but generally it is considered a design smell.

Instead, you usually want the base class to only directly access its own members, and allow derived classes to override methods.

Kristopher Johnson