Public Group

# Stuck on Classes

This topic is 3791 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

So I looked through my college text book, no good examples of classes. They show examples but none in a complete program, not to mention all their examples are pretty poorly explained. So I turned to google as usual when reading this book and I cant seem to find any good info on classes on there either and was wondering if anyone had some nice sites that they use to explain syntax. I was using CProgramming.com and some other sites that looked like they were from universities but everything I come across seems to have different syntax. So I guess I have a two part question: 1. Does anyone know of any sites they prefer that has tutorials on it? 2. Anyone willing to write me a super simple class? :D I believe I understand the concept, its just the syntax I am hung up on. I see some places use constructors and destructors, others dont, and the syntax seems to be different on each page that I go to. EDIT: I forgot to mention its C++. [Edited by - Chrono1081 on February 6, 2008 1:45:09 AM]

##### Share on other sites
its been a long time since I looked at a entry level C++ book (I'm assuming C++), so I can't think of any suggestions off the top of my head.

But gamedev.net has a large collection of book reviews / ratings.

Books

There are 42 book listed for C++. If your looking for C# or Java you could probably find plenty of those too.

I guess my point is get a book. If the book you looked at isn't clear you just need another book.

But books will get you only so far, looking at other peoples code will teach you more, but only after you get the basics. You'll get the basics from a good book.

Hopefully you can find a book in the link I provided.

##### Share on other sites
Thank you for your suggestion :) However unfortunatly where I am currently at a new book isnt an option : / I already have a few on the way but they take about a month to get here.

##### Share on other sites
I'm about to head to school, but I'll try to give you a small example.

A class is a set of instructions for what an object can do. Let's say we want to create a "ball" object. It can bounce and roll (for this examples purposes).

First we write the instructions prototype (often written in a headerfile), which means we're writing the short-version of the class which we will implement later.

For a ball-class it might look something like this:

class Ball{public:/* Public variables and functions are written here, you should always include both constructor and deconstructor here, even if they are empty, to show that you want them to be. */Ball(); // Constructor.~Ball(); // Deconstructor.void Bounce(); // A public bounce function.void Roll(); // A public roll function.};

That is what you might find in a headerfile. That is the short-hand version of a class, the definition. Next, we need to implement the class, which is often done in a .cpp file, which includes the headerfile.

#include "Ball.h"Ball::Ball(){// An empty constructor, but we still write it so other programmers won't misunderstand.}Ball::~Ball(){// An empty deconstructor, but we still write it so other programmers won't misunderstand.}void Ball::Bounce(){/* Here we put the code needed for the ball to bounce. It could be something as simple as "std::cout << "Boing!";". */}void Ball::Roll(){// Same as the ball-function.}

Now we have implemented the Ball-class. But all this code doesn't do anything by itself, we need a main-function in order to run this.

#include "Ball.h"int main(){Ball aTestBall;Ball.Bounce();Ball.Roll();return 0;}

In that main we created a ball object, called both its functions, then exited.

Now I have to run, hope this gives you a small idea of how a simple class can work.

My teacher once said that a class is a "blueprint" for how something should work, and as you said, the headerfile and .cpp file in this example served that purpose.

Have a nice day and good luck with your studies. :)

##### Share on other sites
You don't want a "tutorial." None of them are any good. I'm sure some have their good points, but they just can't stand up to the books on the subject.

As for books, "Thinking in C++" is one of the better ones and better yet (for you especially), it's available for free from mindview.net. The thing about Thinking in C++ is it's not a real nuts and bolts "this is how things should look in your source code" kind of book. It has long-winded (and very well written and thought out) discussions about object oriented programming and its use in C++. I think it's exactly what you're looking for.

Edit: I didn't mean to imply all C++ books are good either. There's a lot of junk out there..

##### Share on other sites
Best entry level C++ book I know is "Accelerated C++". Go down to a library or a book store or something and check it out. If you like the way it's written get a copy, it's worth the very reasonable price.

Accelerated C++ teaches C++ starting with a coverage of the higher level concepts and working down to the lower level concepts. Imho this is the way that a programming language should be taught.

A super simple class might look like this:

class SuperSimple {};

in order to add member data, you would declare it inside as in:

class SuperSimple {    int memberData;};

member functions (methods) work in a similar fasion:

class SuperSimple {    void memberFunction( void )    {        return;    }};

It's important that you understand public, protected and private access. You should read a book to understand those, because it takes a lot of time to figure them out but here's the syntax for a public member function and public member data for example:

class SuperSimple {public:    void publicFunction( void )    {        return;    }    int publicData;};

NOTE: It's generally a VERY bad idea to declare any member data public or protected because it's free for anyone to mess around with, potentially breaking any invariants in your code. There are exceptions to this rule of course, but for general use, make sure you declare your member data as private.

Constructors and destructors are kind-of, sort-of optional. You can choose not to define them but it's usually not a good idea to leave them out. Constructors are simply member functions which have the name of the class and no return type. Destructors are simply member functions which have a ~ followed by the name of the class and no return type or parameters. Constructors are automatically called when an instance of a class is created and destructors are automatically called when an instance of a class goes out of scope or is deleted. In general, you use constructors for setting the initial values for member data and allocating memory for member data stored on the free store (heap). Destructors are generally used for deleting member data stored on the free store. You can declare constructors and destructors like so:

class SuperSimple {public:    SuperSimple( void )    {        // Do setup stuff in here    }    ~SuperSimple()    {        // Do cleanup stuff in here    }};

Using a class:

int main( int argc, char **argv ){    // Create an instance of class SuperSimple    SuperSimple myInstance; // The constructor is called here    // Accessing public member data    myInstance.publicData = 0;    // Calling a public member function    myInstance.publicFunction();    return 0;}   // The class goes out of scope when the function it is created in ends// The destructor is called here

When accessing data using a pointer to an object, a different syntax is used. For example:

int main( int argc, char **argv ){    // Create an instance of class SuperSimple    SuperSimple myInstance; // The constructor is called here    SuperSimple *pointerToMyInstance = &myInstance;    // Accessing public member data    pointerToMyInstance->publicData = 0;    // Calling a public member function    pointerToMyInstance->publicFunction();    return 0;}

Of course, the above are simply one way of declaring functions in a class, it's possible to define a function outside of the class definition, or even in another file, if you use a different syntax (like the syntax described in one of the posts above). Once you get into more complex stuff, the syntax becomes more complex so take your time to learn all of these and use what you're comfortable with. Learning C++ is a gradual progression, you can use what you know and learn as you go. :)

[Edited by - Leo_E_49 on February 6, 2008 3:27:22 AM]

##### Share on other sites
1) First learn to use existing classes. The library stream classes (fstream, stringstream, etc.) and containers (string, vector, etc.) are a good place to start.

2) Lots of class features are "optional", or at least, a default is commonly provided that does what you want. You use the parts that are necessary for the class you're working on.

3) A class represents a data type. Think of 'Foo bar;' exactly like you would think of 'int bar;', except that there is also syntax for accessing members, which can be either data (just like parts of a struct) or functions (which are "bound" to that Foo instance). When you call a member function of an object, it's like telling that particular object of the class to do something.

4) The point of constructors is to initialize the instances. Think of 'Foo bar(x, y, z);' just like 'int bar = 7;'. In fact, in C++ you can write 'int bar(7);', though it's not common. The point of destructors is to clean up the object's mess when the object goes out of scope. You will practically never call it directly. You can think of primitive types as having a destructor that does nothing (because there is nothing about an int that needs to be "cleaned up"). There are very few ways to "make a mess", and there are pre-defined classes (again, lots of them are in the standard library) that handle most of the basic kinds of messes, so you will very rarely have to write a destructor yourself, if you use proper tools.

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 12
• 9
• 12
• 37
• ### Forum Statistics

• Total Topics
631426
• Total Posts
3000019
×