1
votes
  1. class A has a pure virtual method read()
  2. class B has an implemented virtual method read()
  3. I have a class C that inherits A and B
  4. Can this happen?

What I'm trying to achieve is that the two base classes A and B complement each other.

So C read() method would actually call class B read()

class A {
    virtual int get_data() = 0;

    void print() {
        log(get_data());
    }
}

class B {
    virtual int get_data() {
        return 4;
    }
}

class C : public A, public B {

}
C my_class;
my_class.print(); // should log 4;

I'm not on my computer nor will have opportunity in the next couple of weeks so I can't test this... but I'm designing the architecture and needed to know if this is possible and if not.. how can this be accomplished!

1
Not an answer to your question, but there are many online compilers you can use to check things like this: coliru.stacked-crooked.com (I'm not saying you're wrong for asking, just mentioning)Tas
well it doesn't compile in the online compiler you posted.. if this is not allowed then how can I do something like this?xDGameStudios
@xDGameStudios when something doesn't compile, you should read the error message.eerorika
@eerorika I read the error message!xDGameStudios

1 Answers

2
votes

Can multiple base classes have the same virtual method?

  1. Can this happen?

Yes.

So C read() method would actually call class B read()

That doesn't happen automatically. A member function of base doesn't override a function of an unrelated base.

You can add an override to C:

class C : public A, public B {
    int get_data() override;
}

This overrides both A::get_data and B::get_data. In order to "actually call class B read()", you can indeed make such call:

int C::get_data() {
    return B::get_data();
}

Or... that would be possible if you hadn't declared B::get_data private.


Overriding a function in another base without explicitly delegating in derived is possible if you change your hierarchy a bit. In particular, you need a common base, and virtual inheritance:

struct Base {
    virtual int get_data() = 0;
};

struct A : virtual Base {
    void print() {
        std::cout << get_data();
    }
};

struct B : virtual Base {
    int get_data() override {
        return 4;
    }
};

struct C : A, B {};