I came across the super keyword in Solidity in the context of overriding functions. What does it do?
Asked
Active
Viewed 2.6k times
36
Pavel Fedotov
- 139
- 6
SCBuergel
- 8,774
- 7
- 38
- 69
1 Answers
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();
}
}
SCBuergel
- 8,774
- 7
- 38
- 69
superwould 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:59B.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:58contract C is Ddoes not mean thatsuperin context ofCcan be guaranteed to beD. – Kyle Baker Apr 08 '22 at 14:29