Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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)

{

}

 

}

  • Administrators
Posted

Given the following classes

public class ParentClass
{
	public ParentClass()
	{
	
	}
}

public class ChildClass : ParentClass
{
	public ChildClass()
	{

	}
              
}

public class GrandChildClass : ChildClass
{
	public GrandChildClass()
	{

	}
public GrandChildClass(int i) 
	{

	}
}

 

the line

GrandChildClass c1 = new GrandChildClass();

will call the constructor of ParentClass() then ChildClass() then GrandChildClass().

 

if you instantiated it like

GrandChildClass c1 = new GrandChildClass(1);

 

then it would call the constructor of ParentClass() then ChildClass() then GrandChildClass(int).

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted

But suppose the parent class had another constructor

 

 

public ParentClass(int k)

{

}

 

It's the first constructor that will fire not this one?

  • Administrators
Posted

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:

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.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...