Click here to Skip to main content
11,428,497 members (66,462 online)

momond19 asked:

Open original thread
Hi,
I have a class MyClass which implements an interface MyInterface:
class MyInterface {
public:
   virtual void myFunction () = 0;
};
 
class MyClass : public MyInterface {
public:
    MyClass ();
    virtual ~MyClass ();
    void myFunction ();
};
Now I want to make a dynamic array of MyClass objects.
My first attempt was:
MyInterface *a;
a = new MyClass[n];
for (int i=0; i<n; i++) {
    a[i].myFunction ();
}
which failed at runtime for n > 1.

So I come to a possible solution like this:
(A)
MyInterface **a;
a = new MyInterface*[n];
for (int i=0; i<n; i++) {
    a[i] = new MyClass ();
    a[i] ->myFunction ();
}
The problem with this solution is that when I want to reclaim the used resources with:
for (int i=0; i<n; i++) {
    delete a[i];
}
delete []a;
it really takes a long time, if compared to:
(B)
MyClass *a;
a = new MyClass[n];
for (int i=0; i<n; i++) {
    a[i].myFunction();
}
delete []a;

I notice that allocating with (A) takes a lot more memory than (B), anyone can explain this?

Thanks.
Tags: C++

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).



Advertise | Privacy | Mobile
Web03 | 2.8.150428.2 | Last Updated 26 Mar 2009
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100