Shay
Shay

Reputation: 693

inherit from two classes in c++ and inserting into list

Is the following code problamatic regarding inserting into a list an object that inherits from two classes?

class A
{
}

class B
{
}

class C : public A, public B
{

}

C *myObj = new C();
std::list<A*> myList;
myList.push_front(myObj);

Is creating a list of type A and inserting an object of type C which is part of type B problematic? I know this code compiles but I am affrade of memory issues. If its a problem, what other options do I have to solve this?

Upvotes: 3

Views: 68

Answers (2)

Mihai Bişog
Mihai Bişog

Reputation: 1018

Technically, as long as you add references or pointers of the objects to the list in order to avoid slicing and have virtual destructors you should be safe.

You could think of A and B as being interfaces to the polymorphic type. Take a look at this example:

class Drawable
{
    public:
        virtual ~Drawable() { }
        virtual void draw();
};

class Circle : public Drawable
{
    public:
        void draw() { std::cout << "Drawing a circle\n"; }
}

class Square : public Drawable
{
    public:
        void draw() { std::cout << "Drawing a square\n"; }
}

int main()
{
    std::list<Drawable*> shapeList { new Square(), new Circle(), new Square() };
}

Upvotes: 0

Voo
Voo

Reputation: 30216

As long as the list stores the data by reference or pointer and the destructor is virtual you're fine.

The basic problem is that you are not allowed to store a C into a variable of A, but you can store it into A& or A*. So A a = C() would be just as bad as storing a C into a list<A> or vector<A>. This would lead to slicing

Upvotes: 3

Related Questions