Base Class Constructor Gets Executed When Creating a Derived Class Object

Let's create two classes: Base class and Derived class. Derived Class inherits from the Base class. We have Base () and Derived () constructor for Base class and Derived class respectively.

Now when we create a Derived class object Base constructor gets executed, Let's see in the code:

Code 
  1. using System;  
  2. namespace OOPS  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Derived d = new Derived();  
  9.             Console.ReadLine();  
  10.         }  
  11.     }  
  12.   
  13.     class Base  
  14.     {  
  15.   
  16.         public Base()  
  17.         {  
  18.             Console.WriteLine(" I am Base class constructor");  
  19.         }  
  20.     }  
  21.   
  22.     class Derived :Base  
  23.     {  
  24.   
  25.         public Derived()  
  26.         {  
  27.             Console.WriteLine(" I am Derived class constructor");  
  28.         }  
  29.     }  
  30. }  
Output
  

So In this example we saw the Base Constructor is executed first when creating a derived class object. Hope you got the concept ,Thanks for reading.

Ebook Download
View all
OOP/OOD
Read by 0 people
Download Now!
Learn
View all