__old C++ Lesson2: Some Basics

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

Moderator: thunderchero

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

__old C++ Lesson2: Some Basics

Post by Flocke » Sat Jun 02, 2012 7:08 am

C++ Lesson2: Some Basics to develop with C++

ATTENTION, THIS LESSON GOT SPLIT,
THERES NO NEED TO READ THIS ANYMORE!!!

instead refer the following:
C++ Lesson2: Introduction
C++ Lesson3: Classes



==============================================================================
Previous: C++ Lesson1: Preparations
Follower: --

First, don't be shocked by the long post, like previous lesson it's actually far easier than it does look like.
However this time you've much more room to experiment.
As always I'm around for help and questiones. :!:

In last lesson I showed how to set up MinGW GCC with Code::Blocks as a development environment. We also did build a simple "Hello World" program to proof the installation works.

This lesson you're going to build your first own program and get in touch with some C++ basics.
Normally you'd first read through a whole book of what the languague has to offer, but I'll skip that, we don't need all the details. That I'll leave for next lesson. 8)

As by of now all of us (should) have a working environment to test, I hope to have some more discussion. :)

=======================================
code structure

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.
All that will become more clear in the samples.

You probably already noticed all the different colors the code is represented in by your Editor.
That makes the code much more readable and you'll soon find a grasp on.
Let me build on last "Hello World" example.
#include <iostream>

using namespace std;

int main()
{

cout << "Hello world!" << endl;
return 0;
}
Lines beginning with a # symbol are pre-processor directives, so called "macros". They get evaluated before the compiler is invoked when you build an application. In this sample there's only one single include to link in a different file named "iostream". You could copy the whole content of that file and gain the same.
iostream is part of the std library and defines cout and endl as well as the << operation on it.
to avoid naming conflicts it encapsulates all defined variables, functions and classes in a namespace. As Lathon told last lesson, "using namespace std;" tells the compiler to get all of those out of their namespace and access direct so you've less to type. Still they are accessible by their namespace, so if you have your own cout defined you could print std::cout to access the one defined by iostream.

In this sample there's just a single function named 'main'. main is a special function that is called by the os when you start the program. In Windows gui applications it looks a bit different, but for console applications and linux coding "int main()" is standard. In Java you define a main function as part of a class body, here in C and C++ it's always a standalone function.
In the end of that function you return 0 to the calling function, in this case to tell the os that no errors occured. The return is of type int which is an integer.

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 the main development concept of C++. It's the key for object oriented programming with C++.
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.

Think I've talked enough of code structure for now, let's go on with some practice.

=======================================
practice with C++ classes

Start with previous "Hello World" example.
Now create a new class using File->New->Class in Code::Blocks.
It gives you a prompt, enter a name for your class, 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.

If you try to compile right now, it might fail with telling that it couldn't find your header file.
That might be only with me as I might have changed some settings by the time, but if so it is cause we didn't tell where to look for your header files yet.
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 add include

In the header file, first there's a guard using define macros to not declare things multiple times.
The class declaration is devided into three sectiones: 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.
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, create an instance of your class by typing your_class_name myClassInstanceName;
afterwards call your new method by myClassInstanceName.myMethod();
Test to get that work.

=======================================
build your own application

Here comes the fun part.
Open your main.cpp, we'll add a while loop that does not halt before key input.
In that loop you call your class to let it perform some action, do some crazy calculations, whatever.

Remove following portion of your main:

Code: Select all

cout << "Hello world!" << endl;
system("PAUSE");
Then place this instead:

Code: Select all

string input = "";
while(input.compare("exit") != 0)
{
	cout << "post some stuff" << endl;
	getline(cin, input);
}
Next make use of your class method, call it inside the loop but define the object instance before of that loop so it doesn't get constructed and destructed each loop iteration.
Now inside your class header, add a member variable to the public section. e.g. use an integer, simply declare it as int myint;
In your constructor, assign zero to your int so it's sure to be zero also in release mode: myint = 0;
In your method do some calculation with your integer. Use add + substract - multiplicate * or devide /.
You'll find more on the web if you want. One very good reference I've already posted is http://www.cplusplus.com -> http://www.cplusplus.com/doc/tutorial/operators/
Print your result to the console simply by cout << myint; no need to start another line.

One last very useful construct to your program are the if and else clauses.

Code: Select all

if(myint < 77){ myint = myint + 3; }
else{ myint -= 10; }
or

Code: Select all

if(input.compare("BotF") > 0){
	cout << "nothing is greater than BotF, type something else!" << endl;
}
Have some fun and share your results. 8)
Last edited by Flocke on Thu Jul 05, 2012 11:23 am, edited 3 times in total.

User avatar
thunderchero
Site Administrator aka Fleet Admiral
Site  Administrator aka Fleet Admiral
Posts: 6213
Joined: Fri Apr 25, 2008 2:00 am
Location: On a three month training mission, in command of the USS Valiant.
Contact:

Re: C++ Lesson2: Some Basics

Post by thunderchero » Sun Jun 03, 2012 11:43 pm

Well last night I spent some time on lesson 2,

I think I have though this line correct.
"C:\folder\folder\folder\folder\folder\folder\myproject and your includes lay in myproject\include just add include"

But even after reading a few time I am unclear of objective of the lesson. Or really what to do next.

I am sure Flocke will talk me though on ICQ lol :roll:

thunderchero

User avatar
QuasarDonkey
Code Analyst
Code Analyst
Posts: 433
Joined: Tue Jul 26, 2011 8:29 pm
Location: Ireland

Re: C++ Lesson2: Some Basics

Post by QuasarDonkey » Mon Jun 04, 2012 1:15 am

He just means that the folder paths are relative when you include header files. You probably don't need to worry about the header files unless you're actually using any.

Just skip to the "build your own application" part :)

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

Re: C++ Lesson2: Some Basics

Post by Flocke » Mon Jun 04, 2012 3:27 am

QuasarDonkey wrote:Just skip to the "build your own application" part :)
I think part2 "practice with C++ classes" is important to accomplish part3.
part2 mostly is just talk again. Task of that part is to add one class and make sure it compiles.
If it fails and tells that it couldn't find the header file for your class, you've to adjust the include pathes for your project the way I've told. For that it's better not to use the full disk path name but keep it relative to your project folder, but both does work.

Maybe talking of "practice" with part2 was a bit misleading as the real practice actually comes with part3, the "fun" part. ;)

In part3 I expect some funny textual programs that give response on user input. But you can come with something different as well. E.g. you could change the while loop or create anotherone to print stuff to the console till your calculations reach a specific state. You also could use class methods to perform in different modes.
All essential for it is given to you. When compile fails, try to make use of the error message.
If your application doesn't do what you wanted it to do, try to debug it line by line.

As there are lots possibilities with part3, and you're still new to C++, questiones are expected.
You also may present a simple solution first and then go on to make it a bit more complex or try something else.

When presenting your results, please upload your sourcecode so others can see what you did, give some tips to do it better and make sure your program doesn't delete their disk or something else not so funny. :)

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

Re: C++ Lesson2: Some Basics

Post by Flocke » Thu Jun 07, 2012 4:14 pm

If you're having trouble deciding what to program in the own app task, I have an idea for you:
One could start with a very simple output, upload the source, and in turn the others start extending it. This way the class methods also become more of a use, as everyone can implement and test their own stuff and just copy over their methods and call them in some places.
This could become very funny I think.

What you say?

User avatar
thunderchero
Site Administrator aka Fleet Admiral
Site  Administrator aka Fleet Admiral
Posts: 6213
Joined: Fri Apr 25, 2008 2:00 am
Location: On a three month training mission, in command of the USS Valiant.
Contact:

Re: C++ Lesson2: Some Basics

Post by thunderchero » Sat Jun 09, 2012 9:01 am

ok I coped and pasted the first part but get error on compile

removed

Code: Select all

cout << "Hello world!" << endl;
system("PAUSE");
pasted

Code: Select all

string input = "";
while(input.compare("exit") != 0)
{
   cout << "post some stuff" << endl;
   getline(cin, input);
}
||=== hello, Debug ===|
C:\Documents and Settings\Doug\My Documents\downloads\c++\lesson 1\hello\main.cpp||In function 'int main()':|
C:\Documents and Settings\Doug\My Documents\downloads\c++\lesson 1\hello\main.cpp|8|error: 'string' was not declared in this scope|
C:\Documents and Settings\Doug\My Documents\downloads\c++\lesson 1\hello\main.cpp|8|error: expected ';' before 'input'|
C:\Documents and Settings\Doug\My Documents\downloads\c++\lesson 1\hello\main.cpp|9|error: 'input' was not declared in this scope|
C:\Documents and Settings\Doug\My Documents\downloads\c++\lesson 1\hello\main.cpp|11|error: 'cout' was not declared in this scope|
C:\Documents and Settings\Doug\My Documents\downloads\c++\lesson 1\hello\main.cpp|11|error: 'endl' was not declared in this scope|
C:\Documents and Settings\Doug\My Documents\downloads\c++\lesson 1\hello\main.cpp|12|error: 'cin' was not declared in this scope|
C:\Documents and Settings\Doug\My Documents\downloads\c++\lesson 1\hello\main.cpp|12|error: 'getline' was not declared in this scope|
||=== Build finished: 7 errors, 0 warnings ===|

help

EDIT; here is my current main.cpp

Code: Select all

#include <cstdlib>
#include <iostream>

int myint;

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

    myint = 0;
}
thunderchero

User avatar
Lathon
Lieutenant-Junior Grade
Lieutenant-Junior Grade
Posts: 95
Joined: Thu Oct 15, 2009 2:00 am

Re: C++ Lesson2: Some Basics

Post by Lathon » Sat Jun 09, 2012 9:18 am

Well, you need two things. first, you forgot the "system("pause");", and return 0 part at the end. and when you are using strings, unlike java, you have to include the call to it. so it would be like this

Code: Select all

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;
int myint;

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

	myint = 0;

	system("pause");
	return 0;
}

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

Re: C++ Lesson2: Some Basics

Post by Flocke » Sat Jun 09, 2012 9:30 am

Lathon wrote:Well, you need two things. first, you forgot the "system("pause");", and return 0 part at the end. and when you are using strings, unlike java, you have to include the call to it. so it would be like this
Thumbs up for your fast response!
Thumbs down for the answer! ;)

in the beginning thunderchero missed:

Code: Select all

using namespace std;
and in the end ofc

Code: Select all

return 0;
that's all

string is included by iostream header and system("PAUSE") he doesn't need as the while does loop till the user types in "exit" so also the cstdlib include can be removed. :)

Further thunderchero skipped adding a class and put an int above main and initialized it before the end of main which doesn't make any sense. 8)

User avatar
thunderchero
Site Administrator aka Fleet Admiral
Site  Administrator aka Fleet Admiral
Posts: 6213
Joined: Fri Apr 25, 2008 2:00 am
Location: On a three month training mission, in command of the USS Valiant.
Contact:

Re: C++ Lesson2: Some Basics

Post by thunderchero » Sat Jun 09, 2012 10:18 am

Ok I have first part, now I just need to add some "if and else clauses"

first line was generated by exe, and second line was my input and closed on enter.

Image

have some fun everyone :wink:

thunderchero

Dr_Breen
Commodore
Commodore
Posts: 889
Joined: Wed Apr 30, 2008 2:00 am
Location: Zurich, Switzerland
Contact:

Re: C++ Lesson2: Some Basics

Post by Dr_Breen » Sun Jun 10, 2012 5:48 pm

I'll be in vacation for the next 2 weeks. keep going guys i'll catch up later
Public BotF / EF2 Teamspeak 3 Server: 83.169.13.55

User avatar
Lathon
Lieutenant-Junior Grade
Lieutenant-Junior Grade
Posts: 95
Joined: Thu Oct 15, 2009 2:00 am

Re: C++ Lesson2: Some Basics

Post by Lathon » Sun Jun 10, 2012 11:08 pm

string is included by iostream header and system("PAUSE") he doesn't need as the while does loop till the user types in "exit" so also the cstdlib include can be removed. :)
I hate brain farts............I completely forgot about that. Meh, it didn't cause too big of a hick-up ;)

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

Re: C++ Lesson2: Some Basics

Post by Flocke » Tue Jun 12, 2012 12:09 pm

Tough start here.
xDx, anjel, go on! wanna see results! :twisted:
breen I know will easily catch up :)

Talking with thunderchero I realized you need more help on the brackets.
these brackets encapsulate code to specify the body for while, if and else clauses and also define a scope to release resources, but more on scopes next lesson.
And I wanna give you a simple sample to extend now.

Code: Select all

#include <iostream>

using namespace std;
int main()
{
	string input = "";
	int myint = 1;
	while(input.compare("exit") != 0)
	{
		cout << "What shall I do?" << endl;
		getline(cin, input);

		if(input.compare("play BotF") == 0)
		{
			cout << "pefect! :D" << endl;
		}
		else if(myint > 5)
		{
			cout << "hey that's already try no." << myint << endl;
			cout << "find something better!!" << endl;
		}
		else
		{
			cout << "nah, come on!" << endl;
		}
		myint = myint +1;
	}
	return 0;
}

User avatar
thunderchero
Site Administrator aka Fleet Admiral
Site  Administrator aka Fleet Admiral
Posts: 6213
Joined: Fri Apr 25, 2008 2:00 am
Location: On a three month training mission, in command of the USS Valiant.
Contact:

Re: C++ Lesson2: Some Basics

Post by thunderchero » Tue Jun 12, 2012 3:05 pm

Ok after many tries and talking to Flocke on ICQ I got some changes made.

(sorry Anjel I had to pick on someone) :wink:

Image

I will post my code but in "1" font :wink: just use quote to see code

Code: Select all

#include <cstdlib>
#include <iostream>

using namespace std;
int main()
{
   string input = "";
   int myint = 1;
   while(input.compare("exit") != 0)
   {
      cout << "Who has not done lesson 2?" << endl;
      getline(cin, input);

      if(input.compare("Anjel") == 0)
      {
         cout << "Correct" << endl;
         cout << "You got it correct on no." << myint << " try" << endl; break;
      }
      else if(myint > 1)
      {
         cout << "no." << myint << " wrong attempt"<< endl;
         cout << "Thats not the person I was looking for guess again" << endl;
      }
      else
      {
         cout << "Thats not the person I was looking for try again" << endl;
      }
      myint = myint +1;
   }
    system("PAUSE");
    return 0;
}
[/size]

thunderchero

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

Re: C++ Lesson2: Some Basics

Post by Flocke » Tue Jun 12, 2012 5:42 pm

nice, you're making progress, think you worked enough on it for now
the next may extend it or present an own more complex solution
and try to get it work inside a class method the way I told

help is around, just try & ask ;)

User avatar
anjel
Past Administrator
Past Administrator
Posts: 666
Joined: Thu May 08, 2008 2:00 am
Location: Bs As - Argentina

Re: C++ Lesson2: Some Basics

Post by anjel » Tue Jun 12, 2012 6:27 pm

i´ll be back on track asap :)
Live long and propser

Post Reply

Return to “General Chat”

Who is online

Users browsing this forum: Patrick280