I need a little guidance. I've been structuring my code like this:

#include <eosio/eosio.hpp>

class [[eosio::contract("table")]] Square {
    struct [[eosio::table]] square {
        uint64_t id;
        uint16_t width, height;
        uint64_t primary_key() const {
            return id;
    eosio::multi_index<eosio::name("square"), square> t;
    eosio::name _self;

    uint16_t width, height;

    Square(eosio::name code)
        : _self(code)
        , t(code, code.value)

    Square(eosio::name code, uint64_t id) 
        : Square(code)
        auto i = t.find(id);
        if (i != t.end()) {
            width = i->width;
            height = i->height;

    void make(uint16_t width, uint16_t height)
        t.emplace(_self, [&](auto &r) {
            r.width = width;
            r.height = height;

which allows me to create a contract using the above class like this:

namespace eosio {
    class [[eosio::contract("table")]] token : public contract {
        token(name receiver, name code, datastream<const char*> ds) 
            : eosio::contract(receiver, code, ds) 

        void make(uint16_t w, uint16_t h) {
            Square sq(_self);
            sq.make(w, h);

        void get(uint64_t id) {
            Square sq(_self, id);
            print("width = ", sq.width, ", height = ", sq.height);

you'll notice that the Square class is decorated as a table. this is so the ABI generator picks up my multi_index declaration (if there's a better way to do this I'm all ears)

now, my question: in the Square class I have to replicate the contents of the private struct square such that they become accessible to the caller. I would like to avoid this redundancy as it is cumbersome and will lead to errors stemming from failure to keep the two synchronised

if I declared the class itself as an EOS table (flattening the structure), then I'd be writing to the table attributes that properly belong to the class but not to the table. so that doesn't seem like a good alternative. additionally, the multi_index declaration would have to be made within the struct, which I believe would be a problem

what is a better way to do this?

  • you can define a struct square variable in your Square class:private square v; v=t.get(i);then you can access the square variable – Jimmy Guo Nov 20 '19 at 13:55
  • sq.contents.width? ja... it's just cumbersome – ekkis Nov 21 '19 at 21:56
  • if you don't like this, try square sq = Square(_self, id).get() – Jimmy Guo Nov 22 '19 at 7:49

Your Answer

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

Browse other questions tagged or ask your own question.