Defining C++ Interfaces

I have the following problem with defining an interface for a certain class. This is how my final classes look like:

class msg {
};

class statusmsg : public msg {
};

class valuemsg : public msg {
};

Now I need interfaces for the statusmsg and the valuemsg classes, but these interfaces also need to know the functions of the msg base class. I tried something like this.

Interfaces:

class i_msg {
    virtual void do_something() = 0;
};

class i_statusmsg : public virtual i_msg {
    virtual void do_something_else() = 0;
};

Final class definitions:

class msg : public i_msg {
    void do_something() {
        std::cout << "foo" << std::endl;
    }
};

class statusmsg : public i_statusmsg {
    void do_something_else() {
        std::cout << "bar" << std::endl;
    }
};

Now I can't create an instance of statusmsg because the compiler tells me that do_something() is not implemented. Is there a way to get this working?

Thanks in advance.

SOLUTION

Ok, I found a solution to this the problem is to place the virtual keyword correctly when inheriting. Here is the example code:

class i_msg {
public:
    virtual void do_something() = 0;
};

class i_statusmsg : public virtual i_msg {
public:
    virtual void do_something_else() = 0;
};

class msg : public virtual i_msg {
public:
    virtual void do_something() {
        std::cout << "foo" << std::endl;
    }
};

class statusmsg : public i_statusmsg, public msg {
public:
    virtual void do_something_else() {
        std::cout << "bar" << std::endl;
    }
};

Answers


Your statusmsg isn't valid as it doesn't implement the pure virtual method do_something() from i_msg.

To get around this you can put an empty method declaration into statusmsg like so:

class statusmsg : public i_statusmsg {
    virtual void do_something_else();
    virtual void do_something() {};
};

As you have done, final classes should be:

class msg : public virtual i_msg {
    void do_something() override {
        std::cout << "foo" << std::endl;
    }
};

class statusmsg : public /*virtual*/ i_statusmsg, public msg {
    void do_something_else() override {
        std::cout << "bar" << std::endl;
    }
};

But it seems you have to rethink your design to avoid multiple inheritance.


Need Your Help

Append text to column data in PostgreSQL if columns initial value is null

postgresql

Append text to column data in PostgreSQL if columns initial value is null.

adding custom code to jquery answer

javascript jquery html css

I have a form which inputs values like this