Why Use Classes?

L

Langy

Hello

I'm fairly new to C++ but have programmed several other languages and
found most of c++ fairly easy (so far!).

I've come to a tutorial on classes, could someone please tell me why
you would need to use a class?

Perhaps you could also give an example on when it might be used rather
than an alternative method.

Thanks for your help in advance.

Langy.
 
B

Bob Hairgrove

Hello

I'm fairly new to C++ but have programmed several other languages and
found most of c++ fairly easy (so far!).
I've come to a tutorial on classes, could someone please tell me why
you would need to use a class?

Do any of the "other languages" have an object-oriented programming
paradigm? It might be easier to understand what a C++ class is/can do
if one of the other languages you already know has a similar feature.
 
P

PKH

Langy said:
Hello

I'm fairly new to C++ but have programmed several other languages and
found most of c++ fairly easy (so far!).

I've come to a tutorial on classes, could someone please tell me why
you would need to use a class?

Perhaps you could also give an example on when it might be used rather
than an alternative method.

Thanks for your help in advance.

Langy.

I like using classes primarily for the following reasons:
* They provide a logical connection between data and functions operating on
that data.
* You can make class-hierarchies which can save coding and are very
extendable by using virtual functions.
* You can restrict access to data, removing bug-opportunities that direct
access could give.

PKH
 
S

slurper

Langy said:
Hello

I'm fairly new to C++ but have programmed several other languages and
found most of c++ fairly easy (so far!).

easy? have you gone far? ;-) i wouldn't say easy compared to other
languages. c++ is power in your hands, but you need to cope with power.
I've come to a tutorial on classes, could someone please tell me why
you would need to use a class?

it gives you nice abstraction features. you can design internal state and
the operations which should modify the state in a nice chunk of code. In
addition you can hide the representation of the state of your objects
behind its interface, which allows you to modify the representation without
breaking the interface with clients using the modified code, which is
extremely important when you program large evolving systems.
once you have coded some time with object-oriented paradigm, you learn to
see recurring abstract patterns, which you can reapply for other problems,
making you a more productive programmer in long run. you will understand
someone else's code more quickly.
there are fantastic C programmers (or procedural programmers for that
matter) which will code better than some C++ programmers and you can code
in an object oriented manner with C (for example using function pointers to
implement polymorphism), but the syntactical features and support for OO in
the language itself, makes it possible to code more cohesive programs and
to understand other programs more quickly.
Perhaps you could also give an example on when it might be used rather
than an alternative method.
i know what i said before sounds abstract, but i'd convince you to learn the
oo-features. in the long run, i'm sure you will once wonder why you could
do without them for so long; certainly when you start maintaining or
programming proggies with say 20 source files.
 
I

Ioannis Vranos

Langy said:
Hello

I'm fairly new to C++ but have programmed several other languages and
found most of c++ fairly easy (so far!).

I've come to a tutorial on classes, could someone please tell me why
you would need to use a class?


Classes are user defined types.


Perhaps you could also give an example on when it might be used rather
than an alternative method.


For example consider the Complex class of the standard library. Another
example is if you want to use IP connections as distinct objects and so
you define an IP connection type (class).


In general, anything you want to consider as a type, you define it as a
class (or struct).
 
I

Ioannis Vranos

Ioannis said:
Classes are user defined types.


For example consider the Complex class of the standard library. Another
example is if you want to use IP connections as distinct objects and so
you define an IP connection type (class).


In general, anything you want to consider as a type, you define it as a
class (or struct).


A class contains the internal data implementation along with the
functionality (the functions working on this data).


A class definition itself does not occupy space. Its instances, that is
the objects of this type, are those that occupy space.
 
R

Randy Yates

Hello

I'm fairly new to C++ but have programmed several other languages and
found most of c++ fairly easy (so far!).

I've come to a tutorial on classes, could someone please tell me why
you would need to use a class?

I think the basic reason is "encapsulation," that is, the grouping of
data and functions common to a type of object. For example, you might
specify a complex class that stores internally the real and imaginary
parts of a complex number and provides functions to retrieve the number
in rectangular and polar form. C (and C++) structures provide encapsulation
for data only.

A more advanced reason is that you can overload operators like "+", "-",
etc., to operate on that object type in a special way. Sticking with the
complex class example, you could overload + and - to add and subtract two
complex numbers.

But then you probably knew this already as it should be covered in any
introduction to C++.
--
% Randy Yates % "My Shangri-la has gone away, fading like
%% Fuquay-Varina, NC % the Beatles on 'Hey Jude'"
%%% 919-577-9882 %
%%%% <[email protected]> % 'Shangri-La', *A New World Record*, ELO
http://home.earthlink.net/~yatescr
 
R

Randy Yates

Randy Yates said:
[...]
C (and C++) structures provide encapsulation
for data only.

Function pointers notwithstanding. Even then, the function definition itself
is outside the structure and thus not encapsulated with the object type.

Another reason to use classes is to provide "polymorphism." This is a
way to provide a single set of APIs that manipulate a family of
related objects and the ability to invoke the API at run-time on one
of these objects without knowing which specific object type is being
manipulated (see virtual functions.)
--
% Randy Yates % "Ticket to the moon, flight leaves here today
%% Fuquay-Varina, NC % from Satellite 2"
%%% 919-577-9882 % 'Ticket To The Moon'
%%%% <[email protected]> % *Time*, Electric Light Orchestra
http://home.earthlink.net/~yatescr
 
G

Gianni Mariani

Langy said:
Hello

I'm fairly new to C++ but have programmed several other languages and
found most of c++ fairly easy (so far!).

I've come to a tutorial on classes, could someone please tell me why
you would need to use a class?

There is no "need" to use classes. In the same way that there is no
need to use a compiler. You can encode machine language instructions if
you wish, it would be an awful waste of time, however.
Perhaps you could also give an example on when it might be used rather
than an alternative method.

Classes came about because programmers recognized that with data
structures, you usually associate a set of functions. After this point,
it became clear that you could make classes contain their own scope,
i.e. it can contain it's own types and nested classes. Still, there are
times when functions deal with multiple classes, you can't really
associate a function as a "member" of the class.

Then comes the idea of "polymorphism" - i.e. classes as interfaces when
the underlying implementation is not important, but how to use the class
is. Hence you can write one piece of code that can be used for varying
types of implementations. This is all about reducing the amount of
work. This is one of the foundations of "reusablility". Code re-use is
important because you'll find yourself re-writing at least 60% of your
code every time you do a new project.

When you start to formalize classes, there are two very important
operations that need to be well defined, construction and destruction.
C++ has some well defined rules as to how this works and it can be the
cause of some very interesting surprises if you don't grasp it fully.
(said by someone who probably will get some new surprises!).

Anyhow, when you consider operators, conversion operators, templates and
the rest of C++ into the picture, you'll start to understand how classes
are the fundamental building block of C++. In C++ consider using
classes at a very low threshold because they are very efficient
abstractions and most compilers will generate code that is just as fast
as anything you could write without them if you decided not to use classes.

As for your example. Look at the Unix (Posix) file API. A file is
represented as an "int".

int open(const char *pathname, int flags);

Well, "int" is not very useful as it can be confused with other things.
Does it really make sense to add 2 file descriptors ?

int fa = open( "a.file", O_RDWR );
int fb = open( "b.file", O_RDONLY );

int x = fa + fb; // no compiler error - but meaningless !

write( fb, "A", 1 ); // run-time error (not even checked !)

Consider using classes.

RdWrFile fa( "a.file" );
RdFile fb( "b.file" );

fa + fb; // compiler tells you about an error

fb.write( "A", 1 ); // invalid write to RdFile - compile error

Hence, well written interfaces allow the compiler to pick up errors at
compile time. In software development, the earlier you catch errors,
the more productive you are (i.e. the less costly the errors are!).
Hence errors caught at compile time are the least expensive errors.
(Yes, there are a class of errors that can only be caught at run-time,
this is what unit tests are for. Errors caught in the field can be
extremely costly to the extent of loss of life.)

Some interesting links about software development at it's worst !
http://catless.ncl.ac.uk/Risks/
http://www.cis.gsu.edu/~mmoore/CIS3300/handouts/SciAmSept1994.html


G
 
R

Robbie Hatley

Langy said:
I'm fairly new to C++ but have programmed several other languages and
found most of c++ fairly easy (so far!).

I've come to a tutorial on classes, could someone please tell me why
you would need to use a class?

You're familiar with struct's, aren't you? Well, classes are really
just slightly super-charged versions of C structs. In fact, "class" and
"struct" in C++ vary only in default access specification. (struct
defaults to public, class to private.)

Classes are most useful in programs that deal with classification,
especially hierachies of classification.

But even if you're not classifying things, classes can be very useful.
I like 'em because they allow me to bundle the data being worked-on
tightly with the methods used to work on that data. Further, they
allow me to specify somes methods and data to be "public" (so that
any function can access them) and some "private" (so that only member
functions of that class can access them). And, they provide excellent
separation between interface and implimentation for improved modularity
and ease of maintainance. And, class objects provide repositories for
data that the programmer would otherwise be tempted to put in global
variables, which is usually a bad idea.

And perhaps most of all, I love the way that classes clean-up messy
source code. For example, starting last Friday night, I starting
writing a program to count all lines of C/C++ source code in a
directory tree. Use of classes helped speed my programming (allowing
me to finish it in 2 days) and helped keep my code clean.

I first made a class to hold data on lines of source found so far
in this tree:

namespace SourceLines
{
...

class SourceTree
{
public:
SourceTree (void) : Lines(0UL) {}
void CountLines (void);
void PrintLines (void);
void CountLinesInFile (const rhdir::FileRecord& File);
void CountLinesInCurDir (void);
private:
unsigned long int Lines;
};

...
}

Then I used this class in main() like this:

int main(void)
{
using namespace SourceLines;
SourceTree Tree;
Tree.CountLines();
Tree.PrintLines();
return 0;
}

That's my whole main() function! I promise you I didn't shorten
it in any way for this post! Classes just make code that clean.

So what did I do there? First I made an instance (an "object")
of class SourceTree called "Tree". Then I called a couple of
SourceTree member functions through Tree, which did all the work.
Countlines() counted up all the source lines and put the total in
variable "Lines" in object "Tree". PrintLines() then just printed
the value of Lines. Done. Exit.

Without classes, my main() would have been 500 lines instead of
5 lines, and the whole flow and concept would be burried under
all that code.

I usually write class declarations first; then write main(),
laying out the sequence of things to be done; then finally
impliment member functions. Basically, a "top-down" approach.
This keeps the messier code confined to low-level subroutines,
leaving main() and higher-level subroutines much more readable.

So in the end, my answer to your question "why would you need
to use a class" is "Because they make programming easier".

--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant
 
R

Rolf Magnus

Ioannis said:
A class definition itself does not occupy space. Its instances, that is
the objects of this type, are those that occupy space.

That's not exactly true. Think of static data members.
 
C

Catalin Pitis

Rolf Magnus said:
That's not exactly true. Think of static data members.

The static members are not the class definition.

However, there is are cases when the class definition can introduce
additional memory consumption:
- using virtual methods
- using RTTI

Catalin
 
I

Ioannis Vranos

Catalin said:
The static members are not the class definition.

Exactly.



However, there is are cases when the class definition can introduce
additional memory consumption:
- using virtual methods
- using RTTI



sizeof(type)==sizeof(object_of_that_type).


The type instances (objects) are those that do occupy space, and not the
type definition.


The v-tables etc are implementation details, and their space do not
correspond neither to the type definition nor nor to its objects.

In other words, sizeof(type) and sizeof(obj) do not contain the v-table.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,966
Members
47,516
Latest member
ChrisHibbs

Latest Threads

Top