Re: Classes
Fil wrote:
You need to put the definition of the class in Box.h, and the implementation in
Box.cpp. Then #include Box.h in your main.cpp (or whatever it is called).
You mean constructor and destructor in Box.cpp and all the rest of the above
code in Box.h? Or is volume() part of what you call implementation?
Not sure why we need a Box.cpp:
It works fine if I write all the above code in Box.h and I write the include
"Box.h" in the main.cpp.
Why are you using pointer variables in your Box class?
In order to make the destructor I need pointers otherwise I don't have
anything to delete.
To make a collection you could use
std::vector<Box>
No idea what does that mean. I haven't started yet using the std namespace
(except for cin, cout).
(but get rid of the pointer variables first). Use push-back to add boxes to the
vector.
I keep note of that std::vector + push-back thing. Don't you aso havea way
to create this collection from scratch without using the std namespace?
Fil:
You have some strange notions about C++, and I think you could use a good
introductory book.
1. The class definition is just this part
class Box
{
};
Everything else is implementation.
2. You can put all the code in the header file, but in a bigger project where
the header is included in several .cpp files, this code will get compiled over
and over in each translation unit. So if you make any change in the
implementation, all these files will need to be recompiled. Also, you will need
to declare your implementations as inline (or put them inside the class
definition) or you will get multiple definition errors from the linker. Really,
it is best to put all the implementation in a .cpp file.
3. Your destructor does not need to do anything. Get rid of the pointers. As
Alex pointed out, they will cause you trouble if you do not define copy
constructor and assignment.
4. Your volume() method should be declared const:
float volume() const;
Const correctness is a very useful feature of C++ and it is best to get in the
habit of doing it correctly from the beginning.
5. std::vector is just the C++ way of doing containers. It's not that hard. Much
easier than creating your own class to do it.
#include <vector>
#include <assert.h>
std::vector<Box> boxes;
boxes.push_back(Box());
boxes.push_back(Box(1, 2, 3));
boxes.push_back(Box(4, 5, 6));
assert(boxes[0].volume() == 1.0);
assert(boxes[1].volume() == 6.0);
assert(boxes[2].volume() == 120.0);
[We shouldn't test floats for equality, but it will work here because they are
small integers.]
--
David Wilkinson
Visual C++ MVP