newb
newb

Reputation: 1

Problems with "delete" keyword

In the main function

string reader_txt = "Readers.txt";
string book_txt = "Books.txt";

Reader * obj[10];

// *********** Reading Reader.txt

ifstream reader_input;
reader_input.open(reader_txt.c_str()); // open file

string reader_name;
string reader_category;
int reader_n_category;
int counter=0;

if(reader_input.is_open())
{
    while( getline(reader_input, reader_name, '\n') && getline(reader_input, reader_category, '\n'))
    {
        reader_n_category = atoi(reader_category.c_str());

        switch(reader_n_category)
        {
        case FANTASY:
            obj[counter++] = new fantasyReader(reader_name);
            break;
        case MYSTERY:
            obj[counter++] = new mysteryReader(reader_name);
            break;
        case HORROR:
            obj[counter++] = new horrorReader(reader_name);
            break;
        case SCIENCE:
            obj[counter++] = new scienceReader(reader_name);
            break;
        }
    }
}
else
    cout<<"Cannot open up the Readers.txt"<<endl;

reader_input.close();   // close file

reader is base class
fantasyReader, horrorReader, mysteryReader, scienceReader are derived class.

At the end of main I put:

for(int pos=0; pos < counter; pos++)
{
     delete obj[pos];  // compiling error, I don't know why
}

I get a compile error:

main.obj : error LNK2019: unresolved external symbol "public: __thiscall Reader::~Reader(void)" (??1Reader@@QAE@XZ) referenced in function "public: void * __thiscall Reader::'scalar deleting destructor'(unsigned int)" (??_GReader@@QAEPAXI@Z)

This wouldn't work. How can or where should I write a delete statement?

Upvotes: 0

Views: 1505

Answers (4)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385088

That's a linking error, not a compiler error.

You forgot to define an implementation for Reader's destructor.

Upvotes: 2

Kanopus
Kanopus

Reputation: 774

It's not a compile time error, but a linking error. You've declared the destructor of Reader, but not implemented it. You've got to implement the destructor in Reader even if it's a pure virtual one, like so:

class Reader {
public:
  virtual ~Reader() = 0;
};

Reader::~Reader() {}

Also remember (in case you haven't done it already) that a base class must always have its destructor set as virtual.

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249093

The Reader base class needs to have a public virtual destructor. There may be other problems, but this is what I can gather from the incomplete code posted.

Upvotes: 1

GMichael
GMichael

Reputation: 2776

It's not the delete statement that is important. Have you defined the derived classes as virtual ones? Or, at least the have you declared the destructors as virtual?

Upvotes: 0

Related Questions