Sunday, August 2, 2009

New statement in C++?

I have a test tomorrow where I have to insert a new statement into a class given to get the program to work. Basically if I get it to work I do well and get an A if I don't then I don't pass the class. I'm really stressed out and I understand pointers and somewhat classes. Can anyone demonstrate how you would use a new statement in classes?

New statement in C++?
I assume by inserting a "new statement" you mean using the operator 'new', not simply adding a statement that wasn't there before. You also say you need to add this statement to get the program to work. Not knowing why it's not working it's hard to say what needs to be done to make it work. However, I can give you an example of how and why you would use 'new' in a class.





In the simple example below, the class Array has a private attribute that is a pointer to some type, intended to be used to point to an array of objects of that type. In order to get the memory allocated that I need for the array, I use 'new' in the constructor.





So, I'm guessing that in your test, you'll encounter a similar situation. The class will have an attribute that is a pointer to something, and you'll use 'new' in the constructor to allocate the memory you need. Good luck!





#include %26lt;iostream%26gt;





using namespace std;





template %26lt;class T%26gt;


class Array {


public:


Array%26lt;T%26gt;() : _len(0), _a(NULL) { }


Array%26lt;T%26gt;(unsigned len) : _len(len) {


_a = new T [len];


}


unsigned len() { return _len; }


T%26amp; operator[](unsigned x) {


assert ((_a != NULL) %26amp;%26amp; (x %26lt; _len) %26amp;%26amp; (_len %26gt; 0));


return _a[x];


}


~Array%26lt;T%26gt;() { delete [] _a; }


private:


unsigned _len;


T *_a;


};





int main(int argc, char *argv[]) {


Array%26lt;int%26gt; A(5);





// Initialize


for (unsigned i = 0; i %26lt; A.len(); i++) {


A[i] = i;


}





// Print


for (unsigned i = 0; i %26lt; A.len(); i++) {


cout %26lt;%26lt; A[i] %26lt;%26lt; " ";


}


cout %26lt;%26lt; endl;





// Test out of range check


A[99] = 99;





return 0;


}


No comments:

Post a Comment