I have the following function and a hierarchy of classes such that Multinumber is inherited by Pairs, Rational, and Complex. All of these share functions which are virtual in Multinumber. My problem is the following code. The way it is written right now, the newElement variable goes out of scope when it is added to my setArray which is of type Multinumber**, and I need to figure out some way to allocate memory within this function. Oddly, paramters that are passed into the function, even when printed on the first line, are always empty when I do a cout<<newElement->tostring(); Can anyone tell me what is wrong here?
bool Set::addElement(Multinumber* newElement)
{
bool success = false;
if(isFull())
{
resize();
}
if(!isMember(newElement))
{
setArray[numElements] = newElement;
numElements++;
success = true;
}
return success;
}
EDIT: Yes the poster is correct, this is a homework assignment
In the real world (I understand from your previous question that this is for homework), you wouldn’t implement your own set. The standard library provides this functionality (
std::setif you want to keep the elements in order;std::unordered_setif you’re using C++0x and/or have the appropriate extensions, and prioritize speed over the additional functionality).You should probably also look into some smart-pointer classes.
That said:
In your code,
newElementisn’t going out of scope. What happens is that you’ve been given a pointer to the calling code’s data, and the calling code is then letting the pointed-at thing go out of scope.As I responded to your previous question, you need to use the “virtual clone idiom” to make the copy.
Basically, you want to call
newwith whatever the type is of the passed-in, pointed-at thing, in such a way that a copy is made. To ensure “that a copy is made”, the natural thing to do would be to use the copy constructor withnew, that isnew whatever(my_existing_whatever_instance). But in C++, constructors cannot bevirtual, so we can’t actually put the desired type into anewcall. Instead, we have to fake it with a member function. Since member functions can bevirtual, the correct versioncloneis looked up in the actual pointed-at thing, which is implemented to callnewusing its own type, and calling its own copy constructor. The link provides details.