1

In an oop language, I could do the following:

I can define an interface Foo with a function F(). I then define two classes Bar1 and Bar2 implementing this interface. I can then create an array of Foo called say fooArray. I can then call F in any element without knowing if it is Bar1 or Bar2.

I want to do the same in solidity (within a different contract FooBar), or something similar. Is that possible? Would I then create an array of interfaces and fill it with different contracts? Would that mean every contract will get its own address? That seems a bit unnecessary since I only need to access the contracts via the array, not via their addresses, ie I want the array to behave as much as possible like an array of instances of classes in oop.

0

Yes it is possible, yes every contract has it's own address, but think about it like a memory reference rather than simply a direct call to an address. Here's an example:

pragma solidity ^0.4.0;

interface Letter {
    function f() 
        public 
        returns (uint);
}

contract A is Letter {
    function f() 
        public 
        returns (uint) {
        return 1;
    }
}

contract B is A {
}

contract C is Letter {
    function f() 
        public 
        returns (uint) {
        return 2;
    }
}

contract Alphabet {
    Letter[] letters;

    event printer(uint);

    // Add our own new contracts
    function Alphabet() 
        public {
        letters.push(new A());
        letters.push(new B());
        letters.push(new C());
    }

    // Include existing contracts
    function alphabetFromAddresses(address _addrA, address _addrB, 
                                   address _addrC)
        public{
        letters.push(A(_addrA));
        letters.push(B(_addrB));
        letters.push(C(_addrC));
    }

    function getLetters() 
        public {
        for(uint i = 0; i < letters.length; i++) {
            printer(letters[i].f());
        }
    }
}

You can add your own new instances which all get assigned their own contract addresses on creation, you can also reference existing contracts as long as they are implementations of your contracts or interfaces.

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.