Creating array of pointers to class object

假装没事ソ 提交于 2019-12-07 09:23:00

问题


Question:

Create an array of at least four pointers to Reader objects. Use the New operator to create at least four pointers to derived class objects and assign them to the array.

I'm not sure If I did it right or not.

Reader is the base class. John, David, Daniel, Mark are the derived class

int main(void)
{
     Reader *obj[4];

    obj[0] = new John();
    obj[1] = new David();
    obj[3] = new Daniel();
    obj[2] = new  Mark();

}

Would this be right???


回答1:


Your code is correct.

And as @sharptooth suggested, make a practice of delete on the allocated obj[]s. In C++ new allocates memory and delete deallocates.



来源:https://stackoverflow.com/questions/6212206/creating-array-of-pointers-to-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!