user246100
user246100

Reputation: 670

Share functionality of a class between two or more libraries with pure virtual functions

It's ok,

having:

class A
{
    virtual x() = 0;
    virtual y() = 0;
}

class B
{
    virtual x() = 0;
    virtual z() = 0;
}

class C : A , B
{
    x();
    y();
    z();
}

to share instances of class C with two libraries whose one knows only of A and another knows only of B?

Like:

Library 1:

#include <a>

A* a = function_in_the_core_that_creates_a_C_and_retrieves_it();
a->x();
a->y();

Library 1:

#include <b>

B* b = function_in_the_core_that_creates_a_C_and_retrieves_it();
b->x();
b->z();

I'm asking this because I wonder if the compiler will have problems to resolve the functions since the libraries don't have a full knowledge of the ancestry of C.

EDIT:

function_in_the_core_that_creates_a_C_and_retrieves_it() is supposed to return a C* not a C. I thought that that was clear since we are talking about virtual functions.

Upvotes: 0

Views: 74

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254471

As it stands, no. You're calling the same function in both cases; the only way that can work is for it to return C*. Than can only be converted to A* or B* if the definition of C is known (and it would also require the inheritance to be public).

If you have two separate functions, one returning A* and one returning B*, then that will be fine. Each base-class subobject contains enough information for virtual dispatch and RTTI to work correctly, without knowledge of the object's dynamic type.

Upvotes: 1

Dervall
Dervall

Reputation: 5744

You really should make the code compile. C is privately inheriting A and B, so this example isn't going to run. class C : public A , public B is the corrected declaration for C. You are also missing return types for the functions.

Either function_in_the_core_that_creates_a_C_and_retrieves_it will return a B*, which will then conform to the full ancestry of B and work as a B for all intents and purposes - or it will return a C*, in which case you will have to provide a full declaration of C in order for the assignment to work without an explicit cast. You cannot have C just forward declared to do this.

So, you're either returning a pointer to B in which case there is no problem - or a pointer to C where you will need to provide full ancestry in order to make the assignment without a potentially dangerous cast.

Upvotes: 1

Related Questions