Introduction
Dear all, welcome back to a new article on a very interesting topic.
We always have wondered why we even need an abstract class in the first place? You will find the answer to that question in my recent article on Purposes Of An Abstract Class.
After understanding the need for an abstract class, it immediately raises a second question.
If it is a class, it can have a constructor to initialize its properties. But hold on, we know that abstract class can never be instantiated. which means we can never have an object of an abstract class. Then how are we supposed to call a constructor when we can't even create an object of an abstract class.
Hmmm, very interesting.
- public abstract class AppleBase
- {
- public AppleBase()
- {
- }
- public abstract void SetPrice();
- }
First, if I try to create an object of an abstract class what will happen?

There, it's a compile-time error. forget about running your program, not even complier is ready to allow that.

So basically we can not create an instance to call a constructor. But it is not the only way to call a constructor.
Ever heard about Constructor chaining

- Constructor Chaining is a concept when a constructor calls another constructor in the same class or its base class.
Let me explain it to you with an example.
Say we have base class AppleBase which is printing a message in its constructor.
- public class AppleBase
- {
- public AppleBase()
- {
- Console.WriteLine("1. Base class: AppleBase");
- }
- }
The derived class: MacBook. It is also printing a message in its constructor.
- class MacBook : AppleBase
- {
- public MacBook()
- {
- Console.WriteLine("2. Derived class: MacBook");
- }
- }
Now if I create an object of MacBook. what do you think what will happen?
- class Program
- {
- static void Main(string[] args)
- {
- MacBook macBook = new MacBook();
- }
- }
Let's see what will happen.

Analyze the output, even if we create an object of a MacBook, Compiler still calls an AppleBase class's constructor prior to MacBook's.
This concept is known as constructor chaining.
What did this tell us?




Join the conversation! Your thoughts help the community grow.