Code has been added to clipboard!
Solidity Inheritance Example 1
Example
pragma solidity ^0.4.0;
contract ownedContract {
function ownedContract() { ownerAddress = msg.sender; }
address ownerAddress;
}
// The keyword "is" is used to for deriving from another contract. Derived
// contracts are able to access every non-private member which includes
// internal functions as well as state variables. However, those members
// cannot be accessed from outside using `this`.
contract mortalContract is ownedContract {
function killOwner() {
if (msg.sender == ownerAddress) selfdestruct(ownerAddress);
}
}
// These abstract contracts are only provided to make the
// interface known to the compiler. Note the function
// without body. If a contract does not implement all
// functions it can only be used as an interface.
contract Config {
function lookup(uint id) returns (address adr);
}
contract RegisterName {
function register(bytes32 name);
function unregister();
}
// Multiple inheritance is viable too. Keep in mind that "ownedContract" is
// a base class of "mortalContract", but there is only one
// instance of "ownedContract" (in the case of virtual inheritance in C++).
contract named is ownedContract, mortalContract {
function named(bytes32 name) {
Config config = Config(0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970);
RegisterName(config.lookup(1)).register(name);
}
// It is possible to override a function by another function with the same name and
// the same types/number of inputs. Wheb the overriding function has any
// differing types of output parameters, which will cause an error.
// Message-based and local function calls both take overrides like this
// into account.
function killOwner() {
if (msg.sender == ownerAddress) {
Config config = Config(0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970);
RegisterName(config.lookup(1)).unregister();
// It is still possible to call a specific
// overridden function.
mortalContract.killOwner();
}
}
}
// When an argument is taken by a constructor, it would have to be
// inside the header (or at the derived contract's
// constructor in modifier-invocation-style (as shown below)).
contract FeedPrice is ownedContract, mortalContract, named("GoldenFeed") {
function infoUpdate(uint infoNew) {
if (msg.sender == ownerAddress) info = infoNew;
}
function getInfo() constant returns(uint r) { return info; }
uint info;
}