Inheritance, vectors and copy

From: Nudge (a_at_b.c)
Date: 05/25/04


Date: Tue, 25 May 2004 23:10:47 +0200

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?

-- 
Regards, Nudge


Relevant Pages

  • Re: Writing huge Sets() to disk
    ... pushes it's internal dictionaries ... > Almost anything you do copies references. ... > store the values on disc in a reasonably efficient manner. ... bsddb creaps on me that I can store as a key or value only a string. ...
    (comp.lang.python)
  • Re: Which database design is better
    ... you can update primary keys because you can ... of employee. ... Remember that part in the specs in this thread about each store ... then I can use a REFERENCES clause. ...
    (microsoft.public.sqlserver.programming)
  • Re: object references
    ... > performance reasons) so I don't have to recreated the objects when I need ... > stored in the hashtable has no more references to it? ... You'd need to use WeakReferences - store the WeakReference in the table ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: how to make two references to one string that stay refered to the same string reguardless of the
    ... > and have a conversion table to say that 12 translates into Monty Ville. ... Given that you've got to store "Monty Ville" somewhere, ... well just have several references to the same string. ... "Monty Ville" will be a reference to the same string object. ...
    (microsoft.public.dotnet.languages.csharp)