473,385 Members | 1,730 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Why Use Classes?

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.
Jul 22 '05 #1
12 21184
On 24 Oct 2004 13:23:16 -0700, la******@hotmail.com (Langy) wrote:
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.
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.


--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #2
PKH

"Langy" <la******@hotmail.com> wrote in message
news:b6*************************@posting.google.co m...
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
Jul 22 '05 #3
Langy wrote:
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.
Thanks for your help in advance.

Langy.


Jul 22 '05 #4
Langy wrote:
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).

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #5
Ioannis Vranos wrote:
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.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #6
la******@hotmail.com (Langy) writes:
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 %
%%%% <ya***@ieee.org> % 'Shangri-La', *A New World Record*, ELO
http://home.earthlink.net/~yatescr
Jul 22 '05 #7
Randy Yates <ya***@ieee.org> writes:
[...]
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'
%%%% <ya***@ieee.org> % *Time*, Electric Light Orchestra
http://home.earthlink.net/~yatescr
Jul 22 '05 #8
Langy wrote:
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/CIS33...mSept1994.html
G
Jul 22 '05 #9
"Langy" wrote:
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
Jul 22 '05 #10
Ioannis Vranos wrote:
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.

Jul 22 '05 #11

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:cl*************@news.t-online.com...
Ioannis Vranos wrote:
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.


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
Jul 22 '05 #12
Catalin Pitis wrote:
That's not exactly true. Think of static data members.
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.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: David MacQuigg | last post by:
I have what looks like a bug trying to generate new style classes with a factory function. class Animal(object): pass class Mammal(Animal): pass def newAnimal(bases=(Animal,), dict={}):...
16
by: Simon Wittber | last post by:
I've noticed that a few ASPN cookbook recipes, which are recent additions, use classic classes. I've also noticed classic classes are used in many places in the standard library. I've been...
1
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking aftwerwards with ILDASM at what is visible in those assemblies from a...
9
by: Jack | last post by:
Hello I have a library of calculationally intensive classes that is used both by a GUI based authoring application and by a simpler non-interactive rendering application. Both of these...
2
by: joye | last post by:
Hello, My question is how to use C# to call the existing libraries containing unmanaged C++ classes directly, but not use C# or managed C++ wrappers unmanaged C++ classes? Does anyone know how...
18
by: Edward Diener | last post by:
Is the packing alignment of __nogc classes stored as part of the assembly ? I think it must as the compiler, when referencing the assembly, could not know how the original data is packed otherwise....
6
by: ivan.leben | last post by:
I want to write a Mesh class using half-edges. This class uses three other classes: Vertex, HalfEdge and Face. These classes should be linked properly in the process of building up the mesh by...
0
by: ivan.leben | last post by:
I am writing this in a new thread to alert that I found a solution to the problem mentioned here: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/7970afaa089fd5b8 and to avoid...
6
by: mailforpr | last post by:
Suppose you have a couple of helper classes that are used by 2 client classes only. How can I hide these helper classes from other programmers? Do you think this solution is a good idea?: class...
2
by: Amu | last post by:
i have a dll ( template class) ready which is written in VC++6. But presently i need to inherit its classes into my new C#.net project.so if there is some better solution with u then please give me...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.