PDA

View Full Version : C++ Beginner Tut



Macrosoft
09-08-2007, 04:27 AM
Hi, I am unsure of whether this belongs in the C++ section or the Tutorial Island section. If It does not belong here, please tell me or move it.

Please REPLY

Just Finished Massive Update, Enjoy!

Introduction

C++ is a highly powerful programming language used in many professions. There are many rumors that it is difficult. In my opinion, that is bs, though C++ looks scary at first, doing more advance things become much simpler than many other languages. Once you understand it, it will become extremely easy.

I may add a section on how to download a C++ compiler, but right now it is late and I have to go to bed :(

In this tut I will be using Microsoft Visual C++ 2005 as my compiler.

You can download it here (http://msdn2.microsoft.com/en-us/express/aa700735.aspx)

Creating a New Project
First, open Microsoft Visual C++ and go to File>New>Project
In the project types half (left), click Win32 in Visual C++

Then Click, in the right half, Win32 Console Application.
Name the project and click Ok

A window should apear called Win32 Application Wizard. Click next and click empty project in "Additional Options"

Also make sure that Console Application is checked, in the Application type

Now click finish.

Now we need to make a source to type our code in, in the project menu, click add new item. Choose code in the catigories half(left) and C++ file on the right. Name it and click "add"

Now you have a place to type your code.
Variables/Data Types
C++ has the basic types that most programming languages have.
int means integer
bool is boolean
char is a single character
float is a floating point decimal number, or a number with a decimal
double is a double precision floating-point number
long int is a long integer
short int is a short integer
void means nothing

declaring a variable is simple, and can be done at anywere in the script, as long as it is before or when it is used.

First say the type of the variable, then say the name of the variable, and finish the line off with a semicolon.
example:

int x;Almost all lines are finished with semicolons to tell the compiler that the line is finished. The exceptions are includes, if / else lines, while loop lines, and for loop lines. a semicolon is also not needed after { and }, struct and class declaration lines. There are some other exceptions that will be explained later.

Notice there is no "string" type. You only have char , which is one character. A string can either be made from an array of chars(explained later) or including string.h, which gives you the string variable. Using the string variable is easier for beginners, but less useful for intermediates, you will see why later. Strings are always in "". There are ways to convert strings to char arrays and vise verse. They are both used for different things.

Constants
Constants are almost exactly like variables. To declare a constant, first say const then the type (int, float, char, etc) then the name of the const and finally an equal sign and what it equals. The name must be all caps as it tells the compiler that it is a constant.

example:

const int MYCONSTANT=2; // MYCONSTANT is now a constant that is an int that equals 2Includes

C++ is almost entirely based on includes. To include something, just use this format:

#include <Whatever> // whatever represents the include you want to includesome includes we will be using in this tut are


#include <iostream> //in out stream, needed for inputting and outputting
#include <string.h> //needed to use the string type
#include <stdlib.h> //standard library, needed for many thingsThere are an incredible amount of includes. Google is your best friend for finding these includes, just search what you need something to do in C++ and you should get an include for it. Some includes are in our compiler already, such string.h, stdlib.h, and iostream. Others will be like srl and you will need to install them.

Inputting and Outputting
Inputting and outputting are a huge part of C++. In order to input and output, you need to use the include iostream or in out stream. This enables you to use cout and cin. You are probably thinking, what the bleep do those words mean?? Well think of them like this: cout as c out and cin as c in. Get it now? As you may have guessed cout is used when you want the program to output something onto the screen, and cin is used when you want to declare the name of the already declared variable that, whatever inputed from the keyboard, will be stored in.

Whenever using Cout, you must follow it with the << operator, think of these symbols as pointing out. After using <<, you can output a text as a string in ""s or the value of a variable, which will not have "" around it. What if you want to first output "My age is" and then output a variable or const that equals your age (we will call it iAge, the i is for int, just a helpful reminder). then you would do:

cout<<"My age is"<<iAge;when what you are couting changes from a string to the value of a variable or const, and vise versa, you separate them with a <<. If you wish for it to end a line and continue on the next one, use endl (end line) or \n (new line). Remember to separate it with <<'s. Still confused about <<, think about + in scar...sorta. Basicly, << is used to separate different parts of the cout.

For those who think they get it, the << operator is actually saying, cout until a null ( \0 ) character is found. By putting something in ""'s, it is saying it is a string. It automaticly adds a \0 character to the end. If we put it in ' 's, then we would be saying its a character, and in order for it to be a string, it must have \0 at the end. Basicly, null says its the end of the string, and that what was before it was a string.

Take a guess what we use in place of << in cin. If you guessed >>, you are correct. Think of these as pointing into the computer. They are used the same way, only you are saying which variable the users input will be stored in.

The >> operator, reads the user's input, but only the first word, as it stops at the first space. If you wanted to get a whole line, or do other things, you could actually use other operators, such as cin.getline, and cin.ignore (part of the istream class). The << operator also has other operators, which are part of the ostream class. Cin is a istream class (it is a input thing) and cout is a ostream class. I will explain more when i get to classes (classes are advanced, and i don't want to confuse you yet ;))

in the next section, you will learn how to say how you want the info to be displayed on the screen.
Namespaces
When inputting and outputting and pretty much everything else, you need to specify how the info will be displayed. In this tut, we will always be using the standard namespace, std, which is pretty much a black, input output box. If we are using the box for the whole program, we say:


using namespace std; if we didn't say this, we would have to type std:: before cout, etc. everytime we want to output something. This can be useful if we want to use different namespaces for different things. Declaring a constant namespace always comes right after the includes.

Functions
Functions are declared by first saying the data type that will be returned, then the name of the function. After this, the user inputs when using the function are put in (). If no inputs when the function is used, then still put the (), just with nothing in them. DO NOT FOLLOW THIS WITH A SEMICOLON!

If you want the function to not return anything, then you use void.


example:
void lala()

{ and } are used to state the beginning or ending of a function or loop. The { should be put on the next line after the loop or function is declared. Then at the end, put a }. When you put the }, MS Visual C++ will make the } and the {, that goes with it, bold while you are on it to show you which one it goes with. (excuse my English lol)

Returning

Functions all have to return something. The thing it returns must be the data type you typed before the name of the function. The return can be based of of what the function has done, or it can not.

There are no "procedures", where nothing is returned, in c++, only functions. This is not a problem. The main loop is normally a "procedure" and shouldn't need to return anything, so what most people do is:

int main()
{
//bla bla, put ur code here
return 0
}We just returned something, and we don't care what it is because we are not going to use the return.

The Hello World Program...Taken Apart
I know what your thinking,"Oh god not again." The truth is, the Hello World program is a really good program to start with. It is more complicated in C++ than in Scar, but like I said, far more advanced things can be done with C++.

Here is the Hello World code, do NOT get scared, I will explain everything.
Copy and paste this into a source:

#include <iostream>
using namespace std;

int main()
{
cout<<"Hello World! This is my first program in C++"<<endl;
system("PAUSE");
return 0;
}
First I included iostream, or input/output stream for your

int main(); is declaring a function/procedure
int is the output data type, main is the name, and () is the input. Not that difficult.

look at this line and try to guess what it does:


cout<<"Hello World! This is my first program in C++"<<endl;This line is outputting the text in the "" and then, using endl, ending the line.

Once the program finishes, it will close the box in which everything is outputted and inputted. We want the user to see the text, so
System("PAUSE") does the press any key to continue thing.

System is a function, and "PAUSE" is one of the inputs. All system inputs are in all caps. The "" is because it is a string. You get the point.

Finally, we say return 0 because we have nothing else to return, it is a procedure.
In the main loop, it is better to have it be an int, rather than void. I don't know why, it just is.

Starting to become an Intermediate
Get ready to actually start getting into C++.

If Statements
If statements are a big part of programming.

They are declared easily:

if(a==0){
//bla bla, what to do if the above is true
}
else{
//bla bla
}Notice how I put == instead of =. This is because I am comparing 'a' and 0. If I had put a=0, then a would now equal 0. Before we move on, lets get familiar with some of these operators.
Some Useful Operators

== compares two integers, strings, etc. to see if they are equal (note: This will not work with a char array)

>= compares two integers, strings, etc. so see if they are greater than or equal to

<= compares to see if less than or equal to.

> compares to see if greater than

< compares to see if less than

!= compares to see if not equal

! "not" can be put in front of <, <=, etc. and will be true if not that. ! can also be used as "not" for pretty much anything else. (!a==3 is the same as a!=3)

= declares something to be equal to___

"Or" and "And"
Take the statements, q and p. They can be blala==whatever and something else too, but right now, p and q are booleans. Just like if we were to say 1==2 and it would be false, or 1==1 and it would be true, all statements are bools. Now view the table below.

http://img123.imageshack.us/img123/5265/cpptablebf6.jpg (http://imageshack.us)



Note how the statements with || and && change from true to false, based on what p and q are.

to be continued when i have more time...
More will be added later! I hope this was helpful. Please post your comments, I worked sort of hard on this.

Emagdnim
09-08-2007, 04:37 AM
If you don't ming me asking whats the difference between C and C++ i know theres something like C++ is object oriented not so sure what it is sorry if you don't know but this info would be nice to know

Macrosoft
09-08-2007, 04:52 AM
just about to go to bed lol

Yes the difference is c++ is object oriented, i may add stuff on that to the tut tomorrow. Object oriented programing is stuf like structs, classes, inheritance, all that advanced stuff

lets say i have a struct named student that consists of a name ( a string) an age (an int) and a grade (a char). within the class i can have public and private data, which is complicated so im not going to explain that right now.

lets say i want to add a function to the struct, so it does something with the variables as well

this would be a class.

I can also "inherit" the variables from the struct to the class, once again, complicated

basicly, you can have ojects, with many variables and functions within them.

In the beginning stages however, there is very little difference between c and c++, Though c++ is 10x as powerful.

lol if that makes no sense at all, its because its 2:00 am and im tired, explaining things isnt so easy right now

Dan Cardin
09-08-2007, 12:34 PM
aha! ive been waiting for this:p

havent read yet but when i do ill tell u how cool it is

edit:edit a little hard to understand, but most programming languages are(c++ is probly harder cuz u have to relearn programming if u already know like delphi or scar or something). ty though, u explained better than the other tut i read :D

mastaraymond
09-08-2007, 12:36 PM
Im going to read it ^^. Thanks,

~Raymond

Macrosoft
09-08-2007, 02:42 PM
if you dont already know some c++, i would suggest w8ing a bit because it was 2:00 when i wrote that, ill be editing and adding to it today

botmaster
09-08-2007, 03:00 PM
Very nice. But C++ tut's are of very little use to me. I need some kind of C++ library tutorial on the GNU C library. Maybe a bit too specific for these forums :p

Yea, nice tut! Keep 'em coming!

Macrosoft
09-13-2007, 06:44 PM
Just finished massive update, enjoy!

Also, is this the right forum? Maybe tut island is better...

I WILL NOT UPDATE THIS THREAD UNLESS PEOPLE ARE READING IT AND GIVING ME FEEDBACK!

Hugolord
09-13-2007, 06:54 PM
Hi, yes i think you should post leave it here.

and thanks for this m8!

--

Hugo

ShowerThoughts
09-13-2007, 07:05 PM
nice work. sorry for bump

Macrosoft
09-13-2007, 07:12 PM
lol dont worry about it, at least some people appreciate my work...now i have a reason to add random, arrays, datatypes, structs, and classes lol

Yakman
09-13-2007, 09:30 PM
i think this is really nice work, i only read through it once now, and i already learned quite a lot,
its obvious that you worked hard at it cause it explained everything in loads of detail and i dont think anyone will get lost reading it

i was trying to learn some c++, i downloaded DevCpp but i guess i just never hit it off.
i know some java, and c++ is really similar

im intrested in pointers though, they dont have them in java, and they seem quite useful, from what iv heard they are an integer which refers to an object or array or something, iv probably got it wrong, but oh well *looks on wikipedia*

also, whats the differance between a .cpp file, .h file, .c and all those other extentions..

good job once again

Macrosoft
09-13-2007, 11:10 PM
Yes, yakman, your questions get into the advanced section of c++. I am now working on explaining these things. It is stuff like that that makes c++ different than c.

The Next Update of this thread will include:

-Pointers
-Random
-Arrays
-Possible some object oriented stuff like classes and structs
-Possible inheritance
-Data types
-.h and .cpp files, the difference

I can tell you now, that .h files are headers that can be included. Notice string.h can be included. They are like libraries that you can make and include yourself. Source files are the actual code that tells the computer what to do.

If you want, i can pm you when the next update comes out. I will also be adding a c++ graphics area. Not next update though becuase i need to learn it myself first lol. Dont worry, Im a fast learner, I learned all of what I know in c++ in a week!

lardmaster
09-14-2007, 12:56 AM
pointer is the address of a variable.

pointers in 45 seconds:

int imanint;
int* imapointertoanint;
imanint=5;
imapointertoanint=&imanint; //(the & is the adress operator, getting the "location in memory" of imanint, so imapointertoanint "points" to imanint.)
cout << imanint; //prints 5
cout << imapointertoanint; //prints some larger number which is location in memory of the integer;
cout << *imapointertoanint; //prints 5 (* dereferences pointers, meaning it returns the variable in the location that the pointer is pointing to)
imanint=20;
cout << *imapointertoanint; //prints 20, because the variable that it is pointing to is now 20.

*imapointertoanint=40; // i believe this also works, making imanint equal 40.

this is usefull, so you can pass a pointer to an integer, much in the same way you pass var: arguments in scar.

however, you can also get in trouble, because you can do

&213456=127423; //this sets the memory location 213456 to equal 127423, regardless of what is there! this could erase important information and cause the system to crash.

pointers allow other wierd things, like two integers in the same location in memory, so modifying one automatically modifies the other.

in java, all OBJECTS are ALWAYS passed by reference(as pointers), but all PRIMATIVE TYPES, are NEVER passed by reference.


about file extensions:

.c: C program.
.cpp: C++ program
.h: header file, defines constants, macros, and also outlines the methods of a class.
.o: object file, created in the process of compilation. you never should need to mess with these.

Macrosoft
09-18-2007, 01:39 AM
um, Im not updating until i get more replys ...ok... thats stuborn... just reply lol, i have to know people enjoy this because iv put a lot of time and effort into it. I wont put any more if nobody is reading it...

Dan Cardin
09-18-2007, 10:59 AM
u know i'm trudging along :)

i really want to learn c++ but i dont like the
{
cout "blblblblblblbl" endl <<
}

lets hope thats right cuz i didnt look at the tut when i wrote that ;)
(i didnt add the other stuff u put at the top)

edit: oops, more studying to go

int main()
{
cout "i love u" <<endl;
System("PAUSE");
return(0);
}
(didnt look at time either(after i looked at it some more though :p)

Macrosoft
09-23-2007, 01:26 PM
u know i'm trudging along :)

i really want to learn c++ but i dont like the
{
cout "blblblblblblbl" endl <<
}

lets hope thats right cuz i didnt look at the tut when i wrote that ;)
(i didnt add the other stuff u put at the top)

edit: oops, more studying to go

int main()
{
cout "i love u" <<endl;
System("PAUSE");
return(0);
}
(didnt look at time either(after i looked at it some more though :p)


try this


int main()
{
cout<<"I love you"<<endl; //need << to separate cout and the other stuff
System('PAUSE");
return(0);
}


I will prob updatte this withen the next 2 weeks, lol, lots of hw

gamer716
09-26-2007, 10:24 AM
wat is c++ used for?

Macrosoft
09-26-2007, 07:16 PM
...everything and anything, C++ is one of the most common used and powerful programming languages. You can do pretty much anything with it.

zenma
10-01-2007, 12:02 AM
thx, this tut helping me get started

Macrosoft
10-01-2007, 08:25 PM
your welcome

Sorry about not updating this tut for a while, i am currently applying for srl membership

neG
10-06-2007, 12:47 AM
Gratz on getting Membership man.
You deserve it.

Macrosoft
10-06-2007, 04:12 PM
thanks

Dan Cardin
10-14-2007, 10:07 PM
so if statements are prettymuch like scar/ lots of others except u have to put {}'s ? and if i wanted to leave out else it would be

if(z==15){
//stuff
}

and the whole thing would be

int Main()
{
if(z==18){
cout<<"I pwn u cuz im 18!!! and not 19 or 17"<<endl;
}
}?

the table thing confused me :(

for and its always gonna return false if theres a false? and opposite for or?

Macrosoft
10-14-2007, 10:21 PM
im not done with if statements yet

the table just shows what each operator does (and and or)

it just shows that or is only true if one or both of the statements are true, and "and" is only true if both statements are true. Some people like a visual :p

Dan Cardin
10-14-2007, 10:32 PM
oh!! now that u explained it i get it...though i new it before from delphi/scar but i wasnt thinking and the table confused me:p

EDIT: i really like ur sig :)

Macrosoft
10-14-2007, 10:45 PM
lol

Edit: THanks about sig, im a nooby photoshoper, I need practice so if you want, ill try to make one for you

HairyDuncan2
10-16-2007, 10:47 AM
Thanks, I know now some of the basics..

Gunna go look for some more tuts.

:D Cheers

NxTitle
10-20-2007, 04:50 PM
The difference between C and C++, the way I see it:

1. In C, all includes are <something.h> and C++ includes are <something>
now, it is possible to have a C++ header with .h and a C header without, but in the Standard, that's usually the way it works.

2. To print something in C, you would use printf("text"); and in C++ you would use cout << "text";
of course, in C you need to #include <stdio.h> and in C++ you need <iostream> for these functions to work. If you know the basics of stdin, stdout, and stderr, then the C++ functions will seem familiar. For stdin, you just use cin >> var to get a variable, for stdout you use cout << "text" and for stderr you use cerr << "text".

3. C has structs, and C++ has classes.
structs and classes are very similar, it's basically the same thing, but one can hold functions and the other can't. There are also two ways of initializing a class, and only one way of initializing a struct.
An example of using a struct would be:

StructName banana;
banana.variable = 5;An example of using a class would be:

ClassName banana;
banana.variable = 5;
int thing = banana.CallVariable();
or

ClassName banana = new ClassName;
//so on and so on...
now, as you can see, they are very similar, almost to the point that they are almost the same.
you can also access pointers in structs and classes. Instead of using banana.variable, you would use banana->variable.

Now, even though that sounds like a lot, that only what you need to begin in C++. In fact, that still isn't enough. I recommend you go to www.cplusplus.com (http://www.cplusplus.com) and look at the tutorials there for a complete understanding of how C++ works.

I also recommend that if you want to really use C++, get Dev-C++ instead of using Visual C++, for numerous reasons. One, it is a much cleaner interface, and uses up all the space in the frame for something instead of having big gaps. Two, it has what are called Devpaks. These make it very easy to install big libraries like SDL or WxWidgets, for example. you can find these devpaks at www.devpaks.org (http://www.devpaks.org). Once you download one, just run it, and it will go through a readme, automatically install, and then you're ready to go. Third, it's open source. Now, this isn't usually a big deal for IDE's, but I just prefer open source better :p.

Well, that's about it. Go have fun learning C++!

(also, sorry about the format of my paragraphs being so crappy. I wrote this up in about 10 minutes.)

Macrosoft
10-27-2007, 04:11 AM
C++ has structs too!

NxTitle
10-28-2007, 12:21 AM
yes, C++ has everything that C has and more.

Macrosoft
10-28-2007, 11:15 PM
the ppl who say learn c and then go to c++ dont know anything lol