Beruflich Dokumente
Kultur Dokumente
~
Nearly every programming language tutorial starts with a "Hello World" program.
Well, lets start with that, but explain it completely.
#include <iostream.h>
int main()
{
cout<<"Hello, World!\n";
}
Compile the above program and congratulations! You're a C++ Programmer!!
!! You've made and compiled your first program!!!
Now, lets examine this program:
Line 1:#include <iostream.h>
"#include" tells the compiler to take the file "iostream.h" and make the functio
ns in it ready for use. Anything in C++ that starts with
"#"(pound symbol) is called a "preprocessor directive". What is a preprocessor d
irective, you ask? First off, the preprocessor is a
thing the compiler does before reading the code.
Now, you might know what iostream.h does, but if you don't, it defines all the f
unctions required for input/output. You see "cout"? That
is one of them. "cout" is what you type to tell the compiler that everthing foll
owing the "<<" is to be printed to the screen. The "<<" is
there to take everthing following it and do the "cout" function on it. It is req
uired for cout to work correctly. The "<<" are directives
telling that take the following information and do all the functions of cout on
it.
Line 2:(blank)
In C++, spaces and returns are not required. You can take out the spaces and ret
urns in this program and it will run correctly. But, you
can't take out all the spaces and returns. You need them for certain things. Her
e is a very brief list:
*Spaces must be between a variable name and the data type (we'll talk about thos
e a little later)
*A return must be after any preprocessor directive (again, we'll talk about that
later on)
*The "no spaces/returns" rule does NOT count for quotes. You type things in quot
es exactly how you would write it on paper.
And many more will be covered as we go on. If you feel confused now, don't worry
. I will cover everything I talked about so you know
and understand everthing.
Line 3:int main()
This probably looks confusing if you know nothing of C++, so let me explain. "ma
in" is a *required* function in every program. If you
don't have it in your programs, the compiler will have an error and it won't com
pile. That is because "main" starts the program's
operations. It can be anywhere in your program, but it must be there. Think of i
t as the script of the program, in that it has the order
and rules to run the program. If you have multiple functions, you call them all
from main in the order that you want them to happen. For
example, here is a program with 2 functions, but main calls the second function:
#include <iostream.h>
void multiply();
//If there are multiple functions other than main(),
you MUST declare them at the beginning of the program
int main()
{
cout<<"An example of multi function programs!\n";
multiply();
}
void multiply()
{
cout<<"2*2=4";
}
You see how important main() is? "multiply" would never happen if it is never ca
lled, so since no other function is calling it, main() calls
it and it does the contents of "multiply()". Now about the "int": "int" means t
hat the function has a return. You can also use void, but this is not ANSI stand
ard,
so you may not use void with main(), because main returns 0, ending the program.
There is a line in C++ that tells the compiler when the program has stoped and
finished. It is NOT required, but it won't hurt to add it. It is written as "ret
urn 0;". Thats the return that I am talking about. The "0" means
that the program has finished executing, and the application ends. The applicati
on is still open, but there is no more commands to do.
Most ANSI compilers, like Dev C++, put the line in by itself, so that is why it
is not required. We'll talk more about "int" a little later on.
But for now, thats how it works. The parentheses are used with nearly every call
in C++, and they are there to tell the program what variables
to carry with it. The stuff that goes in the parantheses are called "arguments".
You shouldn't worry, as they are really just for more advanced
C++.
Line 4: {
This is what you write to say that the function is going to execute. It starts t
he function, and it starts executing until the end bracket is
reached.
Line 5:cout<<"Hello, World!\n";
As described above, "cout<<" is how you output something to the screen. Everythi
ng after the "<<" is printed to the screen. So here,
the quotes are taken out, as they just hold the text to print, and Hello, World!
is printed to the screen exactly like that. Now, what about
the "\n"? "\n" is one of the "escape commands", or a command that does something
simple to the text. In this one, "\n" is used to tell
the program to skip to the next line and continue from there. The "\n" is not pr
inted, as anything that starts with "\" in quotes is considered
an escape command. Here is a list of alot of them:
\n --Skips to the next line and continues from there
\t --Does what the "tab" button does. It indents about 3 space
s.
\\ --It prints a "\" to the screen
\' --It prints a single quote to the screen
\" --Prints a double quote to the screen
This is all that will be used often by you. Memorize it because it is used quite
is in the default directory the compiler has set for include files,
file name between "<" and ">", like <iostream.h>.
is in the directory that the source code is in, you put the file nam
double quotes, like "iostream.h".
Really the only time quotes are ever used for including files is if you created
a new include file in the same directory and need to use it. Otherwise
everything you need is in the compiler's directory and just use the "<" and ">".
All the include files in this tutorial use < and >.
Understand? Good, because lets continue! Now, a good rule to remember is that in
clude files are not named that all the time. Sometimes they are
called "header files". We'll call them either from now on. C++ is nearly useless
without header files, because most of the definitions to communicate and
do advanced things are in several header files. So how do programmers learn all
about every header file? Well, in school the important ones are taught and used.
Also some people, like me, look through the files for things they need. Usually,
header files come with comments in them describing functions of some variables.
Otherwise, the developer figures it out based on statements around it and the va
riable name. I will tell you about different functions in include files as we go
on.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 3:Variables
~
Variables are names of memory slots that store information based on the data typ
e. Example:I could define "bigNumber" as a variable to store
numbers. Think of variables as dogs. Say you have a dalmation that is named Spot
. In C++, this would be written as "dalmation Spot;". The
data type is dalmation, and the variable name is Spot. Variables are easy to und
erstand as they relate to the real life system of naming objects.
A variable name could be anything, but it can't be any reserved words (words tha
#include <iostream.h>
int main()
{
char in1, in2, in3;
cout<<"Enter 3 letters: ";
cin>>in1>>in2>>in3;
cout<<"\nThe letters you have inputed are "<<in1<<in2<<i
n3<<" .\n";
}
Another very important rule is to save as much memory as possible. If you use a
data type alot of times in a program just to get the same type of input, define
the
variable at the beginning of the program. If you define it at the beginning of t
he program, the defining part must stay out of functions to make it global, or u
sable in any
function without multiple definitions. Heres an example of "global defining", or
defining variables at the beginning of the program for use in any function with
out redefining it:
#include <iostream.h>
char input; //I defined it before any functions are called, and I can now use
it in every function without having to redefine it
The reason to do this is to save memory. Say I create a calculator program and w
ill constantly be using an int data type variable to get input. Instead of call
ing it over and
over again taking up memory, I can define it like above and be able to use it an
ytime without redefining it. What if I already used it and it is storing someth
ing? Simple-it gets deleted and replaced with the new input. Like if it is crea
ted as a global variable and I use it to get info in the function "void getInput
()" but then use it to get input in the function "void getMore()", the input fro
m "void getInput()" is erased and the new input from getMore() is stored.
**IMPORTANT:To use global variables, you MUST declare them at the beginning of t
he program. Otherwise they won't be global. Also, if there are multiple functio
ns in a
program, you MUST declare them at the beginning as well. For example, if I had a
nother function in addition to main(), I would have to declare them at the top l
ike this:
#include <iostream.h>
void anotherFunction();
That is required for functions other than main(). The function definition is cal
led a "prototype".
Homework:
Create a program that gets 3 long ints from the user. Then add them together in
side a cout<< line using the "+" sign to add. The answer is in the Ch. 3 example
s folder
included inside the main Examples folder.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 4:Producing Grea
t software
~
C++ can do a truckload of things. It can calculate things easily and quickly eve
n a human gets confused by, store multiple inputs, keep histories of usages, cre
ate files, and
a motherload of things. But when you learn C++, and basically any language, you
will begin to understand why creating programs that are extremely useful is the
goal of
learning a computer language. It can be useful for your own use, or you can make
it useful for a huge company. Some examples of programs that make the world sta
y
accurate and updated are:
*Banking software
*Satelite systems
*Virus protection
*System software
*ATM machines
*Stock market
*Anything that is stored or relies on computers
See how important programs are? That's why so many people learn computer languag
es. They want to be part of those software needs. But what if alot of those prog
rams
didn't work or had to many needs to run? That's what this lesson, or should I sa
y explanation, is about. When you learn C++ and any computer language, you are l
earning
how to run the very maching you are using to read this. You can now customize th
e computer to do what you want, instead of relieing on companys to do it for you
. But, to
make your software needed and useful, you must follow 3 simple steps: Easy to us
e, as independent as possible, and as useful as possible. A good example of this
is the
system software you are using right now. It is easy to understand, gives you alo
t of resources to use for your own uses, doesn't require much more than a proper
computer,
and is required to run anything. A bad example is a program that crashes often,
takes up alot of resources, is based solely on you knowing what it wants, and re
quires alot
of things. Remember this line: Easyness sells. You wouldn't buy a program that d
oesn't give you an easy interface and requires alot of thinking. So when you mak
e your
programs, you should try to make them as good as possible. You want people to us
e your software. People won't use it if it performs poorly. Of course, every pro
grammer
has fun with programming. Some people create programs for entertainment, and som
e create programs that do nothing but are made simple to pass time. I have inclu
ded
2 examples, one that is a bad example of software, and one that is a good exampl
e of software, in the Ch. 4 example folder inside the main Example folder.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 5:Comments
~
Comments are in about every programming language. They are there to add a commen
t about whats going on in the code. The compiler ignores them. In C++, there a
re
2 different styles of comments: one from C, and one that is new. Here they are:
/* <----Start of C style comments|End of C style comments----> */
// <---------Start of C++ style comments. This type ends the line and t
he rest of the line is considered a comment
Is there a difference between them? Yes. The C style is able to be put in the mi
ddle of any line and close them up to continue with the code. The C++ style ends
the line
completely and you must skip to the next line to continue with the code. Here ar
e two examples of each style:
int main() //These are C++ style comments. I must skip to the next li
ne to start main(). This line has ended.
~
int main(/*Comment*/) /*These are C style comments. You see how I put a
comment in between the parentheses? I can because they are closable.*/
See the difference? They are intechangeable, so you can use either style anytime
. But the C style MUST be closed with */ . If you open the comment up but don't
close
it, the rest of the code is considered comments. Now, people like doing neat thi
ngs with comments. I personally I seen tons of source code, and nearly all of th
em had
"comment special effects". It is optional and programmer puts them there just f
or decoration. Here are 3 examples:
/*
*This is one style of comment side effects.
*I call these "rope style" because it looks a rope of stars.
*Call them whatever you want. Looks cool, huh?
*/
/****************Here is one liner effects. These are preferably for one
line comments, but you can use them on multiple lines.*******************/
/****I call these "Apple comments" because I used to program Macintoshes
and frequently saw Apple coding. Alot of them had this style.********/
/****The style here is that the comment line ends and starts again on th
e next, each time closing it and reopening on the next line. See--------->*/
They, again, are optional and are used simply for decoration. Get creative. You
can do anything in the comments because the compiler simply ignores them and sk
ips over them. You just need to open and close (C style) correctly and no worrys
. But the thing to using comments is that you must try to keep it quick and simp
le. If you get coding from big
companies, they will usually include a copyright notice, disclaimer, and sometim
es edit history. They don't include comments just there for enjoyment and have n
othing to do with the code. Don't use comments to include things other than nece
ssary things or things that will aid in understanding the code.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 6:Math operators
~
In C++, math is a very rich and large section. C++ can do just about anything in
math. It can find square roots, do scientific caculator commands, find remainde
rs, use
decimals, and more. Most of the symbols are the same, except for 3: multiplicat
ion, division, and modulus. Modulus is a method that finds the remainder of num
bers.
The symbols used are:
* =multiply Ex. 8*2=16 (thats an asterisk. Press shift-8 to write)
/ =divison
Ex. 8/2=4
% =modulus Ex. 8%3=2
Most of the more complicated functions, like square roots, are found in math.h.
Here is a list of just a few of the functions in math.h:
FUNCTION:
()
| In math statements, whatever math operation is in the parentheses
gets solved first and then everything else. If there are multi "()"'s, then it g
oes right to left order.
<
| Less than. Used mostly in math statements, but a few times in functi
ons.
>
| Greater than. See description for <.
Use these when needed. They all can be used in math, but some, especially the la
st 4, can be used in anything, like testing statements (see next chapter).
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 7:For, while, and do loop
s
~
In C++, there are functions that start a loop of events. Just like in real life,
we have the process of loops. We eat breakfast, lunch, and dinner in a constant
loop everyday.
That's what C++ is like. Except that it has 3 types of standard loops. They are
used differently, but create the same effect: a loop. First, we'll talk about a
"for" loop.
6.A: For loops
~
"for" loops are loops that use variables to declare the starting point and endin
g point, or when the loop will stop looping and happening. To use a "for" loop,
you need to make an integer. There are probably different ways to use variables
in a for loop, but for now we will start off with a simple integer variable rese
rved only for our "for" loop. So, define your integer variable in the function y
ou will use it. It can be called anything (remeber good variable naming etiquett
e). Now, I will create a model of a "for" loop. You will probably not understand
most, if not all, of it, but that's alright. I will go over it. Here's the mode
l:
What the variable's currently equal to (defaultly 0) | The variable needs to rea
ch 10 to stop
/ | \
/
| \
for(variableName=0;variableName<=10;variableName++)
\ | /
Add 1 to the variable
every completed loop
{
~loop contents~
}
Confused? Don't worry, I am now explaining it. We first start off with the word
"for", obviously saying it's a for loop. We then add the parentheses as with an
y function and
include all the contents and "schematics" of the loop. variableName is the varia
ble that I told you to define. I just called it that for teaching purposes, so r
eplace it with your
variable's name. Since the variable's declaration didn't include what it contain
s or is equal to, it is defaultly set to 0 (zero). So right in that spot you pla
ce what the
variable is currently equal to. It is best to always have a variable equal to 0
when you start, but it really depends on what you want to accomplish with the lo
t and then sees if it should continue. A "for" loop doesn't happen unless the va
riable test is
true.
6.C: While loops
~
While loops are extremely simple. So simple that in fact this part of the tutori
al will go extremely quick. To use while loops, you again have to have a variabl
e to test. For
the example, we will use an integer called "tester" (it's so simple that a model
is not necessary). We start the loop by typing our old friend while(). Then in
the arguments,
or parentheses, we put, "tester=1". Of course, since nothing happened to give te
ster an accumulated value, we gave it the value of 1 when we assigned it. So the
loop
does look like this so far:
while(tester=1)
Next, you put an opening brace, put the contents of the loop, and then close it.
There! You're done! See how easy a while() loop is? But now you may wonder, "If
it's that
easy, why don't I always use that loop?". Because, this loop is also very simple
. It doesn't have the features of, say, a for() loop in which you can only make
it happen a
number of times before it stops. It doesn't happen once and then test to see if
it can continue like a do{} loop can. It also doesn't have tricks like a for() l
oop has, like how
for() loops can make a delay happen by counting to extremely high numbers multip
le times by putting a for loop inside a for loop. Other than that, you are free
to use any
loop based on how and what you will use it for.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 8:if() and else()statemen
t
~
In C++, there comes a time in which the program has to make decisions based on w
hat is currently happening. It is just like in real life. That is what the if()
statement is for.
It pretty much explains itself, so this will be a quick lesson. Let's start. As
with any function, it needs parentheses. In those parentheses we put the data to
test. Maybe you
need to see if a variable is equal to something and work differently if it is. W
hatever it is, it follows a basic skeleton:
if(variable==something)
{
~what to do if it is true~
}
Really, the only thing you
riable. After that, we put
he variable equals
the following. Most of the
ctually, I think it always
ts between the braces
will be performed. As with any test function, it could be anything. We then clos
e the braces. But what if the test is false? That's when the helper function els
e() comes in.
Else tells the program what to do if the previous if() statement is false. If yo
u have more if() tests to do, you would write else before the following if()'s.
If you have no more
tests to do and have something for the program to do, you write else by itself f
ollowed by braces. In the braces, you tell it what to do. Here's an example:
if(variable==70)
{
cout<<"\"Variable\" equals 70!";
}
else if(variable==50)
{
cout<<"\"Variable\" equals 50!";
}
else
{
cout<<"\"Variable\" does not equal 50 or
70.";
}
Understand? Good!
Homework:
Write a program that gets an integer from the user. Then test if the integer is
greater than 50 but less than 100. If it is, tell the user that. If it isn't, te
st if it is over 100 but less
than 200. If it is, tell that to the user. If none of the past two are true, tel
l the user that.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 9: Reference Variables
~
In C++, there comes a time where you need variables in a certain function that a
re defined in a different function. Like if I made a function called addition()
and it needed
to use input from main. Well, in C++ doing that is a little complicated, but eas
y enough to learn if you pay good attention. The only time you will ever need th
is is if you are
using multiple functions. To start, make a new C++ file and declare the second v
oid function's prototype at the top of the program and call it "multiply", but i
nstead of having
nothing in the parentheses, put the words "int &input, int &input2". See the "&
" in front of the integers? That means that those integers will not be used to s
tore data
originally for them, but to act as "dummy variables" or to be variables that can
be replaced with any variable name assigned to it, and also to get data from a
different variable
from a different function *and* both the function that called the second functio
n and the second function both get
affected by the changes. If there is *no* "&" in front of the variables in the a
rguments, or parentheses, of the function, then only the function changing the v
ariables' values
gets affected. Because of that reason, the names in the arguments of the second
function can be replaced with any variable names from the same data type. Here i
s an
example of the confusing reason I just gave you:
void multiply(int &someNumber); /* This means
that the function calling this and this actual function get affected by any
changes to the passed on variables, regardless of which function the changes hap
pen
in. */
~
void multiply(int someNumber); /* Having no "&"
sign makes only this function affected by any changes to the passed on
variable that are made in this function. So if main() shares the same variable(s
) that get passed on to
this variable, only this function will be affected by any changes made in this f
unction. */
when it will be used. Next, start main(). In main(), declare two int variables.
You may call them anything, but I will call the first one "multiplyOne", and for
the second one, I
will call it,"multiplyTwo". Next, ask the user for 2 numbers, either by using bo
th variables on one "cin>>" line or 2 different "cout<<" and "cin>>"s. Now, here
is the part where the second function happens. Write the line, "multiply(multip
ly, multiplyTwo);". Remember when I said that the variable names in the function
prototype can be replaced with any variable as long as it is the same data type
? Well, that's what we just did. We called the function, just like how we assign
values to variables, with the 2 variables used. Now the function will use those
variables when it does the commands it is coded to do. But it is only able to d
o that because of the "&" we put in front of the variables inside the parenthese
s, or "arguments", in the second function's prototype. Now, close up main() to s
tart the second function. Start the second function with the name from the proto
type, you know, "void multiply(int &input, int &input2)", and put an opening bra
ce. Next declare an integer called "answer". This will hold the answer to the mu
ltiplication we will do with the passed on variables. After that, you pretend th
at we are still using the dummy variables, in this case "input" and "input2", by
assigning the answer variable's value to input*input2. But remember: we assigne
d multiplyOne and multiplyTwo to the dummy variables in main(), so even thought
it looks like it is still using the dummy variables, it is actually using the ma
in() variables as they got assigned to the dummy ones.
~Example 8.A with comments I add
ed to teach you~
#include <iostream.h>
void multiply(int input, int input2) //Prototyp
e
int main()
{
int multiplyOne, multiplyTwo;
cout<<"Enter two numbers separated by a
space: ";
cin>>multiplyOne>>multiplyTwo;
Just like with cout<<, you can get multiple inputs in one cin>> line
multiply(multiplyOne, multiplyTwo);
//
/
different cases because until it reaches something other than "case", it knows t
o do the same thing to the chained together cases. So, once the compiler finds n
o more
case statements chained together, it considers everything until the next case st
atements as the instructions of what to do if the cases are true. So, you can pu
t multiple
case statements together separated by a ":", but once the compiler finds no more
case statements chained together, it considers everything until the next case s
tatements
as the instructions of what to do if the cases are true. Understand now? Good, b
ut heres an example program:
~Example 11.A "11A_cases.cpp"~
#include <iostream.h>
int main()
{
char a;
cout<<"Enter A for a star to show, B for a numbe
r, and C for a percent symbol: ";
cin>>a;
switch(a)
{
case 'A':case 'a':
cout<<"\n********";
case 'B':case 'b':
cout<<"\n99999999999";
case 'C':case 'c':
cout<<"\n%%%%%%%%%%%%";
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 12:Making your own include files
~
Before we begin, I want to tell you that all include files end in a .h in the fi
le name. That is what sets it apart from an ordinary source file. So include tha
t on your include files.
So, you've learned about functions, variables, if statements, case and switch st
atements, other include files, file input/output, reference variables, and a ton
more. Now it's
time that you can start creating your own include files. But what makes an inclu
de file any different than a normal source file? Because the compiler has to kno
w if the file
has already been included earlier in any source code file so it can give an erro
r if a mistake happens that you accidently include it a second time in the same
source file.
That's what I will teach you here. Now, in any include file, it is best to comme
nt about the file's functions so anybody looking at them can know what it does.
So at the top
of your own include files, add in all the functions it does. That way you help p
eople understand what the functions do and how to call them. Next, the statement
to tell the
compiler not to include it a second time in one source file is a preprocessor di
rective. The first command is written as:
#ifndef _NAME_H
This means that if the include file has not already been defined, or included in
the source code including it, that it is okay to include it. After that you put
a _ to start the file
name. You then write the file's name without the .h part after the _ without spa
ce inbetween. Then you write another _ inbetween the name and "H". You then add
an H at
the end of the line. That means, "if the file ---- is not included already, cont
inue on including it.". If it already is included in the source file including i
t, the compiler will give an
error. If it goes well, then you define the file. To do that, you write the line
:
#define _NAME_H
It is just like the first preprocessor directive except you replace ifndef with
define. "define" makes it define the include file's source, or tell the compiler
that it is now being
included so don't include it again in the same source file. After that, you just
continue on with the source like normal. But remember: the point of an include
file is to add
definitions so any program can include it without having to define everything it
self. If you just use and include file to make a program, that isn't good and yo
u should take out
the above preprocessor directives and takeout the .h prefix on the file's name.
Finally, when you are done with all the include file's source, and I mean totall
y complete, you
add the following line after the last line:
#endif
That tells the compiler that the include file is done and that that's the source
code the compiler should be on the lookout for to prevent double inclusions. Th
ere you have it!
Now you can make your own include files! By the way, so there's no confusion, yo
u may include other include files in an include file. In fact, most do. I have i
ncluded examples
of include files I made myself in the Ch. 12 examples folder inside the main exa
mples folder. They are quite simple, but they are enough to give you an idea of
this lesson.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 13: Classes
~
In C++, there are times when your code is complex and confusing with alot of fun
ctions and variables. That is when classes become a handy tool to make it look s
imple.
Classes are like a suitcase for C++ code, in that it carries everything you will
use in a neat arrangement. In classes, there are public members and private mem
bers. First,
we will go over a model of a class:
Declare a class and put its name
/ \
class className
{
public:
~public members~
<------Everything th
private:
<----------Start def
~private members~
<--------Everything
at's public
ining private members
that's private
};
<-----!!!Notice the semi colon! This is *
required* after the closing brace on any class declaration
Now, you probably are lost and confused. That's what you should be or else you d
on't need to read this tutorial. We start off by declaring a new class. Unlike m
any other
commands and functions in C++, we actually declare it and start adding to it the
n, unlike makeing prototypes and making them later. Next we name the class. It c
an be
anything, but it is best to call it something that relates to the contents. Like
if the class if full of math variables and functions, you might call it "mathem
atics". After that, we
start defining public and private members. This is where you learn the real func
tions of a class. The names give away most of the meaning, but you must learn ho
w they do.
Public members are variables and functions that any part of the source code can
use. That means it can be used or called in main(), or it can be used in any oth
er things.
Private means that only the public members may use the private contents. That is
why private members get declared after public members, so it goes in order. So
if I had
the public function "void getAnswer()" and the private variable "answer", only g
etAnswer() may use the variable "answer". So main() or any other general functio
ns may not
use it. So you declare the functions and variables in their appropriate catagori
es, depending on how and where you will use them. But you may only use a name fo
r something
once, regardless of it being private or public. Like if I had "int b" in the pub
lic section, I can't put another int called b in the private section. But now th
ere comes a style that is so
common, that if you don't use it, your programs will look awkward and funky at f
irst. That style is defining most, if not all, of the variables/functions outsid
e of the class instead
of when you declare them. So if I put 3 variables and 5 functions in a class, it
would be best to give them their definitions and values outside of the class. B
ut there is a special
way that you call the contents of a class, which I will cover in a minute. Anywa
y, after you declare all of the contents in their appropriate catagories, you th
en close up the
class and continue on with the program. Now, as I just said, there is a way to c
all or define or give value to anything inside a class. Actually, it is required
. Instead of simply
typing the name of the function or variable, you include the data type of the va
riable/function you will be defining/calling and then you write the name of the
class and then
you write two, count 'em, two ":"'s. So a model of what I just explained looks l
ike this:
datatype className::
Now, after the two ":"'s, you put the name of the function/variable you are abou
t to define. So if I was going to define "void number" from the class called "ma
thematics",
I would write that like this:
void mathematics::number()
After that, you just define it like normal.
To call it, you make an instance of the class, or replace the data type of any n
ew variable with the name of the class, like for class name Math, I would first
write, "Math variableName". Then, I would call a class function by typing the in
stance's name and then a period followed by the name of the function, like:
classInstanceName.classFunction();
Just the function name, like you never made the class.
Lesson 14:Type conversion
~
In C++, there comes a time where you need to change a variable's data type. It m
ay be to do a special trick, or you need it for some function to work properly.
Either way,
there is a way in C++ that is extremely simple. The variable you are converting
must already be defined and declared. You also may not fool around and convert a
data type
to the same data type or a similar one, i.e. converting an int to a long int. So
, to convert a variable, you simply either:
1. Take the target data type and put that in parentheses, and leave the name of
the variable following it outside of the parentheses. Example:
char a;
...
(int) a;
//This converts a character to
an int. In C++, that simply returns the character's ASCII value.
2. Take the target data type and write it normally, but put the variable name in
parentheses. Example:
char a;
...
int (a);
But there are rules to converting. If you convert a char to an int, it just retu
rns its ASCII value. If you convert an int to a float or any decimal data type,
it will simply add zeros
after the decimal because an int doesn't hold decimal numbers. Just use your bra
in when converting.
$Ending Part$
~
Well, this leaves us to the end of this C++ tutorial. I hope you learned alot as
I spent alot of time on this. Look at the Future References file I included to
help you learn more