Sie sind auf Seite 1von 59

2007 Wikimedia Foundation Fund Raising

C++
This is a placeholder for Portal:Engineering and Technology → School:Computer
Science → Topic:Computer Programming → Topic:C++
Welcome to C++. Whether you're not certain which language to pick or you've
already decided on C++, you've come to the right place.
Arguably, C++ is the most versatile language in common use. It combines speed
with expressive power like no other language: it isn't perfect, but it represents the
current best compromise between these two, often conflicting, attributes. It also
combines "low-level" programming, as in moving bytes around, to "high-level"
programming, which is very abstract. Both of them have pros and cons that we'll
cover in this tutorial.
Why should you learn C++?
A key feature which distinguishes it from the language it grew from is that it is object-
oriented. An example can help to demonstrate what that means. If you were writing
a program to track the statistics of a racing cyclist, you might make different parts of
the program for their age, years of racing, wins, falls, what teams they've raced with
and so on. In real life, though, that's not how we think. Instead, we would think of the
cyclist as a whole, and the different statistics as being part of him. We could also
apply that general "model" of a cyclist, maybe with a few modifications, to any
cyclist, and have a complete representation of them. This is the essence of object-
oriented programming, and as you understand it more fully, it will allow you to create
powerful yet easily-understood programs. Instead of relying on data that is scattered
throughout a program, you can create a block of code that defines everything you
need, and then you reuse that throughout the code.
As a further example, think of a motor car. You unlock it with the key, and get in.
Then, you turn the ignition, put the car in reverse, release the brake, and press the
accelerator. As you drive, you use the steering wheel, the brake, and the accelerator
(and maybe the clutch). You don't know or need to know all the specifics of the car to
make it work. You just use what you need, and it's simple, too. Object-oriented
programming is like that. You can make powerful code, but it's all hidden, and you
can interact and reuse that code using the simple controls.
Other languages, such as Java, Python, Smalltalk and C#, allow the programmer to
write code in this object-orientated way. The key difference between C++ and these
languages is that C++ is designed to be compiled into efficient low-level code which
can run directly on the processor of a computer. This ability means that C++ differs
in many ways from these other languages, and lacks many of the advanced facilities
you might be familiar with if you already know one of them.

Contents
[hide]

1 Prerequisites

2 Course Description

1. 2.1 Pros and Cons of


C++

3 Lessons

4 To be merged

5 Enrolled

Prerequisites [edit]
Your enthusiasm. This is meant for a first time user. Every lesson will only depend
on what has already been taught in previous lessons. All you need here is your
willingness to learn, experiment, and have fun with computers.
In addition, it is essential to have a compiler. These are programs that can take the
C++ code which you input and turn them into a program. There are many compilers
around: Borland C++, Microsoft Visual C++, and GNU C++. There's also a host of
free, un-sponsored compilers out there--most notably Dev-C++.
As you go through this tutorial, run the scripts through your compiler, edit them, and
muck around with your own. It will give you practical knowledge and you'll quickly
learn to program effectively.

Course Description [edit]


This course covers everything, from the most basic principles of C++ up to
advanced concepts such as polymorphism, inheritance and the Windows API.
Pros and Cons of C++ [edit]
Pros
1. Is extremely popular, and therefore lots of support is available
2. Has a large base of freely available code for downloading
3. Is very powerful, and can be used to create just about any program, including
low-level system programs
4. There is a compiler for C++ on every major operating system, including
several free ones
5. C++ programs will work on most major operating systems
6. Compiled to low-level machine code, so it runs faster than similar languages
such as Java, Python, and C# in most cases
7. Is likely to be around in one form or another for a long time
Cons
1. Has an often difficult learning curve
2. Is very picky how code is formatted (but not quite as picky as Fortran or RPG)

3. Does not come with a ready-made "library" of useful code, and so requires a
vast amount of effort to create a relatively simple GUI program, for example
4. C++'s most powerful features, such as templates, have a very complex
syntax.
Lessons [edit]
Beginners
1. Lesson 1: Introduction to C++

2. Lesson 2: Variables and User Input

3. Lesson 3: Simple Math

4. Lesson 4: Conditional Statements

5. Lesson 5: Loops

6. Lesson 6: Functions and Recursion

7. Lesson 7: More Functions


Data Structures
1. Lesson 8: Classes and Inheritance

2. Lesson 9: Templates 1

3. Lesson 10: Templates 2

Advanced
1. Lesson 11: The STL
To be merged [edit]
1. Switching from C to C++

2. Flow Control
Enrolled [edit]
Please sign below if you are participating in this topic. Use 4 tildes (~) to sign.

1. J Blom 18:10, 9 January 2008 (UTC) I would love to re-explore the secrets of
C++ -- Thanks guys.
2. PGalasti 04:40, 7 January 2008 (UTC) I need to re-learn C++. Great site to
re-learn.
3. Thejamesman 18:28, 12 October 2007 (UTC) I look forward to learning. I
have ALOT of computer modding and manipulation experience, but its time to
get to the bare bones!
4. Smartguy583 00:37, 30 September 2007 (UTC) This course seems so much
more comprehensible that any of the books I've tried to learn C++ from.
5. Raspberry 21:58, 29 July 2007 (UTC) I love wikiversity. Learn, and pass on
what you know! I'm learning computer science, and teaching physics,
astronomy and music!
6. Kafitz22 15:15, 24 July 2007 (UTC) Can't wait to start learning C++, although I
know nothing except a bit of TI-BASIC :P
7. Michael Z 07:42, 2 July 2007 (UTC) (Looking forward to learning the language
of C++)
8. Mortimir 01:15, 22 May 2007 (UTC)
9. Giawa 17:51, 5 October 2006 (UTC) (Here to learn, have my code torn apart,
try to help teach, everything)
10. --SB_Johnny | -- Complete and total newbie. I'd like to become less
talk

ignorant about programming languages, and C++ was recommended as a


good place to start for what I want to use languages for.
11. Kwaggle 22:08, 20 December 2006 (UTC) C++ is my main proficiency, maybe
I can pass some of it on.
12. Josteinaj 22:55, 21 December 2006 (UTC) Here to learn. I know Java from
before (as it is arguably easier, and very portable), but I'd like to learn C/C++
now. It would be great if the guide emphasized compatibility between
platforms. Also, I eventually want to learn how to generate sounds, graphics
and networking in C++.
13. --80.230.255.60 22:00, 28 December 2006 (UTC)

14. Miles32 06:45, 7 January 2007 (UTC) Here to learn C++. Im completely new
to programming and I heard that c++ was the way to go.
15. Blasterman 7 January 2007 -- C++ is my main programming language, so I'd
like to sometimes help write the lessons. Never used C before, though.
16. — Saivorgz 05:34, 12 January 2007 (UTC) -- January 11 2007 -- §wanting to
learn c++ since i know java
17. ex0du5 22:25, 12 January 2007 (UTC) -- Currently enrolled in Computer
Engineering, and have taken 3 Java courses. I want to learn C++ as it is more
efficient in programming visual and graphic intensive applications.
18. Modnar 09:31, 26 January 2007 (UTC) (Going to be doing this in university
this year and would like to get a head start and always wanted to learn and
now I have decided to do so and looking to use this also with creating Palm
OS programs in the future hopefully as well :D)
19. cybergig (02/01/07 5:02AM ) I'm a total newbie to this so I am here to quickly
learn this language and hopefully several others to get a head-start on
programming.
20. Liam §wanting to learn c++

21. Mattsan 19:27 10 Febuary 07 Totally new to programming but I'm really
enthusiastic on learning C++!
22. Chuboltite 10:00, 10 March 2007 (UTC) I've heard from multiple sources that
C++ is a great language to learn. Plus, the programming experience will help
me in my future studies, so why not?
23. Chyld989 09:23, 11 March 2007 (UTC) I already know some C++, some of
which I learned on my own and some of which I learned in school. Hoping to
maybe learn a bit more, and maybe help others in the process.
24. baci 09:26, 12 March 2007 (UTC) Like so many others, I'm here to learn and
then teach. I wish I more experience so that I could assist with completion of
this course.
25. Devourer09 20:38, 22 March 2007 (UTC) Here to learn and if possible help
others.
26. 72.94.226.175 03:02, 21 April 2007 (UTC) Well, I could probably help, just
need to find a topic that needs to be covered. maybe pointers?
27. --Xentalion 00:57, 2 May 2007 (UTC) I'm here to help too, I've written a few
programs in C++ and am hoping to help other people learn.
28. Jocade 010 07:25, 21 May 2007 (UTC)

29. --Topcount345 01:14, 22 May 2007 (UTC)|Talk I hope to learn more about c++,
next year I am going to be in a class( by myself) in an attempt to learn c++.
Starting to learn now in an effort to put a footstool in place to climb the wall
this will probably be.
30. Scooter 16:37, 23 May 2007 (UTC) I've been writing code for about 2 years,
one of them with C++, I am most enthusiastic about wikiversity and I plan to
contribute as much as I can.
31. Cbradleyo 17:19, 18 June 2007 (UTC) Learned programming in high school,
but that was over 10 years ago. Eager to learn C++.
32. Aamirsayid1 20:51, 10 July 2007 (UTC)Aamir Sayid

33. Cslashb 15:23, 12 July 2007 (UTC)

34. ali2538 22:07, August 4 2007 (UTC) I wanted to learn this language since 7
years ago and every time that I started some thing happened. I hope I can be
successful in it this time. I really want to learn c++. Good Luck to Everyone in
learning C++. Including me.
35. --Pajumed 02:12, 8 August 2007 (UTC) Just found out about wikiversity and
I've wanted to learn C++ for a while, might as well if I want to do comp sci in
college.
36. Vitor 03:01, 14 August 2007 (UTC) To teach those who know less and to learn
from everyone.
37. jolt_34500 23:44, 28 August 2007 (UTC) Want to learn more about
programming.
38. Bensaved 06:57, 31 August 2007 (UTC) Senior Computer Science major,
looking to learn more about other languages than Java.
39. icecreamsoop 13:09, 11 October 200y (UTC) I'm looking to expand my
programming knowledge beyond that of Java.
40. 205.204.242.22 13:43, 5 September 2007 (UTC)User:ki4jgt

41. User:Zlrussell 68.153.118.128 18:49, 17 September 2007 (UTC

42. Drew 21:15, 2 November 2007 (UTC)

43. Tommosimmo 09:03, 19 December 2007 (UTC)

44....
45. Speilberg0 23:47, 26 December 2007 (UTC)

46. Captain panda 05:13, 5 January 2008 (UTC) I have only just learned a few
weeks ago how little I really know about computers and I want to learn
programming languages to help teach myself. C++ seems like a good place to
start.
47. Nofrak 05:04, 23 January 2008 (UTC) Expanse of knowledge
Category: Programming Languages

1. resource
2. Discussion
3. Edit this page
4. History
1. Log in / create account
Navigation
1. Main Page
2. Browse
3. Recent changes
4. Random topic
5. Random page
6. Help
7. Help desk
8. Donate
community
1. Portal
2. Colloquium
3. News
Search
Go Search

Toolbox
1. What links here
2. Related changes
3. Upload file
4. Special pages
5. Printable version
6. Permanent link
In other languages
1. Français
2. Italiano

1. This page was last modified 09:58, 23 January 2008.


2. All text is available under the terms of the GNU Free Documentation License (see
Copyrights for details).
Wikiversity is a trademark of the Wikimedia Foundation, Inc., a US-registered
501(c)(3) tax-deductible; nonprofit charity.
3. Privacy policy
4. About Wikiversity
5. Disclaimers
Introduction to C++
Contents
[hide]

1. 1 Hello World

1. 1.1 Includes

2. 1.2 main()

3. 1.3 Namespaces

4. 1.4 Cout, endl, and cin

5. 1.5 How to end a line of


code

6. 1.6 How to end a function

7. 1.7 A note about some


compilers

2. 2 Where To Go Next

Hello World [edit]


Before starting computer programming its a very good idea to get a general
overview of what computer programming is useful for.
The best way to learn C++ is to look at existing code and understand its
fundamental elements. If you are familiar with C, Java, Javascript, PHP, Flash
scripting or other C inspired languages, most of this syntax will be familiar to you.
Unlike web languages such as PHP and Javascript, C++ is not an interpreted
language. In other words, once you write the code in any basic text editor, you will
need to compile the code into objects, and then link all the objects together into an
executable program. The "compiler" turns what you write into low level codes the
computer can understand, and the "linker" makes the low level codes able to be run.
[1]

Alright, on to the code. Two consecutive forward slashes is a single-line comment,


and everything to the right of the slashes will be ignored by the compiler.

#include <iostream> // includes std::cout and std::endl

using namespace std;

int main()
{
cout << "Hello World!" << endl; //Prints Test
cin.get(); //Without this line the program ends very quickly in
Windows
return 0; //Returns Success of the program
}

Includes [edit]
Now to explain this introduction to C++ code. The commands that are used in this
example are defined in two files which are included with the #include directive.
#include <filename>

Most of the time you will need to include commands like this so you don't have to
reinvent them from scratch. When the C/C++ compiler reaches an #include directive,
it will attempt to load the file named within the symbols <filename>. This file is called
a header file, include file, or library as stated above, but it is basically just another
file with C/C++ code in it. Loading files with #include allows you to access new
functions, global variables, objects, and structures that would otherwise not be
available to you in the code. Unlike most commands in C/C++, you do not need to
end an #include directive with a semicolon. It is common practice to place the
#include directives before the body of the code, but this isn't required.
The <ostream> and <iostream> files contains functions that assist in formatting and
writing output to the screen.
main() [edit]
When you compile your code, the compiler looks for a main function and starts the
program there. Functions will be explained in greater depth in a later lesson, but
what you need to know now is that the compiler looks for main() and runs the
commands contained within main() first. You start writing your commands
immediately after the { symbol, and the program ends when it reaches the } symbol.
A note: with normal functions, you call them from another function, for instance, if
you had a function that took two numbers and multiplied them, you might use code
like this: multnumbers(6, 2);. So what calls the main function? The answer is the
operating system, and so that is where your program starts off. That is why it is so
important to include the main() function in your code. By the way, if you don't
understand this, don't worry. It will all be explained later on, like I said.
Namespaces [edit]
Within all modern programming languages there is a the concept of namespaces.
Just as I said before, using other peoples code is a great way to get your code
working. Again, there is no point in reinventing the wheel. Namespaces contain all
sorts of "identifiers" that are useful. In our program there is a namespace called std,
which contains cout and endl. The method to use an identifier within a namespace
is:
namespace::identifier

So in the case of our program, we've used the namespace std and the identifiers
cout and endl. Namespaces can be nested, you can create namespaces, and you
can be using identifiers from multiple namespaces at the same time. Coding with the
namespace::identifier format can get tedious though, especially if you are only using
one namespace in your code. For this reason, there is an easy way to let the
compiler know that you will be using the std (or any other namespace) for the rest of
your code. It's a way of telling the compiler where to look when it can't find an
identifier you used. The code looks like this:
using namespace std;

I've used the namespace "std", which is the namespace we used in our code. This
will allow us to remove std:: from all of our code. This is extremely useful, because
you can imagine how much extra space would be used up by std:: if we had more
that one line of cout and endl. "std" is also used for other identifiers that you'll be
using in your future code, so it is helpful to include the std namespace in most of
your beginner programs. After you've removed std::, your code should look like this:

#include <iostream> // for std::cout and std::endl


using namespace std;

int main()
{
cout << "Hello World!" << endl; //Prints Text
cin.get(); //Without this line the program ends very quickly in
Windows
return 0; //Returns Success of the program

Cout, endl, and cin [edit]


The cout identifier is an easy and powerful way to output information to the screen.
The opposite of the cout identifier is cin, which will be used in our next program.
Each operand for cout is seperated by <<, whereas each operand for cin is
seperated by >>. This lets the compiler know when it should be looking for a new
operand to control cout or cin. For example, you can add extra text by using the
code:
cout << "I'm going to try and display Hello World! on a new line" << endl <<
"Hello World!" << endl;

When compiled, the output should be:

I'm going to try and display Hello World! on a new line


Hello World!

The cin command is used to recieve user input. Without the cin.get() command the
program would run and exit in less than a second on Windows Platforms. By adding
this line, the user must press enter to end the program. This gives you a chance to
see your code work.
Another way you can do this is using "\n". \n basically means "new line after this"
here is an example of it in use:

#include <iostream>
using namespace std; // very bad practice with namespace

int main() {
cout << "I'm going to try and display Hello World! on a new
line\nHello World!\n";
system("pause"); // this won't work on many platforms - you should
stick to standard C++
return 0;
}

Note: cin.get(); is the cross platform substitution for system("pause"); Adding


cout<<"Please press Enter to continue..."; will duplicate the look of the pause call.
How to end a line of code [edit]
Every line of code in C++ is terminated by a semicolon(;). This allows your code to
span multiple lines on your screen, but be treated as one line of code by the
compiler. In C++, white space is ignored, so:

//this
cout << "hello";
//is the same as
cout
<<
"hello"
;
//and this
cout
<< "hello"

This makes your code neater and more organized. This rule holds for the most part,
although there are occasional things that you can't break up into two lines, but
unless you see that specified in a certain section, go ahead and do it in your code.
How to end a function [edit]
Most functions are built to return some sort of value to whatever called it in the first
place. There will be more on this later. What you need to know is that return 0;
means that a value of 0 will be returned from the code. Your compiler will normally
tell you how your program ended. For example, my compiler will say "HelloWorld
ended with code 0" after I've compiled and run my code. Different values can mean
different things depending on your program. You could set a return code of 2 to
mean there was an error, or and return code of 1 could mean your function
completed successfully. Many times, it might be an answer- for instance, above, I
wrote about the multnumbers() function that looked like this: multnumbers(6, 2);. In
this function, it might assign 6 to a and 2 to b, and the return code might be

return a*b;

So, if you had called this in your main() function, you might have written something
like

myinteger = multnumbers(6, 2);

So now, myinteger would be equal to 12.


The main() function is special, though: the return code is returned to the operating
system. For now, keep it at 0.
A note about some compilers [edit]
Because console programs are supposed to be run from an already open console, if
you run it by itself, the program will quickly display a black box and then disappear.
This is your program running, finishing and then closing very quickly. So fast, that
normally, that you don't get a chance to see the output. (Note: Xcode, see below
does not have this problem) The following code will wait until the user hits a key and
then proceed to terminate the program

#include <stdio.h>
int main()
{
//Your code here
getchar();
}

• Another note on compilers: What if you don't have one? Well, the good news
is, there are tons of good compilers that are available for free. For most
POSIX systems, gcc (the GNU Compiler Collection) is available. It is arguably
one of the best compilers ever written and does a good job of implementing
standards. However, many people using Windows or the Mac OS like good
IDEs. For OS X, there is Xcode. It is a very powerful, yet user friendly IDE for
developing in many languages, and it uses gcc for C++. It's large however,
but if you're developing on OS X, this is vital. For Windows, there is Dev C++
(which is very popular at my university among students). Also popular (but
expensive) is Microsoft Visual C++.

Variables and User Input


Contents
[hide]

1. 1 Variables - What are they

2. 2 Initializing Variables

3. 3 Types of Variables

1. 3.1 Booleans

2. 3.2 Integers

3. 3.3 Char

4. 3.4 Floats

5. 3.5 Doubles

4. 4 Lesson 2 Program

1. 4.1 Getting User Input

2. 4.2 Casting

3. 4.3 Continuing with our


program

4. 4.4 End of lesson 2

5. 5 Where To Go Next
Variables - What are they [edit]
Before we get into coding, let's think a little bit about what variables really are. I am
going to describe this in as simple terms as possible.
When engineers way back in the day began to work on computers, they quickly
realized that there needed to be a way to input information into the computer and
store it there. Then that information needed to be accessed again and used. You can
of course, understand why this is important. Computers would not be of much use if
they had no way to temporarily store information. Today, there are many different
types of data that can be stored on a computer. We'll take a look at them in this
lesson. Then we'll look at ways for the user to input data into a program and get a
result.
Anyways, back to my story about the engineers and the early computers. Before
languages such as C++ existed, engineers used to program their computers in a
language such as assembly. In assembly, engineers would have to keep track of
every single part of memory on the computer. Memory on a computer is stored
linearly, with a specific address for each memory location. So, if a programmer
wanted to add the contents of his working register with the contents of register 0x86,
they would have to use an instruction such as

addlw 0x86

The above, of course, would get extremely complicated if you were trying to code
something that relied on hundreds of data addresses. You would have to keep huge
tables to let you know which data address meant what, and so on. Mistakes would
be bound to happen, and that is why engineers developed a better way to organize
data.
Variable (defn): a symbol for an unspecified member of a class of things or
statements
A variable is a name that is given to a data address. When a compiler sees a
variable that is initialized it creates a data address for that variable, and assigns that
address to all instances of that variable name. This makes it much easier on the
programmer (you!). So instead of the above code example, you can now use code
that makes a lot more sense.

int myVariable=5;
myVariable = myVariable + myVariable;

Initializing Variables [edit]


All variables are very similar to use. Whether you are using a double, integer, char or
bool, they are declared the same way. The format is

variable_type variable_name;

If, for example, you would like to create 2 integers with the names "Zelda" and "Link"
you could type

int zelda;
int link;

// or, to save space you could declare them both on the same line. int
zelda, link;

Variables are given a value using the following syntax.

variable_name = value;

There will be examples of initialization of variables under each variable type.

Types of Variables [edit]


Booleans [edit]
Bools (short for boolean) are one bit variables. This means they are either a 0 or a 1,
a logic high or low. Bools are useful to determine whether or not something was
successful. Flags that control parts of your program could be bools, which saves
memory space while still performing a valuable function.

bool true=1, false=0;

This code will create two boolean variables. The variable named true will contain a
1, a logic high, whereas the variable named false will contain a 0, a logic low. These
could then be used in logic statements or be set to different values. Notice how I
have set the variables equal to their values on the same line that I initialized them.
Integers [edit]
An integer is a number that does not have any decimal places. It is a whole number,
for example 1,2,3,4 are all integers. 4.3 is not, as it is a fraction of a whole number. If
you were to try and place the number 4.3 into an integer the number will be rounded
down to 4. Originally an integer was an 8 bit value, which meant that it could store a
value from 0 to 255. It is also possible to store signed integers, which means they
can hold numbers that are below 0. Let's take a look at all the different types of
integers now.

short myVariableName; // stores from -32767 to +32767


short int myVariableName; // stores from -32767 to +32767
signed short myVariableName; // stores from -32767 to +32767
signed short int myVariableName; // stores from -32767 to +32767
unsigned short myVariableName; // stores from 0 to +65535
unsigned short int myVariableName; // stores from 0 to +65535

int myVariableName; // stores from -32767 to +32767


signed int myVariableName; // stores from -32767 to +32767
unsigned int myVariableName; // stores from 0 to +65535

long myVariableName; // stores from -2147483647 to +2147483647


long int myVariableName; // stores from -2147483647 to +2147483647
signed long myVariableName; // stores from -2147483647 to +2147483647
signed long int myVariableName; // stores from -2147483647 to
+2147483647
unsigned long myVariableName; // stores from 0 to +4294967295
unsigned long int myVariableName; // stores from 0 to +4294967295

Wow, that is a lot of variable names. Now, all of these values are guidelines for C++.
The compilers must store from AT LEAST these ranges. Some compilers will use
more bits for their long integers, but these are the guaranteed ranges regardless of
your C++ compiler. Many of these variables store the same range of values, yet
there are so many different names. What is the difference between a "long" and a
"signed long int"? In my mind, the only difference is 12 extra keystrokes. Pick one
that works for you.
Char [edit]
A char is an 8 bit integer. This means that an unsigned char can store between 0
and 255, and a signed char can store between -127 and 127. Unsigned chars are
commonly used to store text in ASCII format, and can be used to store strings of
information. A char can be initialized to hold either a number or a character.
char myChar='A';
char myOtherChar=65;

Both characters that I have just initialized would be equal. The number 65 is the
ASCII code for the letter 'A', so both characters would contain the 8-bit value of 65,
or the letter A.
Floats [edit]
Floats are floating point numbers, which means that these numbers can hold
decimal places. This allows us to store numbers such as "8.344" and
"3432432653.24123".

float myFloat; // Creates a floating point variable


myFloat= 8.3; // Stores 8.3 in the new variable

Like integers, floats are dependent on the hardware of the computer you are
compiling on. Later we will look at ways to see how much accuracy your computer
will get with floating point numbers.
Doubles [edit]
Doubles are like "floats", which means they can store decimal places. Doubles can
generally store more information than a standard float.

double myDouble; // Created myDouble


myDouble= 8.78; // Stores 8.78 in myDouble

Lesson 2 Program [edit]


Getting User Input [edit]
Time to write code! This will be a simple little program that will name a couple
variables, perform something called casting and display the information back to the
screen. So, let's get started with laying out our program. Programmers often use a
language called pseudocode which relays what they want to accomplish. Let's write
some pseudocode for this program.
create two integer variables: monkey, banana
create a float variable: bird
set banana=10, set monkey=15
let user set the value of bird
display the outcome of banana+monkey
display the outcome of monkey+bird as a float using casting
display the outcome of monkey+bird as an intenger using casting

Set up a console application just like in last lesson. Make sure you include iostream
and create your main() function. If you have any problems, check your code against
mine below. So the first part of this code is easy. We've seen how to declare and
initialize variables (specify type, name, and a value). Write the code to initialize your
variables, and set banana=10 and monkey=15.
Now it is time to get user input. Remember how we used cout to write to the screen?
Now we will use cin to read from the user. The syntax is very similar. Here's a
comparison of cin and cout

int myVariable; // initialize myVariable


cout << "Enter an integer: ";
cin >> myVariable; // will wait for the user to type in an integer and
then hit enter
cout << "You entered the number: "<< myVariable;

This code will output

Enter an integer: 15
You entered the number: 15

15 is the number that you, the user, entered. The program stored that value 15 at
the data address referenced by myVariable. Now, it is time to incorporate cin into our
program. Let's see where we can get to now.

#include <iostream>

using namespace std;

int main (int argc, char * const argv[]) {


int monkey=15, banana=10;
float bird;
cout << "Enter a value for bird:";
cin >> bird;
return 0;
}

This program initializes all of our variables and gets user input for one of them. Now
it is time to do something with the data we have stored. To do that, it is time to learn
something called casting!
Casting [edit]
Casting is extremely useful, and is used to convert one type of variable or data type
into another. An example might be an integer that you want to turn into a float. If you
wanted to divide the integer 4 by the integer 3, you would get an answer of 1. Even if
you are setting a float equal to 4/3, you would still get 1. That is because there are
no decimal places available for the division of 4 and 3, the compiler assumes you
want a integer response when dealing with two integers. Casting solves this
problem.
Casting syntax is very easy.

(cast to type)variable_name;

Let's dive right into some examples, as they are easy to understand.

int three=3, four=4;


float answer;
answer=four/three;
cout<< answer; // Since this is the division of two ints, the response
will be 1, another int

answer=(float)four/(float)three;
cout<< answer; // Now that the ints have been changed to float, the
response will be 1.33333, a float!

Continuing with our program [edit]


Now that we understand the basics of casting, let's continue with the code. You first
want to display the outcome of monkey and banana, which have been added
together. Then use casting for the last two lines of our pseudocode. Here is what I
got.

#include <iostream>

using namespace std;

int main (int argc, char * const argv[]) {


int monkey=15, banana=10;
float bird;
cout<< "Enter a value for bird:"; // Ask the user to type a value
for bird
cin>> bird; // Get the value of bird from the
user

cout << monkey+banana << endl; // Display monkey+banana, an


integer
cout << bird+(float)monkey << endl; // Display bird+monkey as a float
cout << (int)bird+monkey << endl; // Display bird+monkey as an
integer
return0; // Our code is done
}

Wonderful! We have now written a second piece of code that works! Here is what
was output by my code:

Enter a value for bird:5.6


25
20.6
20

End of lesson 2 [edit]


So you can now see casting and variables in action. All of our future code will rely on
variables and different ways of getting data into them. Thanks for reading this far,
and hopefully you have learnt something! If any of this seemed too complicated, let
me know! Write something in discussion, or anything like that.
Simple Math
Contents
[hide]

1. 1 Simple C++ Math

1. 1.1 Adding, Subtracting, Multiplying and


Dividing

2. 1.2 Basic Math Library Functions

3. 1.3 End of lesson 3

2. 2 Where To Go Next

Simple C++ Math [edit]


So, first things first. Lets add the math libraries to our C++ project. That way we
have the ability to do useful math functions such as powers, square roots and the
like.

#include <cmath> // ANSI C++ way. For ANSI C you should do: #include
<math.h>

Note that the math library is one of the 18 ANSI C language standard libraries that
can be imported in C++. Now you have made many useful functions available to
your program. Now, let's do some math.
Adding, Subtracting, Multiplying and Dividing [edit]
These are all very straightforward, and do not even need the math library to work.
The syntax for basic math with these operands are as follows:

variable = operand operator operand;

So an example of this could be something like

int myResult;
myResult= 5 + 6; // A value of 11 will be stored into the integer
myResult
Now, C++ allows this all to be very flexible. So you can mix numbers, variables,
floats, ints and all sorts of things together.

int five=5, six=6, twelve=12;


float pi=3.14, myResult;
myResult = six * pi + twelve; // since pi is float, no need to cast six
and twelve to float
myResult = myResult - five;

C++ will perform operations via BEDMAS (or PEDMAS, or however you learned it in
middle school). That means brackets (or parantheses) will be computed first. Then
exponents, then division and multiplication, and then finally addition and subtraction.
The above code will take the number six, and then convert it to a floating point
number. Then it will multiply 6 by pi, which will return a floating point number. Then
twelve, which has been converted to a float, will be added to the result. So myResult
at this point will contain 30.84. Then five will be converted to a float and subtracted
from myResult. The result will be 25.84.
This should be pretty straightforward. Now, take a look at the last line of the above
code. Notice that we are taking the variable and adding another value to it, and then
dumping it back into itself. You've just had to type the same variable name twice in a
row, which could lead to typos, and also takes up time. There is an easier way to do
this! Each of the following lines has an equivalent line of code that follows.

myResult = myResult+5;
myResult += 5;
myResult = myResult-5;
myResult -= 5;
myResult = myResult*5;
myResult *= 5;
myResult = myResult/5;
myResult /= 5;

See the pattern? We reach another very common situation. There are many
instances where you will want to increment a variable by one, or decrement it by
one. This is very common in counters and loops. For example, everytime the user
hits a button on the keyboard you may want to increment a counter by 1. So, here's
an easy way to add one, or subtract one from a variable.
intcounter=0; // Initialize the variable
counter++; // Adds 1 to the variable counter
counter--; // Subtracts 1 from the variable counter

Basic Math Library Functions [edit]


Now it is time to browse a few of the functions that are available from the math
library. We can take the square roots of numbers, we can take powers of numbers,
etc. The syntax is as follows:

float myValue=25, myResult;


myResult = sqrt(myValue); // Squareroot the variable myValue, and
store it into variable myResult
myResult = pow(my_result,2.00); // Square the variable myResult, and
then store it back into myResult

Let's investigate what this does. First, this program takes the square root of 25 and
stored into myResult. This leaves a 5.00 in myResult. Then this value is squared and
stored back into itself. This means 25.00 will be stored in myResult. So, more
simply:

pow(myValue,myPower); // myValue is the base and myPower is the


exponent

For a list of functions, see math.h.


End of lesson 3 [edit]
You should now be able to get C++ to do some simple math for you. In reality, it
never gets much more complex than this. Almost everything you will write will be
based on just a few simple operators. Thanks for reading this far. Hopefully you
have learned something.

Where To Go Next [edit]


Conditional Statements
First, a couple notes (since I've pretty much made this tradition in my lessons). So...
- Firstly, hopefully you have read the lessons to date. You should be well versed in
simple input/output as well as variables.
- Secondly, hopefully the lessons are teaching you some valuable skills in C++.
Once again, it is awesome to see people adding on to the lessons.
As the name implies, conditional statements specify whether another statement or
block of statements should be executed or not. These are often called "selection
constructs". The two general types are "if...then" and the "switch...case" construct.
Note that there is no looping involved here, but that conditionals are involved in
loops.
Contents
[hide]

1. 1 Comparison Operators

2. 2 The if...then Conditional

3. 3 The switch...case
Construct

4. 4 The Conditional
Statement

5. 5 Where To Go Next

Comparison Operators [edit]


The conditions tested are specified using comparison operators. These operators
cause the immediate statement in which they are contained to return a boolean
value of either true or false. (Note that in certain circumstances they may evaluate
to 0 or 1; be careful combining conditional statements with arithmetic)
The following comparison operators are available:
1. Equality: ==, or Inequality: != of any primitive data type (int, char, float, bool,
etc.) These are binary operators (take two operands) and are specified using
infix notation (which means that the operator goes in between the two
operands).
2. Greater-than: >, >= or Less-than: <, <= Also binary operators using infix
notation. Use only with numeric data types; there are specific functions for
comparing other data types.
3. Negation: ! is a unary operator, and prefixes the operand.

Examples:

5 == 5 evaluates to true.
7 != 5 evaluates to true.
'a' == 'b' evaluates to false.
6 > 9 evaluates to false.
4 <= 4 evaluates to true.
!true evaluates to false.
true! is invalid.

The if...then Conditional [edit]


There are two variations to the if...then conditional. Let us take a simple case and
explain it line-by-line.

01: if (x == 7) {
02: //this code is executed only if x does indeed contain the integer
value 7
03: }
04: else {
05: //this code is executed if the preceeding if condition evaluated
to false
06: }

Explanation:
1. This is the first line. Note that there is space
between the keyword if and the opening
parenthesis. Inside the parentheses is the
condition; in this case it is a test for equality. It is
good practice to use the same type arguments (not
comparing floating-point values to characters).
Note also the left curly brace {. This symbol
denotes a block of multiple lines of code. Without
it, the conditional would only refer to the statement
immediately following it. It is good practice to
always use the braces.
2. This comment represents the body of the
conditional statement.
3. The right curly brace is essential; it matches the
opening brace on line 1 and signals the end of the
if body.

4. This line is optional. If there is a sort of "default"


behavior that should be carried out, it would be
placed here. The else clause does not belong by
itself, only directly following an if clause.
5. This is the body of the else clause.

6. This curly brace is also essential; it matches the


opening brace on line 4 and signals the end of the
else body.

The body of the else block can be another if statement. This is known as "nested
conditionals" because the conditionals are indeed nested; that is, placed inside of
one another.

The switch...case Construct [edit]


This tests an input variable for equality with any number of cases and then executes
the corresponding code. The syntax follows:

01: switch (a) {


02: case 1:
03: //some statements
04: break;
05: case 2:
06: //some more statements
07: break;
08: default:
09: //even more statements
10: break;
11: }

Again, here is a line-by-line explanation:


1. Line 1: The opening line is very similar to the if construct, described above.
The only difference is that the switch...case construct only uses int values
and character constants or character literals. For this reason, the switch-
case can come in handy but it is limited to these circumstances.
2. Line 2: For each expected value, code a line such as this one. The 1 means
that if a does contain an integer value equal to 1, execution will begin
following the colon on this line. Execution will continue blindly, so,
3. Line 4: contains a break statement that forces execution outside of the switch
block.
4. Line 8: The default block is similar to the else block in a normal conditional. It
is chosen if none of the previous cases matched the value of the condition
variable.
Note, the break statement can be under-used to the programmer's advantage. If
multiple values of the condition variable would lead to executing the same code, the
cases can be listed one after another like this:

...
case 1:
case 2:
case 4:
//code common to those three cases.
break;
...

The Conditional Statement [edit]


There is one more conditional statement, and it is truly a contraction of the if...then
construct, however, this one is quite compact and can fit on one line or even be
embedded within a larger expression. This is the syntax:

( condition ) ? codeIfTrue : codeIfFalse;

The entire expression evaluates to the expression given in the codeIfTrue and
codeIfFalse statements. If those are complete statements, then that code is
executed. It is also possible to specify a single value for each of those, and assign
this conditional statement to a variable, like this:
int a = ( x > y ) ? x : y;
//this is equivalent to:
int a;
if (x > y)
a = x;
else
a = y;

As you can see, this makes simple conditionals all the simpler, but can complicate
readability. Use sparingly.
See if you can come up with a few usages of the conditional constructs you have
just learned.

Where To Go Next [edit]

Loops
Loops allow a programmer to execute the same code repeatedly. These are often
called "repetition" constructs. We will make heavy use of conditional statements in
this section.
Contents
[hide]

1. 1 The while Loop

2. 2 The do...while Loop

3. 3 The until Loop

4. 4 The for Loop

5. 5 The extensible while


loop

6. 6 Where To Go Next

The while Loop [edit]


The while loop is really the only necessary repetition construct. The for loop,
coming up, can be duplicated using a while loop, and with more control. A simple
negation can perform the same behavior as an until loop.
The syntax is as follows:

while ( condition ) {
//body
}

Again, the curly braces surrounding the body of the while loop indicate that multiple
statements will be executed as part of this loop. If the actual code looked something
like this:

while ( x == 4 )
y += x;
x += 1;

There would be a problem. According to what was written, even though the second
line after the while was indented, only the first line corresponds to the while loop.
This is a huge problem because the variable involved in the condition (x) does not
change, so it will always evaluate to true, making this an infinite loop. This could be
alleviated by containing all statements intended to be a part of the loop body in { }.

The do...while Loop [edit]


The do...while loop is nearly identical to the while loop, but instead of checking the
conditional statement before the loop starts, the do...while loop checks the
conditional statement before continuing onto another iteration.
The syntax is as follows:

do {
//body
} while (condition)

As you can see, it will run the loop at least once before checking the conditional.
The do...while loop is still haunted by infinite loops, so exercise the same caution
with the do...while loop as you would with the while loop. It's usefulness is much
more limited than the while loop, so use this only when necessary.

The until Loop [edit]


This loop is basically the while loop with the entire condition negated. It will run while
the specified condition is false and stop executing the body when the condition tests
true. Example:

until (x == 10) {
//do something
}

This loop will do something as long as x does not equal 10. If it gets back and tests
the condition and it evaluates to true, it will stop executing the loop and proceed to
the next statement after the closing curly brace.
Note that the same functionality can be accomplished with:

while (x != 10) {
//do something
}

The only difference is that semantically, the keyword "until" means more to the
programmer, and gives an immediate indication of the behavior of that block. If he
had to read into the condition of the while statement and realize that the negated
condition meant that the loop would wait for that condition to become true, that
would be a waste of time. However, for the programming language itself, it is nice to
have such a versatile loop structure as the while loop.

The for Loop [edit]


The for loop is a while loop that lets a programmer control exactly how many times
a loop will iterate.
The syntax is as follows:

for (initial state; conditional; update statement) {


//body
}

To better explain how the for loop works, let's look at one:

for (i = 0; i < 10; i++) {


cout << i+1 << endl;
}

What does this loop do? Prior to the first iteration, it sets the value of i to 0. Next, it
tests (like a normal while loop) if i is less than 10. If the statement returns true, the
body of the loop is run and the program will print the value returned by the simple
arithmetic statement i+1 and move the terminal cursor down to the next line. After
the loop is finished, i is incremented (by 1), as specified in the update statement,
and the conditional is tested again.
So, this loop will run a total of 10 times, printing the "i+1" each time. You've taught
your program to count!
The variable used in for loops is generally an integer variable named i, j, or k, and is
often initialized prior to the beginning of the for loop. Another option is to initialize
the variable at the same time that you declare the variable's initial state:

for (int i = 0; i < 10; i++) {


cout << i+1 << endl;
}

If this is done properly, it is possible to nest for loops.

int i, j, input;

cout << "How many missiles will you fire?\n";


cin >> input;
cout << endl;

for(i = 0; i < input; i++) {


for(j = 10; j > 0; j--) {
cout << j << " ";
}
cout << "Missile " << i+1 << " has launched.\n";
}

cout << "All missiles have been launched." << endl;

What does this program do? The user is prompted to choose an integer, which is
used in the conditional statement of the first for loop. Each iteration of the i loop will
cause the j loop to run, which counts down from 10 to 1 before allowing the i loop to
continue. The output will look something like this:
How many missiles will you fire?
3
10 9 8 7 6 5 4 3 2 1 Missile 1 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 2 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 3 has launched.
All missiles have been launched.

The extensible while loop [edit]


The while loop can take the place of do...while loops if the condition for the while
loop is "rigged" to be true at least the first time around.
The while loop can take the place of until loops by negating the condition that
would be specified for the until loop, as explained above.
The while loop can take the place of for loops, and with greater functionality. The
"initial condition" would be specified before entering the loop, the conditional would
still be specified for the while loop. The update statement, however, could be more
complex. Keeping in mind the condition being tested, the "update statement" (which
is the only way to make our loop a finite loop) could update data members of an
object, run a function that would affect the condition, or any number of things. Most
importantly, it can be a "compound statement" that is, if several operations are
required to change the state of the environment that would, in turn, affect the
outcome of the loop condition, it is an absolute must to use a while loop.

Where To Go Next [edit]

Functions and Recursion


This lesson will have to do with using functions and recursion to improve readability
and efficiency of your code. This lesson assumes you have a general grasp of C++
syntax. Other than that, I will explain everything as well as I can.
Contents
[hide]

1. 1 Functions

1. 1.1 The main Function

2. 1.2 Prototypes
3. 1.3 Calling

4. 1.4 Parameters

1. 1.4.1 Passing Methods

2. 1.4.2 Default Parameters

5. 1.5 Scope

2. 2 Recursion

3. 3 Where To Go Next

Functions [edit]
Simply put a function is a segment of code that is isolated from the main code
segment. A function is called from a section of code. When the function's code has
been executed, it returns to the calling code. The general form of a function is:
return_type function_name ([arg1_type arg1_name, ...]) { code }

Here is an example of a function:

int addTwoInts(int arg1, int arg2)


{
int sum = arg1 + arg2;
return sum;
}

1. The int at the beginning is the return type of the function.

2. addTwoInts is the function's identifier. It will be what is used to call the


function.
3. int arg1 and int arg2 are called parameters. They are defined in the form
<type> <identifier>. These will be explained later.
4. The code for the function is enclosed in a set of curly brackets { }.

5. Every function with a return type other than void must have a return
statement. This is the data that the function will be sending back to the calling
code.
Many conventions exist governing the form of
functions in C++. Generally, whatever form is most
readable to you is the one you should use. For
example, some coders will leave the opening { on the
same line as the function definition while others will
give it its own line. Also, some coders would name
the above function add_two_ints. This is mostly
personal preference.
The main Function [edit]
The main function is a special function. Every C++
program must contain a function named "main". It
serves as the entry point for the program. The
computer will start running the code from the
beginning of the main function. There are two main
types of main functions; one with and one without
parameters. Below are examples of both:

/* Without Parameters */
int main()
{
...
}
/* With Parameters */
int main(int argc, char * const argv[])
{
...
}

The reason for having the parameter option for the


main function is to allow input from the command line.
When you use the main function with parameters, it
saves every group of characters (separated by a
space) after the program name as elements in an
array named argv. The array datatype may be
beyond you at the moment, but don't fret. In time you
will learn of it. Here is an example of a command line
statement with a program that uses a main function
that accepts arguments.

C:\> program.exe text 234


This command would pass the following information
to the main function:
1. argc = 3

2. argv = {program.exe, text, 234}

1. Note that the '234' is a string, not an integer value


Since the main function has the return type of int,
the programmer must always have a return
statement in the code. The number that is
returned is used to inform the calling program
what the result of the program's execution was.
Returning 0 signals that there were no problems.
Prototypes [edit]
Before we discuss calling the functions, we must
talk about prototypes. Programs written in C++
are executed in logical order from the top down.
A statement can only use things that are
declared in code that has already been executed.
This may not always be above them in the code
literally, but it usually will be. By convention, the
main function is always the first function listed. To
allow main to call functions that are declared after
it in code, we use prototypes; a line of code that
tells the computer the function exists, but it will
be declared later.
The prototype is much the same as the definition,
but without parameter names. Example:

/*Definiton*/
int fctn2(int num1, int num2)
{ ... }

/*Prototype*/
int fctn2(int, int);
This idea will be illustrated in the following
section.
Calling [edit]
Calling refers to how a function is used from
code.
Example:

#include <iostream>
using namespace std;

void fctn1();
int fctn2(int, int);

int main()
{
int sum;

fctn1();
sum = fctn2(2,3);

return 0;
}

void fctn1()
{
cout << "This is function 1!" << endl;
}

int fctn2(int num1, int num2)


{
//the value 2 has been passed as num1
//the value 3 has been passed as num2

return num1 + num2;


}

There are many things to note in this example.


First is the use of the two prototypes that
precede the main function. They allow main to use
fctn1 and fctn2 even though they aren't declared
until after main.
Next, notice that to call fctn1 all we had to do
was enter fctn1();. Since it doesn't require any
arguments and it has a void return value, this is
very simple. For fctn2 however, we see that it
not only requires two arguments, but also returns
an integer as well. To pass data to a function, you
simply list the data in the order it is called for by
the function definition. To catch the returned data,
we use the assignment operator '=' and assign
the returned value to a variable sum.
Another thing to note is that functions with a void
return type, as fctn1, do not require a return
statement as they do not return anything.
Parameters [edit]
Parameters are how data is passed between
functions through the call of the function. Above
we learned that you list the data you want to
pass to a function in the call between the ( ).
The order of the list is determined by the function
definition. The first parameter in the list will be
assigned to the variable listed first in the function
definition. Also, in most cases, you must have the
correct number and type of data being passed to
the function or you will receive an error when you
try to compile your program.
For example:

int main
{
fctn(num1, 12);
}

void fctn(int arg1, int arg2)


{ ... }
This would pass the contents of the variable num1
to arg1 in the function. Then the integer value '12'
would be passed to arg2.
Passing Methods [edit]
By default, values are passed to a function
through a method called pass by value. This
means that the value of the variable is passed,
not the variable itself. This would be like giving a
person a copy of your driver's license. They can
read all of your information and they can change
whatever they want on their copy, but the original
is not altered in any way.
If desired, a value can be passed through a
method called pass by reference where the
function is actually given the address of the
variable, allowing it direct access to the
information. This is done by placing a '&' after the
data type in the function definition (this must also
be present in any prototype). So, if we were to
want to pass num1 using pass by reference, we
would say:

fctn(num1, 23);

as before in the main function, but in the


definition, we would say

void fctn(int& arg1, int arg2)

Following is a guide as to when one should use


pass by reference to alter data, and when one
should just use a return statement:

# values altered Return Pass by value Pass by reference


0 N Y N

1 Y Y N

2+ N N Y

You can mix between the use of pass by value


and pass by reference from parameter to
parameter, but it is not good programming
practice to mix the use of pass by reference and
returning.
Default Parameters [edit]
It's possible to assign default values to
parameters that are omitted from the function
call. The default values are usually defined in the
function prototype like this example:

int addTwoInts(int = 4, int = 5);

In this case, if the parameters aren't provided,


they will be assigned 4 and 5 respectively. So, for
example, if you had the call

temp = addTwoInts();

temp = addTwoInts(33);

Neither of these calls would raise an error. In the


first one, both values would be set to their
defaults. In the second example, the first
argument would be passed 33 while the second
argument would still be defaulted to 5. You
cannot default the second one without defaulting
the first one as well.
Scope [edit]
Scope refers to the level of access an object has.
A function can access only global variables and
those that are passed to it through arguments.
Also, any variable declared inside a function are
only available to that function. For example, an
integer declared in main will not be available to
any other function unless it is passed as an
argument. Vis versa, an integer declared in a
function will not be available to the main function.

Recursion [edit]
Recursion is a method of function calling in which
a function calls itself during execution. Let's start
by showing an example and then discussing it.

int factorial(int n)
{
if(n == 1 || n == 0)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}

This is a classic application of recursion. This


function calculates the factorial of a number. As
you probably know the factorial of n, written n!, is
the product of every number from 1 to n. So we
can say that 4! = 4×3×2×1. Let's step through
what happens in our function when we call num =
factorial(4).

1. factorial(4) is called

1. Since n=4, we take the else path. We return 4×factorial(n-1)

2. factorial(3) is called
1. Since n=3, we take the else path. We return 3×factorial(n-1)

2. factorial(2) is called

1. Since n=2, we take the else path. We return 2×factorial(n-1)

2. factorial(1) is called

1. Since n=1, we take the first path and finally return 1 to the previous function
1. factorial(1) returns 1 so factorial(2) can return 2×1...2

1. factorial(2) returns 2 so factorial(3) can return 3×2...6

1. factorial(3) returns 6 so factorial(4) can return 4×3...24

Many times, a recursive solution to a


problem is very easy to program. The
drawback of using recursion is that there is a
lot of overhead. Every time a function is
called, it is placed in memory. Since you
don't exit the factorial function until n
reaches 1, n functions will reside in memory.
This isn't a problem for the simple
factorial(4), but other functions can lead to
serious memory requirements.

Where To Go Next [edit]

Classes and Inheritance


Contents
[hide]

1. 1 Creating and Editing Classes

1. 1.1 A Description of Classes

2. 1.2 How to Make a Dog Class

3. 1.3 Creating a Class Containing


Functions

2. 2 Where To Go Next
Creating and Editing Classes [edit]
A Description of Classes [edit]
C++ uses classes to implement the object-oriented methodology. In short, object-
oriented design is a method for design which models data objects on the idea of a
real object, using variables to create traits for the object. For instance, you could
have a class that defines a dog:

Dog:

----

int name
int gender
int age
int size
bool healthy

This class has several variables: name, the gender of the dog, the age of the dog,
it's size, and whether or not it is healthy.

How to Make a Dog Class [edit]


class Dog
{

public:
char name[25];
int gender;
int age;
int size;
bool healthy;

};

This class may now be accessed from inside the program. Here is an example.

#include <iostream>

class Dog
{
public:
char name[25];
int gender;
int age;
int size;
bool healthy;

};

int main(int argc, char *argv)


{
Dog newDog;
newDog.gender = 1;
newDog.age = 3;
return 0;
}

As you can see, the program creates a dog named newDog, and sets it's gender to
1, and it's age to 3. However, this method is not advised, because it allows any class
or function to change the variables.
Creating a Class Containing Functions [edit]
To increase the safety of the variables, make them private. This will hide them from
every thing except the class that they are in. To change these variables, we create
functions inside of the class.
C++ comes with two default functions for every class you write. They are both
identical to the name of the class, so if your class is called "Dog", the default
functions will be Dog() and ~Dog() (notice the tilde at the front). The first function,
Dog() is called every time the class is created. The second one, ~Dog() is called
when the class is destroyed, or deleted. These functions do not have return values.
Here is our Dog class, with better protection for it's variables, and functions to
change them.

#include <iostream>

class Dog
{
private:
char name[25];
int gender;
int age;
int size;
bool healthy;

public:
Dog(int getAge, bool getHealthy)
{
gender = 1;
age = getAge;
healthy = getHealthy;
size = 20;
setName("Doggy");
}

//This function sets the dog's name.


void setName(char getName[25])
{
for (int x = 0; x < 25; x++)
{
name[x] = getName[x];
}
name[25] = '\0';
}

//This function checks to see that the dog's age is possible, and
returns false if it is not.
bool changeAge(int getAge)
{
if (getAge >= 0 && getAge < 50)
{
age = getAge;
return true;
}
else
{
return false;
}
}

};

int main(int argc, char *argv)


{
Dog newDog;
newDog.setName("Puddles");
newDog.setAge(20);
return 0;
}

Where To Go Next [edit]

Templates 1
At times we find difficulties in programming, we want to make something work the
same for different objects and we often have to design the same thing several times
in order to make it work. Suppose you want to make a simple Vector class, as in
std::vector. Practically, in C, there is only one way to do it: Keeping type information
stored somewhere in your list. This is a very common problem in C, and several
people came up with several solutions for that, but now, in C++, the solution to all
type-insensitive (those who do not rely on class functions / members) classes and
functions came up. If you are one of those interested in the concept of generics
(same as type-insensitive), you are on the right place. Welcome to C++ templates.
Contents
[hide]

1. 1 Introduction

2. 2 Template
Functions

1. 2.1 Syntax

3. 3 Template
Classes

1. 3.1 Syntax

2. 3.2
Implementatio
n

4. 4 Where To Go
Next

Introduction [edit]
Templates are the mechanism by which C++ implements the generics concept. The
following example illustrates two non-generic (type-sensitive) functions for
multiplying two numbers, x and y:

int multiply ( int x, int y )


{
return (x * y);
}
double multiply ( double x, double y )
{
return (x * y);
}

Two functions that do the exactly same thing, but cannot be defined as a single
function because they use different data types.

Template Functions [edit]


Templates were made to fulfil the need to design generic code, that work the same
way in different situations. Many people get scared when they first look at a
template, as the syntax looks too complex for a very simple thing. Although the
syntax is indeed a little complex, it is just different, not harder, not easier than other
syntax presented in C++.
Syntax [edit]
To start a template, you must provide the following declaration:

template<class Type>

or

template<typename Type>

The keywords class and typename have the exactly same meaning in this case, but
some compilers may replace the word class for typename when giving you
information about the class, as it's often better accepted by programmers.
Type is our generic data type's name, and when the template is to be used, it would
be the same as Type was a typedef for your datatype, and that's exactly how it
behaves, therefore, whenever you use the word Type, you are talking about the data
type being used on your template. The following example now illustrates how the
multiply function would be written using a template:

template<class Type>
Type multiply ( Type x, Type y )
{
return (x * y);
}

To use the function, however, the full syntax is a bit weird:


int result = multiply<int> ( 2, 5 ); /* Yields 10 */

As a syntax sugar, C++ provides the option of hiding the type information, case in
which the data type used on the function call is assumed. For instance:

int r1 = multiply ( 2, 5 );
int r2 = multiply<int> ( 2, 5 );

Both yield the same result, as they are exactly the same. An important note to take
from here is that this is the one of the very few syntax sugars that templates have.
Optionally, a template can have more type options, and the syntax is pretty simple.
For a template with three types, called First, Second and Third, we have:

template<class First, class Second, class Third>

And it works exactly as the single-typed template. The template data types are order
sensitive, of course, so doing:

multiply<char, int> ( 2, 5 );

Is not the same as doing:

multiply<int, char> ( 2, 5 );

As the order the types are assigned changed.

Template Classes [edit]


As another powerful feature of C++, you can also make template classes, which are
classes that can have members of the generic type.
The Standard Template Library (STL) relies heavily on the power of template
classes for it's countless functionalities, as the containers std::vector and std::list, for
example. Examples on the implementation of both containers will be presented later
on, as well as some more.
Syntax [edit]
The syntax for template classes is exactly the same as for template functions. A
small difference is that you can never hide the type of a template class when you
instantiate it.
Therefore, a small class Node, with three members, previous, value and next can be
written as:

template<class Type>
class Node
{
public:

Type value;

Node* previous;
Node* next;
};

Notice one important thing: Although the data type for Node pointers previous and
next is hidden, the type Type is assumed. The same declarations could be written
as:

Node<Type>* previous;
Node<Type>* next;

Also notice that the exact same syntax used for function calling is used for class
instantiating. You can hide data types in specific cases, but for legibility and to
establish a solid coding convention, you shouldn't, unless you are on the same class
as the variable being declared / instantiated.
There is also the possibility of setting a default type, as in:

template<class T1, class T2 = int>

Or

template<class T1, class T2 = DefaultTemplateClass<T1>>

Both syntax are equally valid, and you can use previous types to define next ones
(as T1 is the template type for type T2).
Note it only works effectively (but you can do it otherwise) only when you have more
than one type, as when you have only one you would be lacking the template
argument, causing the compiler to give you an error:

template<class T1 = int>
class Useless
{
public:

T1 value;
};

Useless value; /* Wrong! */

Although the default type for the template class is valid, you can not lack the type
list when instantiating, and that's just why you should only define default arguments
for templates with more than one type (as the argument list would contain at least
one item), as in:

template<class T1, class T2 = T1>


class Useless
{
public:

T1 x;
T2 y;
};

Useless<int> value; /* Valid */

In that case, both T1 and T2 would be of type int, and using the single-type type list
is valid.
Note: The default type setting is available only for template classes, functions
do not present this feature, as they already set the defaults, as explained
before.
Implementation [edit]
Now lets get our hands to work on a simple yet useful class, which we'll call Vector.
Not to worry with minor problems such as dynamic memory allocation, which is
needed in this case (to make the Vector grow when needed and optionally make it
shrink when needed), we'll use an imaginary pointer that we believe contains an
allocated array for us to use as a storage.
Our Vector class will have two functions: push and pop. We will also define an
interesting thing we find in STL's std::vector, the iterators (to walk trough the list),
together with iterating functions begin and end.
To reach this goal, we will rely on a template class and some new concepts which
will be explained with the code. This is how it looks:

template<class Type>
class Vector
{
public:

typedef typename Type* iterator;

Vector ( Type* storage )


{
data = storage;

size = 0;
}

~Vector ( void )
{
/* Optionally free the allocated buffer here */
}

/* Puts the object on the last place in the */


void push ( const Type& object )
{
data[size] = object;

size++;
}

/* Virtually pops a member by saying size is one less */


void pop ( void )
{
size--;
}

/* Returns an iterator to vector's begin */


iterator begin ( void )
{
return &data[0];
}

/* Returns an iterator to vector's end (after last element) */


iterator end ( void )
{
return (data + size);
}
protected:

Type* data;

unsigned int size;


};

This illustrates perfectly just how simple templates really are, now get your hands to
work and, if you know how iterators work, play a little bit with the class, if not, don't
worry, a fast and objective explanation will be given soon. If you got curious about
the typedef we used to define iterator, head to the section relative to it in this
lesson.

Aside: Iterators

Iterators are an essential part of STL containers, that use this


concept as a base for container
walkingtrough. Although they have the same name in all of the various
containers, their
definitions is rather different, as each kind of container uses a
different method for storing
objects.
As an example, take our Vector class definition for iterator: A
pointer, as simple
as that. As our data class member is an array (probably allocated with
new[]), we
can walk trough it's members by simple incrementing / decrementing the
pointer and get a reference
to the value pointed to by dereferencing it.
Function begin returns an iterator to the first element inside our
array (the
data pointer itself, in this case), and function end' 'returns an
iterator to the
position where a new element will be stored in next push, so we know
when our iterator
equals end, there is no more elements to be seen. For the definitions
of another iterators
in STL, check STL sourcecode or your favorite documentation page.

A simple use of our vector class:

Vector<int> v;
Vector<int>::iterator vit;
for ( int i = 0; i < 10; i++ )
{
v.push ( i );
}

for ( vit = v.begin(); vit != v.end(); vit++ )


{
std::cout << (*vit) << std::endl;
}

Which then prints numbers from 0 to 10 in new lines, sequentially. It also illustrates
the use of iterators to walk trough the list.
As requested by HappyCamper, here is an example of a container template class
called List, that uses the same concept of std::list, the linked list.

template<class Type>
class Node
{
public:

Node ( Node* previous, const Type& val )


{
value = val;

prev = previous;

if ( previous != NULL )
{
previous->next = this;
}

next = NULL;
}

~Node ( void )
{
}

Type value;

Node* prev;
Node* next;
};

template<class Type>
class _List_Iterator
{
public:

_List_Iterator ( void )
{
}

_List_Iterator ( Node<Type>* object )


{
node = object;
}

~_List_Iterator ( void )
{
}

_List_Iterator& operator = ( const _List_Iterator& it )


{
node = it.node;

return (*this);
}

bool operator != ( const _List_Iterator& it )


{
return (node != it.node);
}

/* Sets internal Node pointer to next node */


_List_Iterator& operator ++ ( void )
{
node = node->next;

return (*this);
}

/* Sets internal Node pointer to previous node */


_List_Iterator& operator -- ( void )
{
node = node->prev;

return (*this);
}

Type& operator * ( void )


{
return node->value;
}

Node<Type>* node;
};

template<class Type>
class List
{
public:

typedef typename _List_Iterator<Type> iterator;


List ( void )
{
first = NULL;
last = NULL;
}

~List ( void )
{
Node<Type>* node;
Node<Type>* next;

node = first;

while ( node )
{
next = node->next;

delete node;

node = next;
}
}

iterator begin ( void )


{
return iterator ( first );
}

iterator end ( void )


{
return iterator ( NULL );
}

void push ( const Type& object )


{
Node<Type>* node;

node = new Node<Type> ( last, object );

if ( first == NULL )
{
first = node;
}

last = node;
}

void pop ( void )


{
Node<Type>* aux;

aux = last;
if ( first == last )
{
first = NULL;
last = NULL;
}
else
{
last = last->prev;
last->next = NULL;
}

delete aux;
}

protected:

Node<Type>* first;
Node<Type>* last;
};

A new iterator class had to be designed in order to overload the operators (to be the
same as our Vector class iterators, in practice). Also notice that, when the template
class instantiated (inside another class) is not of the class type, it requires the
argument list to be written.
Warning: Both of the classes, Vector and List, were written in request-time,
e.g. they didn't go through exhaustive tests to assure its secure execution, it
just illustrates the concept of template containers.
We can also easily design our counterpart of STL's std::pair, which we'll name Pair.
It goes as follows:

template<class T1, class T2>


class Pair
{
public:

Pair ( void )
{
}

Pair ( const T1& f, const T2& s )


{
first = f;
second = s;
}

~Pair ( void )
{
}

T1 first;
T2 second;
};

A pair is a very simple structure that holds two values (hence the term pair) that may
be of different types. For such achievement we use two arguments in our template.
Function first returns a reference to the first value and, function second, a reference
to the second one.
To be continued

Where To Go Next [edit]

Templates 2
Templates 2 [edit]
Templates can also be used with classes

using namespace std;

template <class T>


class myClass
{
// Attributes
T * storage;
int NElements;
public:
// Constructors & Destructor
myClass(int size = 0)
{
storage = new T[size];
NElements = size;
}
~myClass() {};
// Methods
int GetSize() {return NElements;}
T GetVal(int place) {return storage[place];}

void SetVal(int place, T val)


{
if (place + 1 > NElements)
{ cout << "Cannot place an value at position " <<
place << endl; return; }
storage[place] = val;
}
void push(T val) { SetVal(NElements++, val); }
void pop() { NElements--; }
};
int main()
{
myClass<int> mc1;
for (int i = 0 ; i < 10 ; i++)
{ mc1.push((i + 1)*(i + 1)); }

for (int i = 0; i < mc1.GetSize() ; i++)


{ cout << mc1.GetVal(i) << endl; }

cout << "-------------\n";

myClass<char> mc2;
for (int i = 0 ; i < 26 ; i++)
{ mc2.push((char) i+97); }

for (int i = 0; i < mc2.GetSize() ; i++)


{ cout << mc2.GetVal(i) << endl; }

return 0;
}

Where To Go Next [edit]

Das könnte Ihnen auch gefallen