DPfan said:
What's exactly the meaning of "code reuse" in C++?
Code reuse is something you have to consider in the design
of the components you are building. In particular you need
to think in terms other than your immediate needs, and
devise code that does only one particular job. The standard
C library is good example of code that can be reused, as is
the UNIX text utilities.
But you must realise that there is a cost involved in
writing code that can be reused. Just by writing in C++
won't guarantee that the code you write is reusable.
Why such kind of reuse have more advantages over the counterpart in other
language like in C?
In C the things that you can reuse are functions, and to
some extent data structures. C++ gives you other elements
like classes, templates, and polymorphism. You therefore
have a richer set of things that you can reuse.
How is "code reuse" realized in C++? By composition mainly? What're
others?
I'll thow polymorphism into the pot. Say you have a base
class Person from which you can obtain the city where the
person lives and you want to find all the instances of
Person in a list that live in city X. Write a function to do
that is pretty simple either in C or C++ but not
particularly reusable, because you can only process Person
objects. Now consider that your list contains pointers to
instances of Person rather than Person objects directly
(perhaps using some smart pointer type). Now someone having
derived a class Employee from Person could build a list of
employees which they pass to the find function. The function
is now being reused to find employees. Perhaps Person is
used to derive a class Player in some game scenario, your
find function will still work. In fact it will still work
given a list of Employees and Players.
And there is a deeper reuse going on here, which is one of
the main rationals for OO, the reuse of the concept Person.
Personally I always prefer to see code that operates on the
root of a class heirarchy, I'd much rather code in terms of
Curve or Surface, than Bezier or SweptSurface. The result is
far more reusable.