C++ Lesson 3: Classes

You can talk about anything. (please read forum rules before posting)

Moderator: thunderchero

User avatar
Flocke
BORG Trouble Maker
BORG Trouble Maker
Posts: 3197
Joined: Sun Apr 27, 2008 2:00 am
Location: Hamburg, Germany
Contact:

C++ Lesson 3: Classes

Post by Flocke »

C++ Lesson3: Classes and Object Oriented Programming (OOP)

Previous: C++ Lesson2: Introduction
Follower: --

Last lesson we went through some basics, modified the "Hello World" sample program and implemented an own first application.
This lesson we'll talk on basics of object oriented programming to get you compfortable with it right from the start. ;)

=======================================
concepts and code structure

First some talk on concepts and code structure again.

In C++ the code is organized into header and source files. While header files commonly just declare that something exists and are included by source files or other header files, the source files are used to define what actually exists. The compiler just builds what's in the source files and copies header files in by include statements.
It becomes important to follow this rule once you start to split your code to multiple files.
While definitions only are allowed to be done once in the whole project, declaring them is allowed once per source file as the compiler resets declarations every source file it does compile.
To not declare things multiple times by recursive includes in same source file, guards are used featuring preprocessor macros.
All that will become more clear while we progress.
Just remember, different to many other languages, in C++ you're coding in the .cpp 'source' files and declaring seperately in the .h 'header' files :!:

One important thing about C++ is you're not forced to program in C++ but also can use plain old C or with 'inline assembler' instructions you can even code assembler. Also with macro- and template-programming you have a huge range of abilities, not to talk of the std library and others.
Mixing C++ and C however leads to a bad programming style. Furthermore some old C calls like file access are scoffed and often called deprecate in C++ development for security issues.
We'll go right ahead with C++ development and so have to talk on classes.

Classes is what's used for OOP in C++, it's main development concept.
A class is what defines an object. Have a look around you, all of what you can see are objects. They are instances of classes with multiple methods (=function inside a class) to operate on. Maybe you find a pencil or if not use your mouse. Now take your hand and call a function to operate on that pencil or mouse object. That's the way of thinking with object oriented programming.
Even the hair on your nose is an object - each of it. Maybe down to the atoms or further if you want.
It's been invented to portion your code and gives much better maintainability than with poor C code.

=======================================
basics of C++ classes

Start with main.cpp from last lesson containing the following:

Code: Select all

#include <iostream>

using namespace std;

int main()
{
	string input;
	while(input.compare("exit") != 0)
	{
		cout << "post some stuff" << endl;
		getline(cin, input);
	}
    return 0;
}
Now create a new class using File->New->Class in Code::Blocks.
It gives you a prompt. Enter a name for your class, e.g. "lesson3", leave the rest as is and press "create".
Choose to add it to the current project, both Debug and Release.
What you get is two new files, one header and one source file.
The Debug mode btw is a bit slower than the release one but more safe and includes symbols for the debugger so when you debug your code in code::blocks you can execute line by line to see what happens.

Try to compile.

If it fails telling that it couldn't find your header file, it is cause we didn't tell where to look for your header files yet.
To solve, go to Project->Build options. On the left choose your project name to change for both Debug and Release.
Open Search directories tab, compiler sub-tab should be selected. Add your project's include folder, the folder in where your header file is. To not make your project path dependent, just use the relative path to where your project is located. So if your project is in C:\folder\folder\folder\folder\folder\folder\myproject and your includes lay in myproject\include just type include

Make sure you get that work!

In the header file, on top there there you see a guard using define macros to not declare things multiple times.
The class declaration is devided into three sections: public, protected and private. For now only public does interest as the others do prevent accessing the class methods from outside.
Two methods you see declared. Other than our "int main()" function there is no return type specified. The virtual key word is used for polymorphism but that we talk on another lesson, for now you can remove it. As a Java developer just know that in Java methods always are virtual so there is no such specifier.
That here no return type is specified is cause these are special ones. First one is the class constructor always called on object creation, and second one is the destructor called when the object stops to exist. Both always equal the class name, the destructor just has a preceding ~
declarations end with a ; just like any code expression. That's also the case for the whole class declaration so other than a namespace which is no declaration, it ends with a semicolon!
In the cpp source file you find the according definitions to both of them. As you can see the name of the class occures twice. First one to access class scope using a double colon ::, second for the method name.

What I want you to do now is create another method, declare in header, define in the cpp. Don't forget the return type like it's been with main.
In that print something to the console again. don't forget to add the iostream header to your source file so you can make use of cout.
Now in main.cpp, include your class header. Then inside the main function, create an instances of your class by typing your_class_name myClassInstanceName;
afterwards call your new methods by typing
myClassInstanceName.myMethod();

Here's what I put together:

main.cpp:

Code: Select all

#include <iostream>
#include "lesson3.h"

using namespace std;

int main()
{
	string input;
	lesson3 myInst;
	while(input.compare("exit") != 0)
	{
		myInst.turn();
		cout << "post some stuff" << endl;
		getline(cin, input);
	}
	return 0;
}
lesson3.h:

Code: Select all

#ifndef LESSON3_H
#define LESSON3_H

class lesson3
{
	public:
		lesson3();
		virtual ~lesson3();

		int turn();

	protected:
	private:
};

#endif // LESSON3_H
lesson3.cpp:

Code: Select all

#include "lesson3.h"
#include <iostream>

using namespace std;

lesson3::lesson3()
{
	//ctor
}

lesson3::~lesson3()
{
	//dtor
}

int lesson3::turn()
{
	cout << "my turn" << endl;
	return 0;
}
So far so good, but it doesn't bring us any far on using classes here.
What classes come useful for is when creating multiple inctances and giving each a different state.
Therefore we need so called "member variables".
Member variables can also be seen as attributes of a class making it a logical unit. ;)

Watch and try following code for it featuring while(true) again:
main.cpp:

Code: Select all

#include <iostream>
#include <cstdlib>
#include "lesson3.h"

using namespace std;

int main()
{
	string input;
	lesson3 myInst1;
	lesson3 myInst2;
	while(true)
	{
		cout << "post some stuff" << endl;
		getline(cin, input);
	
		if(input.compare("n") <= 0){
			if(myInst1.turn()){
				cout << "myInst1 won! exit" << endl;
				break;
			}
		}
		else if(myInst2.turn()){
			cout << "myInst2 won! exit" << endl;
			break;
		}
	}
	system("PAUSE");
	return 0;
}
lesson3.h:

Code: Select all

#ifndef LESSON3_H
#define LESSON3_H

class lesson3
{
	public:
		lesson3();
		virtual ~lesson3();

		int turn();

	protected:
	private:
		// here define your member variables
		// for better encapsulation put them in private section
		// so they can't be accessed from outside the class
		int myPrivateState;
};

#endif // LESSON3_H
lesson3.cpp:

Code: Select all

#include "lesson3.h"
#include <iostream>

using namespace std;

lesson3::lesson3()
{
	//ctor initialize member variables on creation
	// else they might contain anything
	myPrivateState = 0;
}

lesson3::~lesson3()
{
	//dtor
}

int lesson3::turn()
{
	// increment myPrivateState, use ++ preceding it
	// to increment before comparison
	if(++myPrivateState > 10) return 1;
	else return 0;
}
=======================================
now practice with classes!

This is the fun part again.
Make some more use of above class concept than me, extend your previous application if you want.

Have fun and don't forget to share results and leave some feedback! :)
Only on good participation I will continue! :P

If you find errors, try fix and report, I didn't try compile yet.
Last edited by Flocke on Mon Jul 23, 2012 4:23 am, edited 1 time in total.
Dr_Breen
Commodore
Commodore
Posts: 889
Joined: Wed Apr 30, 2008 2:00 am
Location: Zurich, Switzerland
Contact:

Re: C++ Lesson 3: Classes

Post by Dr_Breen »

is there anyway to tell code::blocks to automatically use the "include" folder? i always had to enter it into the build options menu.

btw nice examples. working trough them right now.
after that i'm looking for some bigger homework i can do. do you know any websites where they give you some projects you can do, but ALSO offer an example source to it? i like doing it this, so when i'm stuck somewhere i can check how it could be done.

edit: got it. under settings->compiler you can set to add the "include" folder to the directories searched permanently

edit: okay im trough the example you made. looking forward to hear a bit about inheritance and pointers :-)

BTW who is still in? am i the only one?
Public BotF / EF2 Teamspeak 3 Server: 83.169.13.55
Dr_Breen
Commodore
Commodore
Posts: 889
Joined: Wed Apr 30, 2008 2:00 am
Location: Zurich, Switzerland
Contact:

Re: C++ Lesson 3: Classes

Post by Dr_Breen »

by the way the code works
myinst2 can only win when you enter a string with more than 2 characters
myinst wins when entering an empty string or one single character
Public BotF / EF2 Teamspeak 3 Server: 83.169.13.55
Dr_Breen
Commodore
Commodore
Posts: 889
Joined: Wed Apr 30, 2008 2:00 am
Location: Zurich, Switzerland
Contact:

Re: C++ Lesson 3: Classes

Post by Dr_Breen »

*bump* when do we go on? :-)
Public BotF / EF2 Teamspeak 3 Server: 83.169.13.55
User avatar
Flocke
BORG Trouble Maker
BORG Trouble Maker
Posts: 3197
Joined: Sun Apr 27, 2008 2:00 am
Location: Hamburg, Germany
Contact:

Re: C++ Lesson 3: Classes

Post by Flocke »

when more people participate
KrazeeXXL
BORG Trouble Maker
BORG Trouble Maker
Posts: 2323
Joined: Sat Jan 03, 2009 3:00 am
Location: the 36th Chamber

Re: C++ Lesson 3: Classes

Post by KrazeeXXL »

sorry guys, can't participate. As programming just makes me mad.
User avatar
Flocke
BORG Trouble Maker
BORG Trouble Maker
Posts: 3197
Joined: Sun Apr 27, 2008 2:00 am
Location: Hamburg, Germany
Contact:

Re: C++ Lesson 3: Classes

Post by Flocke »

I can tell you why your code works or not, that is what this lesson is for.
If you have no interest that's another thing.
I am waiting for people, who ever it is.
Dr_Breen
Commodore
Commodore
Posts: 889
Joined: Wed Apr 30, 2008 2:00 am
Location: Zurich, Switzerland
Contact:

Re: C++ Lesson 3: Classes

Post by Dr_Breen »

try and error. this is how you get into it KrazeeXXL. how many tries did it take you to learn driving a bicycle? 1? 3? 70?
Public BotF / EF2 Teamspeak 3 Server: 83.169.13.55
KrazeeXXL
BORG Trouble Maker
BORG Trouble Maker
Posts: 2323
Joined: Sat Jan 03, 2009 3:00 am
Location: the 36th Chamber

Re: C++ Lesson 3: Classes

Post by KrazeeXXL »

1 time ;)

my father pushed me and I drove. that was it :D


and to programming. I have some xp in it but it's just not my thang. I tend to forget a little thing here and there and nothing works. I just hate it.

Sisyphusarbeit da nachzuschauen, ob irgendein apostroph irgendwo fehlt oder ein & oder was auch immer. total nervig. Manche Menschen gehen da voll drin auf in so kleinen details, ich wiederrum nicht. das macht mich einfach kirre.

Geht nicht, ums nicht lernen wollen. Es geht um das ganze "Programmieren" an sich. Schön... schleifen, arrays, Zeiger und klassen und diesen ganzen krempel hab ich gelernt. Und ich rede jetzt nicht nur von nem 10h lehrgang. Weit über 200h... und es war einfach grässlich

Nur hab ich echt nicht die Muse jedesmal nach irgendeinem dummen Zeichen zu suchen, was ich in Zeile 386 mal vergessen hab.

Programmieren sollte automatisiert werden. So wie im Holodeck. Sag an was du haben willst und los gehts. Dieses ganze minimalistische ist einfach nichts für mich. Sieht man schon an meiner Unterschrift ;)

sorry, kein bock gerad auf englisch zu schreiben ;)

zur not gibts google translate
User avatar
Flocke
BORG Trouble Maker
BORG Trouble Maker
Posts: 3197
Joined: Sun Apr 27, 2008 2:00 am
Location: Hamburg, Germany
Contact:

Re: C++ Lesson 3: Classes

Post by Flocke »

hey, it's everyones own decision whether to learn programming or not.
I'm just waiting and so long have enough other things to work on.

Once people realize possibilities maybe they reconsider, or new ones get attracted.
May it be for a sequal, a clone, or good old vanilla BotF.
I decided to try improve the original for well reasons.
First to learn of it, second cause it makes fun to me, third cause I don't have time to develop a new one from scratch, fourth cause I always believed that it's possible and just had to give it a try.

By now I know lots more and when I've time again I'll continue research and complete projects like mpr++.
There are many other not just theoreticly possible projects one could work on if interested.
For example develop a complete new AI. As BotF already has one it wouldn't even have to do the full job.
I am absolutely sure it is possible just like other things are, but one needs to have time, I currently don't.

So please stop talking on your personal reasons for not being motivated, that doesn't help motivate others either.
thx
KrazeeXXL
BORG Trouble Maker
BORG Trouble Maker
Posts: 2323
Joined: Sat Jan 03, 2009 3:00 am
Location: the 36th Chamber

Re: C++ Lesson 3: Classes

Post by KrazeeXXL »

tja, keine Ahnung, wieso ich mich dann dauernd genötigt fühle, mich hier erklären zu müssen...
User avatar
Flocke
BORG Trouble Maker
BORG Trouble Maker
Posts: 3197
Joined: Sun Apr 27, 2008 2:00 am
Location: Hamburg, Germany
Contact:

Re: C++ Lesson 3: Classes

Post by Flocke »

jub das weiß ich auch nicht :)
User avatar
Lathon
Lieutenant-Commander
Lieutenant-Commander
Posts: 116
Joined: Thu Oct 15, 2009 2:00 am

Re: C++ Lesson 3: Classes

Post by Lathon »

Just for the hell of it, I worked on this (using microsoft visual studio express 2010). I added where it keeps track of how many more games needs to be played for either value to win.

main.cpp

Code: Select all

#include <iostream>
#include <cstdlib>
#include <string>
#include "lesson3.h"

using namespace std;

int main()
{
	string input;
	lesson3 myInst1;
	lesson3 myInst2;
	while(true)
	{
		cout << "post some stuff" << endl;
		getline(cin,input);

		if(input.compare("n") <= 0){
			if(myInst1.turn()){
				cout << "myInst1 won! exit" << endl;
				break;
			}
		}
		else if(myInst2.turn()){
			cout << "myInst2 won! exit" << endl;
			break;
		}

		cout << "myInst1 has " << myInst1.turnsToVictoryDisplay() << " more to victory!" << endl;
		cout << "myInst2 has " << myInst2.turnsToVictoryDisplay() << " more to victory!" << endl;
		cout << endl;
	}

	system("PAUSE");
	return 0;
}
lesson3.h

Code: Select all

#ifndef LESSON3_H
#define LESSON3_H

class lesson3
{
public:
	lesson3();
	virtual ~lesson3();

	int turn();
	int turnsToVictoryDisplay();
protected:
	//it is in protected because only the class object uses it once turn is called
	void turnsToVictory();
private:
	// here define your member variables
	// for better encapsulation put them in private section
	// so they can't be accessed from outside the class
	int myPrivateState;
	int howManyRuns;

};

#endif // LESSON3_H
lesson3.cpp

Code: Select all

#include "lesson3.h"
#include <iostream>

using namespace std;

lesson3::lesson3()
{
	//ctor initialize member variables on creation
	// else they might contain anything
	myPrivateState = 0;

	//this keeps track of how more it needs to win
	howManyRuns = 11;
}

lesson3::~lesson3()
{
	//dtor
}

int lesson3::turn()
{
	// increment myPrivateState, use ++ preceding it
	// to increment before comparison
	//increment how many more turns it needs to victory
	turnsToVictory();
	if(++myPrivateState > 10)
		return 1;
	else return 0;
}

void lesson3::turnsToVictory()
{
	//keeps track of how many runs were done
	howManyRuns--;
}

int lesson3::turnsToVictoryDisplay()
{
	return howManyRuns;
}
Haleth
Ensign
Ensign
Posts: 23
Joined: Sat Sep 25, 2010 2:00 am
Location: Germany

Re: C++ Lesson 3: Classes

Post by Haleth »

Breen where did u found that preference i dont see it

mfg

Haleth
Anyone who has never made a mistake has never tried anything new.
Dr_Breen
Commodore
Commodore
Posts: 889
Joined: Wed Apr 30, 2008 2:00 am
Location: Zurich, Switzerland
Contact:

Re: C++ Lesson 3: Classes

Post by Dr_Breen »

help me a bit. what are you looking for? that topic is already a year old
Public BotF / EF2 Teamspeak 3 Server: 83.169.13.55
Post Reply

Return to “General Chat”