I came across the super
keyword in Solidity in the context of overriding functions. What does it do?
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();
}
}
-
1
-
@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). – Chan-Ho Suh Jan 15 '20 at 21:59 -
Not sure
B.f()
andC.f()
are allowed anymore in Solidity v0.6.10 and above. Getting a "Cannot call function via contract type name" error. – Paul Razvan Berg Jul 26 '20 at 13:58 -
Update: the issue was that I was trying to override an already-overriden function. Those accessors still work fine. – Paul Razvan Berg Jul 26 '20 at 14:10