2

I come from a C++ background. A nice feature in C++ is pure virtual functions which allow one to create an interface that imposes on any derived class to force it to implement a function. For example, these this code:

class A {
public:
    A() {}
    virtual void aFunction(void) { printf("Hello"); }
    virtual void bFunction(void) = 0;
};

class B : public A {
public:
    B() : A() {}
};

does not compile because B does not implement bFunction, but this version of B does compile:

class B : public A {
public:
    B() : A() {}
    virtual void bFunction(void) { printf("B"); }
};

Are these features (inheritance, virtual functions, and especially pure virtual functions) available in Solidity? Is there any discussion to add them?

2

Yes. You can do the same with abstract contracts: they are contracts that implements some functions and they only declare others, so those functions must be implemented by child contract. You can also define interfaces, where you can't implement any function.

From the official documentation about abstract contracts and interfaces:

Abstract Contracts Contract functions can lack an implementation as in the following example (note that the function declaration header is terminated by ;):

pragma solidity ^0.4.0;

contract Feline {
    function utterance() returns (bytes32);
}

Such contracts cannot be compiled (even if they contain implemented functions alongside non-implemented functions), but they can be used as base contracts:

pragma solidity ^0.4.0;

contract Feline {
    function utterance() returns (bytes32);
}

contract Cat is Feline {
    function utterance() returns (bytes32) { return "miaow"; }
}

If a contract inherits from an abstract contract and does not implement all non-implemented functions by overriding, it will itself be abstract.

You can follow also some discussion here

  • Oh. This is great. So this works exactly as one would expect (but in c++ you can explicitly state in the interface that an implementation is needed). Nice. Thanks. – Thomas Jay Rush Aug 28 '17 at 13:21
  • It's weird that the docs say abstract contracts cannot be "compiled". Certainly they get compiled so that they can be used. – Justin Harris Jan 23 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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