Base Class Constructor

barski

Junior Contributor
Joined
Apr 7, 2002
Messages
240
Location
Tennessee
If you have a base class let's call it "a" and you have another class "b" that inherits class "a". "a" has three constructors. When I create a new instance of "b" will "a" first constructor always be the one that fires? Because it certainly seems like it is.

In other words when the line below executes which of the following three constructors will fire?
a b = new a("myvalue");

public class a{

a()
{
}

a(string myvalue)
{
}

a(string myvalue, string myvalue2)
{
}

}
 
Given the following classes
C#:
public class ParentClass
	{
		public ParentClass()
		{
		
		}
	}

	public class ChildClass : ParentClass
	{
		public ChildClass()
		{

		}
               
	}

	public class GrandChildClass : ChildClass
	{
		public GrandChildClass()
		{

		}
 public GrandChildClass(int i) 
		{

		}
	}

the line
C#:
GrandChildClass c1 = new GrandChildClass();
will call the constructor of ParentClass() then ChildClass() then GrandChildClass().

if you instantiated it like
C#:
GrandChildClass c1 = new GrandChildClass(1);

then it would call the constructor of ParentClass() then ChildClass() then GrandChildClass(int).
 
But suppose the parent class had another constructor


public ParentClass(int k)
{
}

It's the first constructor that will fire not this one?
 
It would call ParentClass(), ChildClass(), GrandChildClass(int)

if you wanted it to use the ParentClass(int) c'tor then you could change the code to:
C#:
	public class ParentClass
	{
		public ParentClass()
		{
        
		}

		public ParentClass(int k)
		{

		}
	}

	public class ChildClass : ParentClass
	{
		public ChildClass()
		{

		}

		public ChildClass(int i) : base(i)
		{}

	}

	public class GrandChildClass : ChildClass
	{
		public GrandChildClass()
		{

		}
		public GrandChildClass(int i) : base(i)
		{

		}
	}

and tell the overloaded c'tor to call the correct one from the base class.
 
Back
Top