Cloning in superclass

  • Thread starter Thread starter Borneq
  • Start date Start date
B

Borneq

Guest
I have

struct Base
{
int a;
Base *clone()
{
base *cloned = new Base();
cloned->a = a;
return cloned;
}
}

struct Sub: public Base
{
int b;
}

is problem cloning Sub

I change to :

virtual Base *clone()

struct Sub: public Base
{
int b;
Sub *clone() override
{
sub *cloned = new Sub();
cloned->a = a;
cloned->b = b;
return cloned;
}
}

1. I must cloning all fields, can't use clone from superclass

2. This violates Liskov principle?



In Object Pascal was virtual constructor and class type - class as parameter, is something like it in C++? Especially I want force new to make object particular dynamic type


-------------

I think, solution can be fillFields method:

void Base::fillFields(Base *cloned)
{
cloned->a = a;
}

void Sub::fillFields(Sub *cloned)
{
Base::fillFields(cloned);
cloned->b = b;
}

Sub *clone()
{
Sub *cloned = new Sub();
fillFields(cloned);
return cloned;
}

Note, that method fillFields must not be virtual.

Because calling it from Base it would set non existing field b.

Continue reading...
 
Back
Top