0

In my contract I have a data structure that involves a node struct and a LeafNode and InnerNode struct that inherit from node.

struct node {
        ...
        virtual string to_string() const {

            string str("node");

            ...

            return str;
        }
    };
struct LeafNode : public node {
        ...
        virtual string to_string() const {

            string str("LeafNode");

            ...

            return str;
        }
    };
struct InnerNode : public node {
        ...
        virtual string to_string() const {

            string str("InnerNode");

            ...

            return str;
        }
    };

Assuming I have an initialized node* nodeptr;:

When calling eosio::print(nodeptr->to_string());, I want it to call the child's to_string() method if the nodeptr is holding a LeafNode or InnerNode struct instead of just calling the base node::to_string() method.

In vanilla C++, this can be done using the virtual keyword. However, after adding it to my struct methods as shown above, I run into the following error:

Error 3070002: Runtime Error Processing WASM
Error Details:
eos-vm system failure
pending console output: ...

Is this because the virtual keyword is not allowed in EOSIO C++? Or is there something else going on here?

0

You are using virtual keyword incorrectly. Please, refer to this and this for better understanding.

The virtual specifier specifies that a non-static member function is virtual and supports dynamic dispatch.

If you would like to override node::to_string() method. You have to:

  1. create a method with same signature in child class
  2. initialize a pointer of parent type as the child type
  3. call the method

In other words it should look like this:

struct node {
         virtual string to_string() const {
             string str("node");
             return str;
         }
};

struct LeafNode : public node {
        string to_string() const {
            string str("LeafNode");
            return str;
        }
};

Then initialize pointer as:

node* ptr;
LeafNode leaf;
ptr = &leaf;

And call method:

ptr->to_string();
2
  • So you are saying to remove virtual from child method signatures? That leads to the same error Jul 2 at 16:42
  • Yes, that's what I was suggesting
    – redCuckoo
    Jul 2 at 16:45

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.