11/14/2013: Code Examples
class MyClass {
public:
MyClass() {}
MyClass(int x, int y) : a(x), b(y) {}
int a, b;
};
void main() {
MyClass *a = new MyClass[2];
{
a[0] = MyClass(1, 2);
}
cout << a[0].a << " " << a[0].b << endl;
delete [] a;
}
·
In
the above, the yellow highlighted code works perfectly, but requires the construction
of a temporary object, and assign to a[0]
·
In
C++, we typically do something like:
class MyClass {
public:
MyClass() {}
MyClass(int
x, int y) : a(x), b(y) {}
void init(int x, int y) { a = x;
b = y; }
int a, b;
};
void main()
{
MyClass *a = new MyClass[2];
{
a[0].init(1,
2);
}
cout << a[0].a << " " << a[0].b << endl;
delete [] a;
}
·
In
the above, we defined a new "init" function, that takes the same
parameter as the constructor we would have called. This way, we avoided a creation,
and anassignment operation.
·
The
above example, when evaluated in the context of HW5, although it is ok to:
MyObject *a = new MyObject[10];
a[0] = MyObject(some parameter);
·
Considering
we are working with images, and often, the constructor involves the allocation
of an image, and in this case, the assignment may also involve the deallocatiion
and allocation of an image, it is much better to define a separate
"init()" function the performs the operation you would have performed
in the constructor:
MyObject *a = new MyObject[10];
a[0].init(some
parameter);
·
HW5 Reminder:
don't forget to use "const" where one should be used.
·
The
following function is meant to allocate memory and set the array size,
int imageSize, patternSize;
ImageClass *allImages;
PatternArea **allPatterns;
// reads file, and allocate the arrays
void ReadInfo(ImageClass *allIMages, PatternArea **allPatterns, int imageSize, int patternSize);
·
Note
that without the "&" all parameters are passed by value, and
whatever operations/assignments we performed on the above parameters will not be
visible from the called!
·
If
you want a function to read the array size, and allocate the array and set/change
the pointers, this is the function you should define:
void ReadInfo(ImageClass *&allIMages, PatternArea **&allPatterns, int &imageSize, int &patternSize);