I currently have a derived class and a base class. How can I make the base class of the derived class equal to a base class that I have? Will a shallow copy work?
class Base
{
private string name;
public string Name { get; set; }
private string address;
public string Address { get; set; }
}
class Derived:Base
{
private string field;
public String field { get; set; }
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Base b = new Base();
b.Address = "Iliff";
b.Name = "somename";
Derived d = new Derived();
//How can I make the base class of d equal to b ?
}
}
}
No, that's not possible since assigning it to a derived class reference would be like saying "Base class is a fully capable substitute for derived class, it can do everything the derived class can do", which is not true since derived classes in general offer more functionality than their base class (at least, that's ...
The derived class inherits all members and member functions of a base class. The derived class can have more functionality with respect to the Base class and can easily access the Base class. A Derived class is also called a child class or subclass.
Usually you use a derived class when an existing class provides members that the new class can use, or when you want to extend or embellish existing class properties and methods. This is called inheritance: the new class inherits, and has direct access to, all Public and Private members of the existing base class.
Create a copy constructor for the base class, in doing so you'll also need to create a parameterless one as well as by adding the copy constructor the default constructor will no longer be generated by the compiler. Then in the derived class call the base class's copy constructor.
public class Base
{
public int Name { get; set; }
public string Address { get; set; }
public Base()
{ }
public Base(Base toCopy)
{
this.Name = toCopy.Name;
this.Address = toCopy.Address;
}
}
public class Derived : Base
{
public String Field { get; set; }
public Derived(Base toCopy)
: base (toCopy)
{ }
// if desired you'll need a parameterless constructor here too
// so you can instantiate Derived w/o needing an instance of Base
public Derived()
{ }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With