Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Jun 8th, 2005, 6:43 PM   #1
Encryption
Programmer
 
Encryption's Avatar
 
Join Date: Feb 2005
Posts: 42
Rep Power: 0 Encryption is on a distinguished road
Send a message via AIM to Encryption Send a message via MSN to Encryption Send a message via Yahoo to Encryption
OOP and Classes in C++ :: A Small Tutorial

Here is a small tutorial I wrote for RealmGX. There could be small errors here and there, but it compiles, and thats the best i can do with the time I have.

Meh...Object Oriented Programming. For something that wasn't even present in C, programmers sure do make a big deal out of it now. Why? Thats what we plan to find out, and hopefully implement it in our everyday programs. Sound fun? I didn't think so...but your going to keep reading anyways.

Now, so we can learn best, we are going to do a project with these skills we plan to aquire in the near future. So, since I am such a good project brainstormer (heh)we will be making a text based game lobby. So lets go over how this will work before we start jumping into classes and OOP.

We want this to automatically display everybody in the lobby when you join the lobby. You will be able to remove and add people from and to the lobby.

Clear? Good.

First, we will start with the basic structure of classes. First we will declare our class. It is easily done with the following syntax:
class ClassName
Much like functions you have opening and closing brackes in between the classes memberlists. So far, our class should look like the following.

class GameLobby
{

};
Please note, that you have a semi-colon after the closing bracket on a class. This is very important, but easily forgotten.

Now, what do we put inside the brackets. Something I mentioned earlier called a memberlist. A memberlist consists of a list of member declaractions. These can be data member or method declarations. Data member declarations are normal variable declarations. For example, "int x;", is a data member declaraction when inside a class. However you cannot initialize them(give them a value)where you can declare them. They must be initialized either in a method or outside the class. The scope of all data members is the same as the scopte of he object created from the class. However, data members cannot always be accessed from outside a class. The data members of a class define and describe the class properties(also known as attributes).

Method declarations are just as easy to understand as are data member declaractions. Method declarations are function declarations placed inside a class(recall that a function declaration can also include the implementation, or you can implement it separately). All methods can be accessed only through an object of the class(with the exception of static methods).

Two special kinds of methods, the constructor and the destructor, can be in a class. Both are optional, but they provide functionality that other methods cannot provide.

With all that, it may seem a bit confusing, so lets confuse you just a bit more with some code.

class GameLobby
{
     string userName;
     vector<string> usersInLobby;
     
     GameLobby(); //constructor
     ~GameLobby(); //destructor

     void AddUser(string name);
     void RemoveUser(string name);
     void ShowUsers();
};

You have, in general, walked through class declaractions. Now, it is time to take a more detailed look at methods. First of all, you can declare a method two ways. The most common way is to declarea method inside the class declaration and then implement it outside. The second way is to declare and implement the method at the same time inside the class declaration. We will be using the first way. The common syntax is:

return_type ClassName::methodName(argumentList)
{
    methodImplementation
}

Now lets apply this bit of information, and make our own methods for our class.

void GameLobby::AddUser(string name)
{ 
     usersInLobby.push_back(name);
}
void GameLobby::RemoveUser(string name)
{
    for(iter = usersInLobby.begin; iter != usersInLobby.end(); ++iter)
   {
          if(*iter == name)
          {
                usersInLobby.erase(iter);
          }
   }
}
void GameLobby::ShowUsers()
{
     cout<<endl;
     for(iter = usersInLobby.begin(); iter != usersInLobby.end(); ++iter)
           cout<<*iter<<endl;
     
}
Now we are going to write the constructor and destructor.

Constructor
GameLobby::GameLobby()
{
      //filling the game lobby up with the users there when user joins
      usersInLobby.push_back("Dark_Mage-");
      usersInLobby.push_back("Mason");
      usersInLobby.push_back("1337Drummer");
}

Destructor
GameLobby::~GameLobby()
{
      usersInLobby.clear();
}

Now, we have our basic class. Amazing. So, just incase you haven't been following along too well, here is the current code we have.

class GameLobby
{
     string userName;
     vector<string> usersInLobby;
     
     GameLobby(); //constructor
     ~GameLobby(); //destructor

     void AddUser(string name);
     void RemoveUser(string name);
     void ShowUsers();
};
void GameLobby::AddUser(string name)
{
     usersInLobby.push_back(name);
}
void GameLobby::RemoveUser(string name)
{
    for(iter = usersInLobby.begin; iter != usersInLobby.end(); ++iter)
   {
          if(*iter == name)
          {
                usersInLobby.erase(iter);
          }
   }
}
void GameLobby::ShowUsers()
{
     cout<<endl;
     for(iter = usersInLobby.begin(); iter != usersInLobby.end(); ++iter)
           cout<<*iter<<endl;
     
}
GameLobby::GameLobby()
{
      //filling the game lobby up with the users there when user joins
      usersInLobby.push_back("Dark_Mage-");
      usersInLobby.push_back("Mason");
      usersInLobby.push_back("1337Drummer");
}
GameLobby::~GameLobby()
{
      usersInLobby.clear();
}

Now...time for a bit of a twist. C++ allows you to control where the data members of your class can be accessed. This control is a powerful tool because it allows you to protect data members from accidental change. An access specifier is a word that controls where the data members in a class can be accessed. The syntax for an access specifire is as follows:

class ClassName
{
   classMembers
   accessSpecifier:
   classMemers
};

An access specifier affects all members of the class (including methods) that come after it until another access specifier is encounteredor until you reach the end of the class.

A class has two kinds of access specifires: public and private(actually there are three, the last is protected, but I am not covering that in this article). The effects of these two access specifiers are outlined here:

Public members can be accessed anywhere than an object of the class can be accessed and from within the class(that is, in the class's methods).

Private members can be accessed only from within the class itself. An object of the class cannot access the private members, except through public methods. If no access specifier is provided in teh class, all members default to private.

Here is an example of how you might use these specifiers:

class ClassName
{
       int x;
       public:
           int y;
           int z;
       private:
           int a;
};

Now lets apply this to our class...
class GameLobby
{
     public:
     string userName;
     void AddUser(string name);
     void RemoveUser(string name);
     void ShowUsers();
     GameLobby(); //constructor
     ~GameLobby(); //destructor
  
     private:
     vector<string> usersInLobby;
};

After all the preceding discussion on how to create classes, you must be eager to learn about classes. Soon you will be creating your own objects from your own classes, but for now, you learn just how to create objects.

There are two basic syntax forms to create objects:

className objectIdentifier(arguments);
or
className objectIdentifier = className(arguments);

So now that we know how to create an object, lets do it with our class.

GameLobby Lobby();

Now we are going to talk about accessing members. When a member is public, you can access it from anywhere than an object can be accessed. You can access a public member by using the member access operator(.) between the object identifier and the member. To assign a value to a public data member, use this syntax:

objectIdentifier.dataMemberName = value;

To retrieve a value of a public data member of an object, you switch the operands like this:

variable = objectIdentifier.variableName;

Public methods are accessed similarly. Here is the syntax to call a public method:

object.method(arguments)

Now...we have all we need to finish our game lobby...so try to finish it yourself, but if you have trouble, here was my final code.
#include <iostream>
#include <vector>
#include <string>
using namespace std;

class GameLobby
{
     public:
     void AddUser(string name);
     void RemoveUser(string name);
     void ShowUsers();
     GameLobby(); //constructor
     ~GameLobby(); //destructor
  
     private:
     vector<string> usersInLobby;
	 vector<string>::iterator iter;
};

void GameLobby::AddUser(string name)
{ 
     usersInLobby.push_back(name);
}
void GameLobby::RemoveUser(string name)
{
    for(iter = usersInLobby.begin; iter != usersInLobby.end(); ++iter)
	{
          if(*iter == name)
          {
                usersInLobby.erase(iter);
          }
	}
}
void GameLobby::ShowUsers()
{
     cout<<endl;
     for(iter = usersInLobby.begin(); iter != usersInLobby.end(); ++iter)
           cout<<*iter<<endl;
     
}
GameLobby::GameLobby()
{
      //filling the game lobby up with the users there when user joins
      usersInLobby.push_back("Dark_Mage-");
      usersInLobby.push_back("Mason");
      usersInLobby.push_back("1337Drummer");
}
GameLobby::~GameLobby()
{
      usersInLobby.clear();
}

int main()
{
	cout<<"Welcome to The Virtual Game Lobby"<<endl;
	cout<<"What is your username?"<<endl;
	string username;
	cin>>username;
	cout<<endl<<"Type \"quit\" to terminate the program.\nType \"add\" to add a user to the lobby."<<endl;
	cout<<"Type \"remove\" to remove a user from the lobby\nType \"show\" to view the current users in the lobby."<<endl;
	string userInput;
	GameLobby Lobby;
	string nameUser;
	do
	{
		cin>>userInput;

		if(userInput == "add")
		{
			cout<<endl<<"Who would you like to add?\n";
			cin>>nameUser;
			Lobby.AddUser(nameUser);
		}
		else if(userInput == "remove")
		{
			cout<<endl<<"Who would you like to remove?\n";
			cin>>nameUser;
			Lobby.RemoveUser(nameUser);
		}
		else if(userInput == "show")
			Lobby.ShowUsers();
	} while(userInput != "quit");

	return 0;
}

And finally, if you want to get into more advanced OOP concepts with C++ I can recommend these links...
http://www.elearningdepot.com/catalo...oopcpp8l1a.htm
http://oopweb.com/CPP/Documents/Thin...umeFrames.html
http://oopweb.com/CPP/Documents/Intr...umeFrames.html
__________________
Quote:
Originally Posted by Bjarne Stroustrup
* "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do succeed, you will blow away your whole leg."

* "I have always wished that my computer would be as easy to use as my telephone. My wish has come true. I no longer know how to use my telephone."
Encryption is offline   Reply With Quote
Old Jun 8th, 2005, 7:29 PM   #2
Ancient Dragon
PFO God In Training
 
Ancient Dragon's Avatar
 
Join Date: Jun 2005
Location: near St Louis, MO. (USA)
Posts: 532
Rep Power: 4 Ancient Dragon is on a distinguished road
I didn't read all of this, but shouldn't this have been in the Tutorial board?
Ancient Dragon is online now   Reply With Quote
Old Jun 8th, 2005, 8:36 PM   #3
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
I didn't look at it all, either, but I think you may want to review the validity of the bolded part.
Quote:
for(iter = usersInLobby.begin; iter < usersInLobby.end(); ++iter)
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Jun 9th, 2005, 3:59 AM   #4
El Toro
Newbie
 
Join Date: Jun 2005
Posts: 16
Rep Power: 0 El Toro is on a distinguished road
i don't want to be all negative, but...

0) it doesn't compile on my machine (DaWei's comment)
Quote:
Originally Posted by g++
tut] g++ --version
g++ (GCC) 3.2.2 20030222 (Red Hat Linux 3.2.2-5)
Copyright (C) 2002 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

[tut]
[tut]
[tut]
[tut]
[tut] g++ -Wall -ansi -pedantic tut.cc -o tut
tut.cc: In member function `void GameLobby::RemoveUser(std::basic_string<char,
   std::char_traits<char>, std::allocator<char> >)':
tut.cc:26: no match for `__gnu_cxx::__normal_iterator<std::string*,
   std::vector<std::string, std::allocator<std::string> > >& = <unknown type>'
   operator
/usr/include/c++/3.2.2/bits/stl_iterator.h:571: candidates are:
   __gnu_cxx::__normal_iterator<std::string*, std::vector<std::string,
   std::allocator<std::string> > >& __gnu_cxx::__normal_iterator<std::string*,
   std::vector<std::string, std::allocator<std::string> > >::operator=(const
   __gnu_cxx::__normal_iterator<std::string*, std::vector<std::string,
   std::allocator<std::string> > >&)
[tut]
1) does it run?
2) does it work correctly?
3) have you tested it?
4) what about header/source separation?
4) placing 'using namespace std;' (or any namespace) in global scope in a header file (which is where it would have to go if you turn this into a project) is bad c++ and should be punishable by castration.
5) what about operator overloading? you have a ShowUsers method where you could overload <<...

on the plus side, i have no doubt that you have the opportunity to learn a lot yourself in writing a tutorial like this and posting it for review.
El Toro is offline   Reply With Quote
Old Jun 9th, 2005, 4:48 AM   #5
Berto
Programming Guru
 
Join Date: Aug 2004
Posts: 1,022
Rep Power: 6 Berto is on a distinguished road
Send a message via AIM to Berto Send a message via MSN to Berto
Quote:
Originally Posted by Ancient Dragon
I didn't read all of this, but shouldn't this have been in the Tutorial board?
it will no odoubt be moved when a mod wakes up.
__________________
"Put your hand on a hot stove for a minute, and it seems like an hour. Sit with a pretty girl for an hour, and it seems like a minute. THAT'S relativity."

- Albert Einstein
Berto is offline   Reply With Quote
Old Jun 9th, 2005, 6:58 AM   #6
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
Quote:
Here is a small tutorial I wrote for RealmGX. There could be small errors here and there, but it compiles, and thats the best i can do with the time I have.
Here is what I see as the rub. A tutorial implies something is a learning mechanism for others, not oneself. I doubt one can write a substantial piece that is completely free of errors, but if one can't DEDICATE to doing that, one should call it a learning exercise, not a tutorial. It is highly undesirable to mislead those who are learning with errors and improper ideas and practices.

I have no problem with it being posted here if the idea is to get a critical assessment in order to find improvements or corrections. When I did my pointers thangy, I posted it in the forum (well, not the whole thang, jes' a link) and asked for comments and suggestions. I got some superb help. I have been told by many that the tutorial was helpful. For me, that was paydirt for the effort I expended. It WAS effort, and I COMMITTED to taking whatever time was required.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Jun 9th, 2005, 7:36 AM   #7
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,209
Rep Power: 5 grumpy is on a distinguished road
I agree with Dawei.

The purpose of a tutorial is to help others learn the topic. Writing something to help yourself learn is fine (as is getting it critiqued as such) and, eventually, you may be able to turn such material into a tutorial for others when you have learnt it.

At the moment, no offence intended, I wouldn't describe Encryption's post that started this thread as a tutorial on OOP in C++. It is a reasonable start at something written to learn a few of the basics. Hence my comments below may seem harsh, but are no intended to be: they are concerned with things that need to be done if the post is to eventually become a tutorial on OOP in C++.

OO (analysis, design, programming) is actually independent of any programming language. To teach someone about OO, it is necessary to describe the concepts (eg what is an object, aggregation, delegation, inheritence, specialisation, relationships between objects, etc etc). Then you wil be able to describe how to work with thost concepts in C++ (eg defining a class, member function, attributes, access control, etc etc). At the moment, by focusing of a few elements of C++ syntax (and then trying to describe a few of the OO concepts in terms of them) and that means only a little of what is needed will be learnt by someone else. The problem with that approach is that it would make a newbie who learns OO using this tutorial thing only in terms of C++ ways of doing things (and not all C++ ways of doing things at that): if that person later goes to another OO programming language, they will find the description of the C++ way of doing things will not necessarily map that well into the new language.

As others have said, the code examples are not all valid C++: the examples will not compile with a self-respecting C++ compiler.
grumpy is offline   Reply With Quote
Old Jun 9th, 2005, 9:46 PM   #8
Encryption
Programmer
 
Encryption's Avatar
 
Join Date: Feb 2005
Posts: 42
Rep Power: 0 Encryption is on a distinguished road
Send a message via AIM to Encryption Send a message via MSN to Encryption Send a message via Yahoo to Encryption
It compiles, and it the program works fine if your using Microsoft Visual C++ 6.0. When I said that it compiles but is not tested, was actually not valid to this date.

As for the above...when I said OOP and Classes in C++, I meant OOP in C++ also.

EDIT::
=-/
__________________
Quote:
Originally Posted by Bjarne Stroustrup
* "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do succeed, you will blow away your whole leg."

* "I have always wished that my computer would be as easy to use as my telephone. My wish has come true. I no longer know how to use my telephone."

Last edited by Encryption; Jun 9th, 2005 at 9:50 PM.
Encryption is offline   Reply With Quote
Old Jun 10th, 2005, 5:51 AM   #9
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
Be sure and read your own Stroustrup quote .
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 8:23 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC