regerus
regerus

Reputation: 73

How do I create a new object from an instance of its base class?

I have a base class, A, which has a method that returns an instance of itself:

class A
{
    protected DateTime P { get; private set; }

    protected A()
    {
        P = DateTime.Now;
    }

    protected A GetOneA()
    {
        return new A();
    }
}

I need to create instance of child class B based on A object.

class B : A
{
    private B(A a)
    {
        //help
    }

    public B GetOneB()
    {
        A a = A.GetOneA();
        return new B(a);
    }
}

Is it possible?

Upvotes: 2

Views: 2593

Answers (3)

Nix
Nix

Reputation: 58522

Yes it is possible. First create a "copy" constructor and pass a class instance of A. Inside this constructor you will need to copy all necessary attributes.

class A
{
  protected DateTime P { get; private set; }
  protected A(A copy){
      //copy all properties
      this.P = A.P;
  }
  protected A()
  {
    P = DateTime.Now;
  }

  protected A GetOneA()
  {
    return new A();
  }

}

Then just call the super classes copy constructor.

class B : A
{
  //help
  private B(A a) : base(a)
  {
  }

  public B GetOneB()
  {
    A a = A.GetOneA();
    return new B(a);
  }
}

Let me know if this is not what you are looking for.

Further reading on copy constructors: http://msdn.microsoft.com/en-us/library/ms173116.aspx

Upvotes: 3

Sion Sheevok
Sion Sheevok

Reputation: 4217

You made the constructor for A protected. B already contains an A because it is-an A. When the constructor for B is called, it will implicitly call the default constructor for A. What your GetOneB method is doing is calling GetOneA, which allocates an A, followed by allocating a B that is copy-constructed with A a as the parameter.

There's an issue of separation of concerns. There's initialization and there's allocation. If a B is-an A, and As can only be allocated a certain way, then B can not allocate only its A part a certain way and its B part another way. The whole B must be allocated in one manner, but the initialization of it can be done otherwise.

If A must be allocated in a manner different than the rest of B, then you must use containment and create a has-a relationship.

EDIT: We're talking C#, so most of that is irrelevant, because if you're working in C# you're probably not manually managing memory allocation. In any case, you don't need to call GetOneA, because B is-an A and A's constructor is called when B is constructed.

Upvotes: 2

Noon Silk
Noon Silk

Reputation: 55062

It is not technically possile no. That is, if I understand your goal to be to set an instance of some class to have an independent "parent" instance. It's just quite logically wrong I suppose.

You'd do better explaning what you want to do. Perhaps you may just like to copy the properties of the object into your own; in that case it's quite straight foward ...

Upvotes: 0

Related Questions