barski Posted February 5, 2004 Posted February 5, 2004 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) { } } Quote
barski Posted February 5, 2004 Author Posted February 5, 2004 oops typo a b = new a(); should be b c = new b(); Quote
Administrators PlausiblyDamp Posted February 5, 2004 Administrators Posted February 5, 2004 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). Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
barski Posted February 5, 2004 Author Posted February 5, 2004 But suppose the parent class had another constructor public ParentClass(int k) { } It's the first constructor that will fire not this one? Quote
Administrators PlausiblyDamp Posted February 5, 2004 Administrators Posted February 5, 2004 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
barski Posted February 5, 2004 Author Posted February 5, 2004 Thank you. It always seems obvious once you see the answer Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.