Search code examples
c++v8

How to properly create a derived class from this v8 class


So I have a class that is in v8 that I want my own class to derive from and then instantiate an instance of my own class.

In v8 there is the class with this signature:

class V8_EXPORT CodeEventHandler {
 public:
  /**
   * Creates a new listener for the |isolate|. The isolate must be initialized.
   * The listener object must be disposed after use by calling |Dispose| method.
   * Multiple listeners can be created for the same isolate.
   */
  explicit CodeEventHandler(Isolate* isolate);
  virtual ~CodeEventHandler();

  /**
   * Handle is called every time a code object is created or moved. Information
   * about each code event will be available through the `code_event`
   * parameter.
   *
   * When the CodeEventType is kRelocationType, the code for this CodeEvent has
   * moved from `GetPreviousCodeStartAddress()` to `GetCodeStartAddress()`.
   */
  virtual void Handle(CodeEvent* code_event) = 0;

  /**
   * Call `Enable()` to starts listening to code creation and code relocation
   * events. These events will be handled by `Handle()`.
   */
  void Enable();

  /**
   * Call `Disable()` to stop listening to code creation and code relocation
   * events.
   */
  void Disable();

 private:
  CodeEventHandler();
  CodeEventHandler(const CodeEventHandler&);
  CodeEventHandler& operator=(const CodeEventHandler&);
  void* internal_listener_;
};

And my own derived class looks like this:

class CodeEventHandler : public v8::CodeEventHandler
{
public:
    ~CodeEventHandler()
    {
        listeners.clear();
    }

    void Handle(v8::CodeEvent* event)
    {
        // code omitted for readibility
    }

    v8::Local<v8::Object> SerializeEvent(v8::CodeEvent* event)
    {
        // code omitted for readibility
    }

    void AddListener(v8::Local<v8::Function> listener)
    {
        // code omitted for readibility
    }

    void SetResource(CV8ResourceImpl* _resource)
    {
        resource = _resource;
    }

private:
    CV8ResourceImpl* resource;
    std::vector<v8::UniquePersistent<v8::Function>> listeners;
};

But when I want to instantiate my class like this:

v8::Isolate* isolate = v8::Isolate::GetCurrent();
auto codeEventHandler = new CodeEventHandler(isolate);

I get this error:

error C2664: 'CodeEventHandler::CodeEventHandler(const CodeEventHandler &)': cannot convert argument 1 from 'v8::Isolate *' to 'const CodeEventHandler &'

What am I doing wrong?


Solution

  • (This is not a V8-specific question; it's plain C++.)

    As @JosephLarson points out, you need a constructor with the right signature. Add this to your class:

    explicit CodeEventHandler(Isolate* isolate)
        : v8::CodeEventHandler(isolate) {
      // any code you need to initialize your subclass instances...
    }