Re: Reallocating arrays of classes
- From: pj_hern@xxxxxxxxx
- Date: 19 Oct 2006 16:06:31 -0700
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?
.
- Prev by Date: Re: transmitFile() function
- Next by Date: Re: C++ with VS.NET and Twilight of the Microsoft Era
- Previous by thread: Re: Reallocating arrays of classes
- Next by thread: Re: Circular DLL dependencies
- Index(es):
Relevant Pages
|