Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

c++ - How to add derived class objects to an array of base class type?

unfortunately, I can't use std::vector and have to use plain C++ arrays. I got the following code:

class Base
{

}

class DerivedCar : Base
{
public:
    DerivedCar(int a) a(a) {};
private:
    int a;
}

class DerivedHouse : Base
{
  public:
    DerivedHouse(float b) b(b) {};
private:
    float b;  
}

class Vector
{
    Vector() :
    index(0)

    void add(const DerivedCar& car)
    {
       vec[index] = new DerivedCar(car.a);
       index++;
    }

    void add(const DerivedHouse& house)
    {
       vec[index] = new DerivedHouse(house.b);
       index++;
    }

private:
    Vector vec[100];
    int index;
}

int main()
{
    Vector vector;
    DerivedCar car(100);
    DerivedHouse house(2.f);

    vector.add(car);
    vector.add(house);
}

I would like to have an array of type Base and add objects of a derived type. Is there a better approach to this other than the way I did? What would be the best way to keep copying of objects at a minimum.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to add derived class objects to an array of base class type?

You can not put derived class objects into raw array or std::vector of base class because the derived class objects are usually larger and so simply do not fit there.

Is there a better approach to this other than the way I did?

Better approaches are certainly out there. One good example of such containers with polymorphic elements is boost::base_collection. Read its documentation and its source code. If you do not understand some detail in it then ask about that detail in Stack Overflow.

What would be the best way to keep copying of objects at a minimum.

Containers that only contain pointers to objects and intrusive containers keep copying of objects at minimum. However such containers do not manage the objects and so responsibility of objects life time has to be taken by something outside.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...