How can I convince myself that a pure virtual method is being called from my derived class?

I have the following situation:

#include <iostream>

class Base{
  public:
    Base() = default;
    virtual void make_sure_im_called() = 0;
};

class Child : public Base {
  public:
    virtual void make_sure_im_called()
    {
      std::cout << "I was called as intended." << std::endl;
    };
}

This is so that I want every class derived from Base to implement make_sure_im_called () (which succeeds, making it pure virtual). But how can I argue that someone getting a new class from Base is also forced to call a function? It seems that everything I try from the base class will not be executed due to a missing implementation.

+4
source share
1 answer

In C ++, there is no built-in construct that does what you want, but you can always do it yourself.

#include <iostream>

class Base{
  public:
    Base() = default;
    void make_sure_im_called() {
       before_make_sure_im_called();
       // Your own code
       after_make_sure_im_called();
    }
  protected:
    // Hooks to be implemented
    virtual void before_make_sure_im_called() = 0;
    virtual void after_make_sure_im_called() = 0;
};

class Child : public Base {
  protected:
    virtual void before_make_sure_im_called() override
    {
      std::cout << "I was called as intended." << std::endl;
    };
    virtual void after_make_sure_im_called() override {}
}

2 ( 1 ). - make_sure_im_called, .

, , .

.

make_sure_im_called Base. , , , .

#include <iostream>

class Base{
  public:
    Base() = default;
    ~Base() { assert(_initialized && "Some message"); }
    void make_sure_im_called() {
       before_make_sure_im_called();
       // Your own code
       after_make_sure_im_called();
       _initialized = true;
    }
  protected:
    // Hooks to be implemented
    virtual void before_make_sure_im_called() = 0;
    virtual void after_make_sure_im_called() = 0;

  private:
      bool _initialized{false};
};

class Child : public Base {
  protected:
    virtual void before_make_sure_im_called() override {};
    virtual void after_make_sure_im_called() override {}
}

_initialized, . Dtor , ( -?). : ///.

, , , , . API.

+5

Source: https://habr.com/ru/post/1676404/


All Articles