Re: Classes
First of all, get rid of these pointers. They are completely
redundant. Moreover, your class has a serious bug due to the
erroneous usage of pointers. You forgot to define copy constructor
and assignment operator. So, following code exhibits undefined
behavior:
{
Box b1;
Box b2;
// All pointers in b1 instnce are lost,
// since they are overwritten by values from b2.
b1 = b2;
} // Oops! Both b1 and b2 attempt to delete the same pointers!
"Fil" wrote:
I am starting with classes and so far I wrote by Box class:
Start of Box.h file.
class Box
{
float * a;
float * b;
float * c;
Should be:
class Box
{
float a;
float b;
float c;
....
public:
Box();
Box(float,float, float);
~Box();
float volume();
};
End of Box.h file.
Start of Box.cpp file.
#include "Box.h"
Box::Box(float x,float y, float z)
{
a = x;
b = y;
c = z
}
Box::Box() : a(1), b(1), c(1)
{
// empty body
}
Box::~Box()
{
delete a;
delete b;
delete c;
}
No need for destructor.
float Box::volume()
{
return a * b * c;
}
End of Box.cpp file.
My first wish is to write this code in a separate cpp file but,
when I tried, the compilation failed. I am not sure what to
write in the main() cpp file to make it work.
No just include Box.h in main.cpp file:
#include "Box.h"
int main()
{
...
}
My second wish is to create a class Boxes with a method add that
would work like a vba collection. My Boxes occurence would be
empty initially. When you call its add method it would add a
Box(1,1,1) to it.
You could use std::vector here:
#include <vector>
....
typedef std::vector<Box> Boxes;
Boxes boxes;
boxes.push_back(Box());
boxes.push_back(Box(1, 1, 1));
boxes.push_back(Box(10, 20, 30));
etc.
HTH
Alex