views:

100

answers:

3

These are functions and Struct declarations I have, and I'm not allowed to change them.

DerivedA giveDerivedA ();
DerivedB giveDerivedB ();

struct Base{
    QString elementId;
    QString elementType;
};

struct DerivedA : Base {
    int a;
    int b;
};

struct DerivedB : Base {
    int c;
    int d;
};

But what I need is something like this:

struct DerivedA : Base {
    int a;
    int b;
    void create();
    QString doc;
};

How can I add these method and member to structs I got?

My first idea is:

struct myA: DerivedA {
    void create();
    QString doc;
};

Do you have any suggestion?

Edit: 2nd Alternative(Choosed)

struct myA{
    void create();
    QString doc;
    private:
      DerivedA derivedA;
};
+1  A: 

That ain't workin', that's the way you do it.

Noah Roberts
+1  A: 

This is similar to the problem people have extending standard library classes. If your base class doesn't have a virtual destructor, you can't safely inherit from it. In that case, you must either use free-functions (preferred anyway), or composition.

Otherwise, what you have there is good.

GMan
Base class doesn't have a virtual constructor, what is the problem with inheritance in such a case?
metdos
@metdos: If you have: `struct base {}; struct derived : base {};` Then: `base* x = new derived;` becomes undefined behavior with `delete x;`. If you delete a derived type through a base pointer, the base type must have a virtual destructor. This is why you cannot inherit from (most) standard library classes.
GMan
Thanks, I see now.
metdos
@GMan: I think you meant virtual destructor in your answer and not virtual constructor?
Naveen
@Naveen: :x Why yes.
GMan
+1  A: 

Use composition or inheritance, depending on what kind of relationship the classes have (see e.g. Items 32 and 38 in Effective C++).

Philipp
Thanks, I liked "is-implemented-in-terms-of".
metdos