can we create derived class object from base class c#

Answer: No.

In general, When we create object of a class, its reference is stored in stack memory and object is stored in heap and address of object is assigned to class reference.

For example child is the class and Child objch=new child(); is the object then

Child objch is child class reference created on stack memory.

new child(); create object of Child on Heap memory and address ofit is assigned to objch referenece.

class Child
    {
        public Child()
        {
            Console.WriteLine("Child class Constructor");
        }
        
    }

Example program for creating a derived object from base class.

class Program
    {
        static void Main(string[] args)
        {
            Child objC = new Child();
        }
    }
    class Parent
    {
        Child objCh = new Child();
        public Parent()
        {
            Console.WriteLine("Parent Class Constructor");
        }
    }
    class Child:Parent
    {
        public Child()
        {
            Console.WriteLine("Child class Constructor");
        }
        //Parent objP = new Parent();
    }

Output

Process is terminated due to StackOverflowException.

In the above example,

creates an object of child class(derived class) from parent class(base class) then first parent (base) class constructor and then (child class )derived class constructor get called implicitly.

This constructor calling from base class to derived class and derived to base class repeats until stack memory is full.

After reaching stack memory limit, it terminates the process and raise the stack overflow exception

base–>derived–>base–>derived—> …until stack is full.

Related Posts