Re: How to learn the C++ way?
Thank you for sharing, I have learned from this post.
W. J. La Cholter wrote:
For example, if you were to avoid generic practices for containers,
then you'd be stuck with something like pre-Java generics for storing
a collection of objects. Perhaps, everything would have to inherit
from a common base class to be stored. If you try to use certain
generic algorithms without functional Boost Lambda (or C++ TR1's
implementation), you'd have to write ad-hoc functions to apply
transforms across objects that don't quite fit the interface. If you
implement your domain objects using a functional technique, you really
wouldn't have a three-tiered architecture anymore.
This part is very interesting to me. I still have argument with java
people about why is STL better than the pre-Java generics collection in
Java. As you say, everything must inherit from a base in order to be in
the collection. I know this is bad. Can you break it down for
beginner/intermediate like me and others I argue with? Here is some
pseudo-code (and C++ used to be like this pre-STL remember RougeWave
RWCollection?). Why is line 25 so bad? Why forcing inheritance from
Collectable is so bad?
1 // all must inherit from here to be in a Collection
2 class Collectable
3 {
4 virtual int comp(const Collectable *, const Collectable *) = 0;
5 };
6 class Collection
7 {
8 public:
9 void add(Collectable *);
10 size_t size();
11 Collectable *getAt(size_t);
12 };
13 class Canvas; // forward declaration
14 class Shape: public Collectable
15 {
16 public:
17 virtual void draw(Canvas &) = 0;
18
19 };
20 class Canvas
21 {
22 public:
23 void render(Collection &sc) {
24 for ( size_t i = 0; i < sc.size(); i++ )
25 ((Shape *)sc.getAt(i))->draw(*this);
26 }
27 };
28 class Rectangle: public Shape
29 {
30 public:
31 void draw(Canvas &) {;} // override to draw rectangle
32 };
33 class Triangle: public Shape
34 {
35 public:
36 void draw(Canvas &) {;} // override to draw Triangle
37 };
38
I have some reasons, but I could benefit from more detail and stronger
reasons.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]