1

Trying to compile the code

pragma solidity ^0.8.0;

abstract contract Test {
    
    event functionCompleted(address indexed);
    
    modifier emitter(address x) {
      _;
      emit functionCompleted(x);
    }
    
    function testFunction(address x) public virtual emitter(x);
}

on Remix IDE gives the following error: SyntaxError: Functions without implementation cannot have modifiers.

What are the reasons for Solidity not supporting modifiers on virtual functions?

2

It does not have anything to do with the function being virtual. Modifiers can only be used on functions with implementations.

Modifiers have a special symbol _; (as indicated in line 8 your code), which means the body of the function you are modifying is inserted in that particular location.

The modifier would only work here if you did something like this:

function testFunction(address x) public virtual emitter(x) {
    uint8 example = 1 + 2; // function body
}

And therefore the complete function together with the modifier body would be:

function testFunction(address x) public virtual emitter(x) {
    uint8 example = 1 + 2; // function body
    emit functionCompleted(x); // modifier body
}
3
  • 1
    Thanks for your answer @rlyx31. I was not clear in my question: I was thinking in the possibility where I would have another contract inheriting the contract Test and implementing the testFunction afterwards. That way the modifier would be applied to the implemented testFunction in the child contract (though the definition of the modifier would be in the parent contract). Does that makes sense? Or do you think it would be a bad feature for the Solidity language?
    – shamisen
    Jun 1 at 4:15
  • 1
    Ah, I see what you mean! It definitely seems like a good feature to add, but I don't quite have an answer to why it hasn't been implemented yet, other than the fact that Solidity is still a relatively young language. Apologies for the misunderstanding of your question.
    – rlyx31
    Jun 1 at 7:27
  • I just found out that Solidity does support it. There was an error on my code: it should have been function testFunction(address x) public virtual emitter(x) {} instead of function testFunction(address x) public virtual emitter(x)
    – shamisen
    Jun 10 at 3:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.