Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Overloading of Solidity syntax, what is the definition of inheritance

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "overloading of Solidity grammar, what is the definition of inheritance". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1 Summary

Ethernet intelligent contract language Solitidy is an object-oriented language.

2 contract description

Solidity contracts are similar to classes in object-oriented languages. There are state variables for data persistence and functions that can be modified in the contract. When the function of another contract instance is called, an EVM function call is executed, which changes the context of the execution so that the state variable of the previous contract cannot be accessed.

Object-oriented (Object Oriented,OO) language has three major features: encapsulation, inheritance, polymorphism, and Solidity language also has three features.

The three major features of the object-oriented language are explained as follows:

Encapsulation (Encapsulation)

Encapsulation is to encapsulate objective things into abstract classes, and classes can only let trusted classes or objects operate their own data and methods, and hide information from untrusted ones. A class is a logical entity that encapsulates data and the code that manipulates it. Within an object, some code or data can be private and cannot be accessed by the outside world. In this way, objects provide different levels of protection to internal data to prevent unrelated parts of the program from accidentally changing or misusing the private parts of the object.

Inheritance (Inheritance)

Inheritance is a method that allows an object of one type to obtain the properties of an object of another type. It supports the concept of classification by level. Inheritance is the ability to use all the functionality of an existing class and extend it without rewriting the original class. New classes created by inheritance are called "subclasses" or "derived classes", and inherited classes are called "base classes", "parent classes", or "superclasses". The process of inheritance is from the general to the special. Inheritance can be implemented through "Inheritance" and "Composition". There are two ways to implement the concept of inheritance: implementation inheritance and interface inheritance. Implementation inheritance refers to the ability to directly use the properties and methods of the base class without additional coding; interface inheritance refers to the ability to use only the names of properties and methods, but subclasses must provide implementation.

Polymorphism (Polymorphism)

Polymorphism means that the same method of a class instance has different forms in different situations. Polymorphic mechanism enables objects with different internal structures to share the same external interface. This means that although specific operations are different for different objects, they (those operations) can be invoked in the same way through a common class.

Also explain overloading and rewriting.

Overloading (Override) is a form of polymorphism, is the interior of a class, multiple parameters in the method, depending on the number of input parameters, will return different results.

Overwrited, which is a method in which a subclass inherits the parent class and overrides the parent class. Polymorphism is a technique that allows you to set a parent object to be equal to one or more of its children, and after assignment, the parent object can operate differently according to the properties of the child object currently assigned to it. To put it simply, it is a sentence that allows pointers of subclass types to be assigned to pointers of parent class types. Polymorphism in both Object Pascal and C++ is through virtual functions.

3 function overloading (Override)

A contract can have a function of the same name with multiple different parameters. This also applies to inheriting functions. The following example shows the overloaded function f in contract A.

Pragma solidity ^ 0.4.16 th contract A {function f (uint _ in) public pure returns (uint out) {out = 1;} function f (uint _ in, bytes32 _ key) public pure returns (uint out) {out = 2;}}

Overloaded functions also exist in the external interface. If two externally visible functions are distinguished only from the types within the Solidity rather than their external types, it will cause an error.

/ / the following code fails to compile pragma solidity ^ 0.4.16 th contract A {function f (B _ in) public pure returns (B out) {out = _ in;} function f (address _ in) public pure returns (address out) {out = _ in;}} contract B {}

Both of the above f function overloads accept the address type of ABI, although they are considered different in Solidity.

3.1 overload parsing and parameter matching

You can choose to overload the function by matching the function declaration in the current scope with the parameters provided in the function call. If all parameters can be implicitly converted to the expected type, select the function as the overload candidate. If there are no candidates, the parsing fails.

Pragma solidity ^ 0.4.16 th contract A {function f (uint8 _ in) public pure returns (uint8 out) {out = _ in;} function f (uint256 _ in) public pure returns (uint256 out) {out = _ in;}}

Calling f (50) results in a type error because 50 can be implicitly converted to either uint8 or uint256. Calling f (256), on the other hand, resolves to f (uint256) overloading, because 256 cannot be implicitly converted to uint8.

Note: the returned parameters are not used as the basis for overloaded resolution.

4 inheritance

Solidity supports multiple inheritance by copying code that includes polymorphism.

All function calls are virtual, which means that the farthest derived function will be called unless the contract name is explicitly given.

When a contract inherits from multiple contracts, only one contract is created on the block chain, and the code of all base class contracts is copied into the created contract.

In general, Solidity's inheritance system is very similar to Python's inheritance system, especially in terms of multiple inheritance.

The following example is explained in detail.

Pragma solidity ^ 0.4.16 alternate contract owned {function owned () {owner = msg.sender;} address owner;} / / derives from another contract using is. Derived contracts can access all non-private members, including internal functions and state variables, but cannot be accessed externally through this. Contract mortal is owned {function kill () {if (msg.sender = = owner) selfdestruct (owner);}} / / these abstract contracts are used only to provide interfaces to compilers. / / Note that the function has no function body. / / if a contract does not implement all the functions, it can only be used as an interface. Contract Config {function lookup (uint id) public returns (address adr);} contract NameReg {function register (bytes32 name) public; function unregister () public;} / / can have multiple inheritance. Note that owned is also the base class for mortal, / / but there is only one instance of owned (just like virtual inheritance in C++). Contract named is owned, mortal {function named (bytes32 name) {Config config = Config (0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970); NameReg (config.lookup (1)) .register (name);} / / function can be overloaded by another function with the same name and the same number / type input. / / if the overloaded function has different types of output parameters, it will cause an error. / / both local and message-based function calls take these overloads into account. Function kill () public {if (msg.sender = = owner) {Config config = Config (0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970); NameReg (config.lookup (1)). Unregister (); / / you can still call specific overloaded functions. Mortal.kill ();} / / if the constructor accepts arguments, / / it needs to be provided when declaring (the constructor of the contract), / / or in the modifier invocation style at the constructor location of the derived contract (see below). Contract PriceFeed is owned, mortal, named ("GoldFeed") {function updateInfo (uint newInfo) public {if (msg.sender = = owner) info = newInfo;} function get () public view returns (uint r) {return info;} uint info;}

Notice that in the above code, we call mortal.kill () to "forward" the destruction request. This is problematic, as can be seen in the following example:

Pragma solidity ^ 0.4.0X contract owned {function owned () public {owner = msg.sender;} address owner;} contract mortal is owned {function kill () public {if (msg.sender = = owner) selfdestruct (owner);} contract Base1 is mortal {function kill () public {/ * cleanup operation 1 * / mortal.kill ();} contract Base2 is mortal {function kill () public {/ * cleanup operation 2 * / mortal.kill () }} contract Final is Base1, Base2 {}

Calling Final.kill () calls the farthest derived overload function, Base2.kill, but bypasses Base1.kill, mainly because it doesn't even know that Base1 exists. The solution to this problem is to use super:

Pragma solidity ^ 0.4.0X contract owned {function owned () public {owner = msg.sender;} address owner;} contract mortal is owned {function kill () public {if (msg.sender = = owner) selfdestruct (owner);} contract Base1 is mortal {function kill () public {/ * cleanup operation 1 * / super.kill ();} contract Base2 is mortal {function kill () public {/ * cleanup operation 2 * / super.kill () }} contract Final is Base1, Base2 {}

If Base2 calls a function of super, it will not simply call the function on its base class contract. Instead, it calls this function in the next base class contract of the final inheritance graph, so it calls Base1.kill () (note that the final inheritance sequence is-- starting with the farthest derived contract: Final, Base2, Base1, mortal, ownerd). The actual function called with super in the class is unknown in the context of the current class, although its type is known. This is similar to a common virtual lookup.

4.1 parameters of the base class constructor

The derived contract needs to provide all the parameters required by the base class constructor. This can be done in two ways:

Pragma solidity ^ 0.4.0X contract Base {uint x; function Base (uint _ x) public {x = _ x;}} contract Derived is Base (7) {function Derived (uint _ y) Base (_ y * _ y) public {}}

One method calls the base class constructor (is Base (7)) directly in the inheritance list. Another way is to use the modifier modifier as part of the definition header of the derived contract constructor (Base (_ y * _ y)). If the constructor argument is constant and defines or describes the behavior of the contract, it is convenient to use the first method. If the parameters of the base class constructor depend on the derived contract, you must use the second method. If, as in this simple example, both are used, the modifier modifier-style parameters are preferred.

4.2 multiple inheritance and linearization

There are several problems that need to be solved to realize multiple inheritance in programming language. One problem is the diamond problem. Solidity borrows from Python's approach and uses "C3 linearization" to force a DAG (directed acyclic graph) made up of base classes to maintain a specific order. This is ultimately reflected as the only result we want, but it also makes some ways of inheritance invalid. In particular, the order of the base classes after is is important. In the following code, Solidity gives an error like "Linearization of inheritance graph impossible".

/ / an error occurred in the compilation of the following code pragma solidity ^ 0.4.0X {} contract An is X {} contract C is A, X {}

The reason for the code compilation error is that C requires X to rewrite A (because the order defined is A, X), but An itself requires X to rewrite X, which cannot resolve this conflict.

You can remember by a simple rule: specify all base classes in the order from "nearest base class" (most base-like) to "farthest inheritance" (most derived).

4.3 inherit different types of members with the same name

This is considered an error when inheritance results in a contract with a function and modifier modifier with the same name. It is also considered an error when the event has the same name as the modifier modifier, or when the function has the same name as the event. With one exception, the getter of a state variable can override a public function.

This is the end of the content of "overloading of Solidity grammar, what is the definition of inheritance". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report