Distinguish between pointers created with 'new' and created with references.
Hi all,
I am struggling with a design problem. It showed up because of some
architectures constraints.
I have a group of classes which derive from an abstract one.
I have a vector with pointers to the generic abstract class (neither
vector of references nor vector of classes are allowed since it's
abstract).
A member function that loads objects into the vector, lets say from
file, has to do it creating object with new operator since it couldn't
be done by references to objects created locally.
A public functions lets the user to add single objects too but it
could use new or reference as an argument.
The problem is when I need to call the destructor, and erase all of
the objects created within the vector.
I thought of using delete operator for each element in the vector, but
what if some other elements has been added from a reference. delete
&something ## failure.
I guess there is no way to distinguish between object address created
with new and created with a reference.
How a to write a proper destructor then??
Here it is a very easy program that shows the situation.
Thanks!!
#include <iostream>
#include <vector>
using namespace std;
class Fruit
{
public:
virtual string name() = 0;
};
class Orange : public Fruit
{
public:
virtual string name(){return string("Orange");};
};
class Watermelon : public Fruit
{
public:
virtual string name(){return string("Watermelon");};
};
class Apple : public Fruit
{
public:
virtual string name(){return string("Apple");};
};
class Basket
{
public:
void loadFruits();
void addFruit(Fruit* pFruit);
void showFruits();
private:
vector<Fruit*> fruitList;
};
void Basket::loadFruits()
{//adds three fruits
addFruit(new Watermelon());
addFruit(new Orange());
addFruit(new Apple());
}
void Basket::addFruit(Fruit* pFruit)
{
fruitList.push_back(pFruit);
}
void Basket::showFruits()
{
for(unsigned int i=0;i<fruitList.size();++i)
{
cout << fruitList[i]->name() << endl;
}
}
int main()
{
Basket myBasket;
myBasket.loadFruits();
Orange theOrange;
myBasket.addFruit(&theOrange);
myBasket.showFruits();
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]