Can we create instance of base class and store it to derive class?
No, you cannot directly create an instance of a base class and store it in a variable of the derived class. Inheritance allows you to go from the derived class to the base class, but not the other way around.
However, you can achieve a similar effect through a process called upcasting. Upcasting involves creating an instance of the derived class and then storing it in a variable of the base class type. This works because the derived class object inherently contains the features of the base class.
Here's an example to illustrate upcasting:
public class BaseClass
{
public void BaseMethod()
{
Console.WriteLine("Base method");
}
}
public class DerivedClass : BaseClass
{
public void DerivedMethod()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass baseObj = new DerivedClass(); // Upcasting
baseObj.BaseMethod(); // Output: Base method
// baseObj.DerivedMethod(); // Error: BaseClass doesn't have the DerivedMethod
}
}
In this example, an instance of the DerivedClass is created and stored in a variable of type BaseClass. This is possible because a derived class object can be treated as an instance of its base class. Therefore, you can call the base class methods and access the members that are inherited from the base class.
However, you cannot directly access the methods or members specific to the derived class using the base class variable. In the example above, attempting to call DerivedMethod() on baseObj would result in a compilation error because the BaseClass does not have that method.
If you want to access the specific members or methods of the derived class, you can perform a downcast, which involves explicitly casting the base class variable back to the derived class type. But for that, you must ensure that the actual object stored in the base class variable is an instance of the derived class, otherwise, an exception will occur at runtime (known as an invalid cast exception).
DerivedClass derivedObj = (DerivedClass)baseObj; // Downcasting
derivedObj.DerivedMethod(); // Output: Derived method
In this case, the downcast (DerivedClass)baseObj allows you to access the specific members and methods of the derived class. However, you need to be cautious when performing downcasting to ensure that the actual object is of the derived class type to avoid runtime errors.