Re: Reallocating arrays of classes

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance




Nigel in the aerospace buisness wrote:
How do I resize an array of classes which have been allocated using new in
Visual c++ 6
class MyClass
{
public:
};

int main()
{
MyClass *pMyClass = new MyClass[5];
pMyClass = (MyClass*)realloc(pMyClass,7 * sizeof MyClass);
delete [] pMyClass;
}

This doesn't work
Thanks

You can't. The only way to modify an array's size is to create it.
An array has a constant size and thats guarenteed.
And you don't need new / delete to prove that.

int main()
{
MyClass arrayfive[5];
MyClass arrayten[10];
for(size_t i = 0; i < 5 ; ++i)
{
arrayten[i] = arrayfive[i];
}
}

Have you looked at std::vector? Its an array on steroids, or rather -
to be politically correct, on vitamins.

#include <vector>

int main
{
std::vector< MyClass > myvec(10); // container now has 10 elements,
all def constructed
MyClass instance;
myvec.pushback( instance ); // 11
myvec.pushback( instance ); // 12

return 0;
} // 12 elements and one container destroyed automatically

And if your class had a parametized ctor, say an integer, you could
create 100 MyClass dynamic elements all with a member integer set to 99
with one line:

std::vector< MyClass > vec(100, 99); // automatically deallocated

Can you say priceless?

.



Relevant Pages

  • Re: This I simply cant swallow
    ... encapsulation and abstract data types are completely orthogonal ... int i; ... MyClass i; //An instance of MyClass ... An ADT is a type that cannot, itself, be instantiated. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Why this fix work ?
    ... "int" is 32 bits wide. ... This is basically a matter of luck -- bad luck that it works at ... MyClass* myobj; ... "MyClass *", which is actually 64 bits wide. ...
    (comp.lang.c)
  • Re: Class Destroys itself straight away!
    ... CRectangle; ... int area ... MyClass mc = MyClass; ... void MyClass::SayHello ...
    (microsoft.public.vc.language)
  • Re: Explicit function vs. overloaded operator?
    ... > void operator() (int x, ... The conceptual advantage is that if class MyClass does just one thing, ... make the code easier to read. ...
    (comp.lang.cpp)
  • Re: Template collection classes
    ... But it also says as it's true, that we quite always use Reference as ... void Func(int x) ... MyClass(): x ... you will read the message "MyClass copy ctor ...
    (microsoft.public.vc.mfc)