N
Nudge
I am slightly confused, so please keep that in mind if I make
only little sense.
Assume I have a base class:
class Base { ... };
and two derived classes:
class Int : public Base { ... int foo; };
class Double : public Base { ... double bar; };
Assume I want to keep a vector of Int's OR Double's.
I could write either
std::vector<Base *> v1;
or
std::vector<Base &> v2;
So far, so good?
I'm probably missing something fundamental: is there a real
difference between v1 and v2? Will v2 work with virtual functions?
I'll allocate several Int's and Double's on the heap with new
and store them in v2, for example.
Now I want to copy v2 into v3. If I just write v3 = v2, I'll end up with
the same references in v2 and v3, right? What I want is to copy every
object in the vector and store the reference to the copy in v3. That
way, if I modify an object in v3, v2 won't be affected.
One way I see is to overload operator=
typedef std::vector<Base &> MyVec;
MyVec &operator=(MyVec &)
{
for every element in MyVec, call a virtual self-copy method;
}
Is that acceptable? Is there a better way?
only little sense.
Assume I have a base class:
class Base { ... };
and two derived classes:
class Int : public Base { ... int foo; };
class Double : public Base { ... double bar; };
Assume I want to keep a vector of Int's OR Double's.
I could write either
std::vector<Base *> v1;
or
std::vector<Base &> v2;
So far, so good?
I'm probably missing something fundamental: is there a real
difference between v1 and v2? Will v2 work with virtual functions?
I'll allocate several Int's and Double's on the heap with new
and store them in v2, for example.
Now I want to copy v2 into v3. If I just write v3 = v2, I'll end up with
the same references in v2 and v3, right? What I want is to copy every
object in the vector and store the reference to the copy in v3. That
way, if I modify an object in v3, v2 won't be affected.
One way I see is to overload operator=
typedef std::vector<Base &> MyVec;
MyVec &operator=(MyVec &)
{
for every element in MyVec, call a virtual self-copy method;
}
Is that acceptable? Is there a better way?