Showing posts with label Base Class Constructor. Show all posts
Showing posts with label Base Class Constructor. Show all posts

Thursday, July 24, 2014

How constructors are called while the classes are inherited: Exploring Object Oriented Programming and Concepts

Constructor Calls in Inheritance

Case study 1:

ClassA is a base class of ClassB.
Both classes have default constructor.

Observations:
While creating a new instance of ClassB (without parameters):
- it will first call default constructor of ClassB which will call constructor of ClassA.
- it will complete executing code of default constructor of ClassA.
- after that, it will complete executing code of default constructor of ClassB.

Case study 2:

ClassA is a base class of ClassB.
ClassA has no default constructor, but only parameterized constructor.
ClassB has a default constructor.


Observations: 
- it will not allow creating ClassA without a default constructor 
- if you want to do so, you need to call a base class constructor from ClassB's constructor: 
For example, following is the constructor of class A 
public ClassA(string someVariable) ..... some code .... }  
To allow ClassA without a default constructor, its all child classes should call base class constructor as below: 
public ClassB(): base("some value") 
or
public ClassB(string fullName): base(fullName)