Copy constructor in polymorphism in C# -
please first take @ simple code;
this base class:
public class baseclass { public baseclass() { } public baseclass(baseclass b) { } public virtual string getmsg() { return "base"; } }
and derived one:
public class drivenclass : baseclass { public string msg { get; set; } public drivenclass(string msg) { msg = msg; } public drivenclass(drivenclass d) { msg = d.msg; } public override string getmsg() { return msg; } }
and test:
public partial class form1 : form { public form1() { initializecomponent(); } public baseclass b { get; set; } public drivenclass d { get; set; } private void button1_click(object sender, eventargs e) { d = new drivenclass("driven"); b = new baseclass(d); messagebox.show("b:" + b.getmsg() + "\nd:" + d.getmsg()); } }
now question should b = new baseclass(d);
works b = new drivenclass(d);
?
i'm using in polymorphism , use 1 copy-constructor instead of different driven ones.
i want output :
driven driven
but it's :
base driven
you can use overridden virtual copy method instead of copy constructor.
public class baseclass { public baseclass() { } public virtual baseclass shallowcopy() { return new baseclass(); } public virtual string getmsg() { return "base"; } } public class drivenclass : baseclass { public string msg { get; set; } public drivenclass(string msg) { msg = msg; } public override baseclass shallowcopy() { return new drivenclass(this.msg); } public override string getmsg() { return msg; } }
then call this:
d = new drivenclass("driven"); b = d.shallowcopy();
this work because calling virtual method calls actual overriden implementation in subclass, when called baseclass interface.
Comments
Post a Comment