×

Loading...
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务

A c++ question for help!!! Thanks!

Consider the implementation of a Container class framework with the following abstract base class Container:
template <class Item>
class Container {
public:
unsigned numberOfItems() {return currentSize;}
bool isEmpty() {return currentSize == 0;};
virtual void flush() = 0;
~Container() {flush();}
private:
unsigned currentSize;
};

Here the idea is that each particular (derived) container class shall implement its own flush() operation (which makes sense because different containers are flushed in different ways: there may be arrays, linked lists, rings or hashtables used in the representation), and when a container is destroyed its flush() operation will be automatically invoked. However, the idea is flawed and the code as written causes a terrible thing to happen. What happens?
Report

Replies, comments and Discussions:

  • 工作学习 / IT技术讨论 / A c++ question for help!!! Thanks!
    Consider the implementation of a Container class framework with the following abstract base class Container:
    template <class Item>
    class Container {
    public:
    unsigned numberOfItems() {return currentSize;}
    bool isEmpty() {return currentSize == 0;};
    virtual void flush() = 0;
    ~Container() {flush();}
    private:
    unsigned currentSize;
    };

    Here the idea is that each particular (derived) container class shall implement its own flush() operation (which makes sense because different containers are flushed in different ways: there may be arrays, linked lists, rings or hashtables used in the representation), and when a container is destroyed its flush() operation will be automatically invoked. However, the idea is flawed and the code as written causes a terrible thing to happen. What happens?
    • Object Inheritance and destruction issue...
      If you have some basic idea on inheritance and object destruction, you would know whenever the descendants start to destroy themselves, system would automatically destroy their base class object first! That is the problem because the stupid base class has to use a pure virtual function to do the trick, ridiculous right?
    • Moreover, the destructor of base class is not virtual!!! I cannot believe this code snippet is from a professional... So dumb