user1135541
user1135541

Reputation: 1891

Class Interface functionality

If I have the following code:

class A_Interface {
 public:
    virtual void i_am_a() = 0;
};
class A : public A_Interface {
 public:
    void i_am_a() {printf("This is A\n");}
};

class B_interface {
 public:
    virtual void i_am_b() = 0;
    // would like to run i_am_a()
};
class B : public A, public B_interface {
 public:
    void i_am_b() {printf("This is B\n");}
};

int main() {
    B BO;
    B_interface* BI = &BO;

    BI->i_am_b();
    // ******* WOULD LIKE TO RUN THE FOLLOWING ********
    BI->i_am_a();
}

What are my options to be able to run the class A member function from B_Interface Pointer?

I know that it is possible for B_interface to inherit A_interface as:

class B_Interface : virtual public A_interface ...

class A : virtural public A_Interface ...

But that makes it impossible using GMOCK to the best of my knowledge to mock class B. What are my options?

Thanks...

Upvotes: 0

Views: 61

Answers (2)

user1135541
user1135541

Reputation: 1891

OK, I was wrong, again :(. So here is the answer code can be like this:

class A_Interface {
 public:
    virtual void i_am_a() = 0;
};

class A : virtual public A_Interface {
 public:
    void i_am_a() {printf("This is A\n");}
};

class B_Interface : virtual public A_Interface {
 public:
    virtual void i_am_b() = 0;
    // would like to run i_am_a()
};

class B : public A, public B_interface {
 public:
    void i_am_b() {printf("This is B\n");}
};

GMock can be like this:

class MockB : public B_Interface, public MockA {
    MOCK_METHOD0(foo, int(int));
}

This works for me in real application, but seems a little messy.

Upvotes: 0

M.M
M.M

Reputation: 141544

Inside class B_interface have:

void i_am_a()
{
     // throws if the object does not actually have A as a base
     dynamic_cast<A &>(*this).i_am_a();
}

Upvotes: 1

Related Questions