36

I came across the super keyword in Solidity in the context of overriding functions. What does it do?

1 Answer 1

65

The super keyword in Solidity gives access to the immediate parent contract from which the current contract is derived. When having a contract A with a function f() that derives from B which also has a function f(), A overrides the f of B. That means that myInstanceOfA.f() will call the version of f that is implemented inside A itself, the original version implemented inside B is not visible anymore. The original function f from B (being A's parent) is thus available inside A via super.f(). Alternatively, one can explicitly specifying the parent of which one wants to call the overridden function because multiple overriding steps are possible as exemplified in the example below:

pragma solidity ^0.4.5;

contract C {
  uint u;
  function f() {
    u = 1;
  }
}

contract B is C {
  function f() {
    u = 2;
  }
}

contract A is B {
  function f() {  // will set u to 3
    u = 3;
  }
  function f1() { // will set u to 2
    super.f();
  }
  function f2() { // will set u to 2
    B.f();
  }
  function f3() { // will set u to 1
    C.f();
  }
}
7
  • 10
    What if it has multiple inheritance?
    – Emobe
    Commented Jan 12, 2020 at 18:10
  • 2
    @Emobe solidity uses the same linearization algorithm as python (C3). So super would refer to the next highest class in the linearization. (caution: in python you read the classes from left to right from lowest to highest; ;in solidity you read from right to left to go from lowest to highest). Commented Jan 15, 2020 at 21:59
  • Not sure B.f() and C.f() are allowed anymore in Solidity v0.6.10 and above. Getting a "Cannot call function via contract type name" error. Commented Jul 26, 2020 at 13:58
  • 3
    important caveat: "gives access to the immediate parent contract from which the current contract is derived" is slightly misleading. It would be more accurate to say "gives access to the parent contract according to the output of the C3 linearization algorithm", which in some cases (e.g. multiple inheritance) may not be the contract listed as the immediate parent on the contract itself. contract C is D does not mean that super in context of C can be guaranteed to be D.
    – Kyle Baker
    Commented Apr 8, 2022 at 14:29
  • 2
    solidity-by-example.org/inheritance is very helpful here
    – relik
    Commented Aug 17, 2022 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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