Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,135,510 members, 7,751,493 topics. Date: Thursday, 29 February 2024 at 02:09 AM

Programming in C++: A tutorial - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Programming in C++: A tutorial (2759 Views)

Creating UWP Application In C# Or C++ (xaml) / My Company Need A C++. A Must Watch Video!! / [problem] Write A Program In C++ That Finds The Hcf Of 2 Numbers Without Using A Recursive Function (2) (3) (4)

(1) (Reply) (Go Down)

Programming in C++: A tutorial by elbaron(m): 3:34am On Nov 20, 2005
The purpose of this tutorial is to give a good understanding of the programming language C++ to any person that wants it.

So what is C++? Why are so many programs written in C++?

C++ is a third generation programming language. When computers were first invented, they were programmed with very simple, low-level commands. A programmer would design a program, then translate the program into a specific set of codes, known as machine language. These codes would be fed into a computer with switches, punch-cards, or primitive keypads. These programs were cumbersome to write, and very hard to debug. (Debugging is the act of removing mistakes in a program.) Machine code is considered the first generation of programming languages.

Assembly languages are considered the second generation of programming languages. Assembly languages allow a programmer to design a program and translate it into machine language using a piece of software called an assembler. Most assembly languages are still very cumbersome to work with. However, the biggest disadvantage of assembly languages is that they are processor-specific. This means that programs written in assembly language will only work on processors similar to the one of the machine that they were written on.

Third generation languages are compiled languages. These languages are not processor-specific. In theory, a program written in a third generation language will be able to run on any other machine. This is not always the case, due to a number of factors. Third generation languages are much more abstract than assembly languages. Third generation languages are translated into assembly language by a complicated piece of software called a compiler. A compiler can be thought of a a language translater

C++ is a very useful language, because it gives the programmer a lot of control, but also is abstract enough so development can be done fairly quickly. C++ is a very portable language as well, because it is a third-generation language, and because it has a well defined set of standards written for it.

So, what exactly is a programming language? As a loose definition, a programming language is a tool used by a programmer to give the computer very specific instructions in order to serve some purpose for the user. A program is like a recipe. It outlines exactly the steps needed to create something or perform a certain task. For, example, when baking chocolate chip cookies, there are certain steps that need to be followed:

mix eggs, butter, sugar in a bowl
add flour, baking soda, and flavorings
mix until creamy
add chocolate chips
bake in the oven.

For a person who has made cookies before and knows the amounts of each ingredient to use, this recipe is sufficient, however, for a person who has never baked cookies before, this recipe will not do. That person would need a recipe like the following:

place two eggs in a bowl
add 1.5 c. butter to the eggs

bake cookies for 10-12 minutes at 375 degrees or until brown

There is still a problem with the preceding recipe. The first instruction says to put two eggs in the bowl, but it doesn't say to shell them first! This may seem like common sense, but it illustrates a fundamental concept: computers do exactly what they are told, no more, no less. When writing a program, a programmer must outline every possible step and scenario that could occur.

The first programming languages that emerged, were assembly languages. These languages are exactly the instruction set of a specific processor. These languages are very low-level and hard to understand. For example, say we wanted to add two numbers, 3 and 4 and get a result:
in C++:                                                                                     in assembly:  
int a = 3 + 4;                                                                             ldl  3, R1
                                                                                                 ldl  4, R2
                                                                                                 addl R1, R2, R3

The version in C++ is easier to understand and simpler to write. This is analagous to the differences in the first recipe presented and the second recipe presented. The first recipe expressed the method of baking cookies on a high level, while the second method went more in depth on how to actually mix and bake the cookies. Programmers write their code in a high level language and then use a compiler to translate their code into an assembly language and then into a machine language that will run on the machine they are using.

Programs consist of algorithms. An algorithm is just a well-outlined method for completing a task. The above recipes could be called algorithms for the task of baking cookies. A high level algorithm for adding two numbers could be as follows:

ask the user for the first number
ask the user for the second number
add the two numbers
display the result on the screen

This high-level abstraction is not actual code. However, it does express the ideas of a program, and is called pseudo-code. Often, programmers will design their programs in pseudo-code, and then use this to write their actual code.

So, why is there more than one programming language? It may seem that a standard language should be agreed on, since all languages are translated using a compiler anyways. However, languages are often designed with a specific use in mind, and some are better than others for dealing with certain problems. So if a programmer is capable of writing a compiler (which is a very complex piece of software) then they can design and create a language.

The most important thing to remember about programming languages is that they are only an abstraction! Programming languages were created so developers could express their ideas on a higher level than a computer can understand. Once a user has a good concept of how computers work, and has learned a few computer languages, it becomes much easier to pick up new languages.

A programming language is a tool used by programmers in order to specifically outline a series of steps that a computer is to take in a certain instance. High-level programming languages allow a programmer to express ideas on an abstract level, and forces the compiler to worry about the low-level implementation details. This allows for faster development of applications, since applications are easier to write. There are even fourth generation languages emerging as viable programming languages. Recall that machine code is considered first generation, assembly languages are second generation, compiled languages are third generation. Fourth generation languages are actually code-generating environments, such as Microsoft's Visual Basic. These fourth generation languages allow programmers to express their ideas visually, and the environment then writes the code to implement these ideas.

Before diving right into the nitty-gritty of C++ language details, let's get started with a full-fledged C++ program! The idea of this program is to introduce you to the overall structure of a C++ program and give you the flavor of C++.

Here, then, is an entire C++ program:

//include this file for cout
#include <iostream.h>

int main() {

 //print out the text string, "Welcome, to Nigeria. Our home, our Heritage!"
 cout << "Welcome, to Nigeria. Our home, our Heritage!" << endl;

 return 0;

}


To prepare for the next section, create a new text file and save this code into the file. If you are on a unix machine, save the file with the filename nigeria.C (make sure it ends with .C, not .c! That is a capital C). If you are on a Windows machine, save the file with the filename hello.cpp.

You're now ready to compile and run your program, covered in our next lesson. See you tommorrow.
Re: Programming in C++: A tutorial by Hunter(m): 4:50am On Nov 20, 2005
excellent job there mate smiley

Keep up the good work
Re: Programming in C++: A tutorial by c0dec(m): 1:54pm On Nov 20, 2005
elbaron:

(make sure it ends with .C, not .c! That is a capital C).


nice man. keep it up. grin. i've a question though. why uppercase C? saving it as *.cpp shouldn't be a problem (at least on linux).

elbaron:

//include this file for cout
#include <iostream.h>


these libraries are now deprecated. newer compilers will give u warnings when u compile. it's better if you use the STL libraries so instead of the above - u do something similar (notice the ".h" missing)


#include <iostream>
using namespace std;



just my 2 cents
Re: Programming in C++: A tutorial by demmy(m): 2:26pm On Nov 20, 2005
This is a great idea elbaron. Nice. Keep it coming. I hope people are interested in this.
Re: Programming in C++: A tutorial by elbaron(m): 1:16am On Nov 21, 2005
Hello c0dec, thanks for pointing out the correction. I should have included .h as the file extension. I am sorry about that. Typo error. About saving the file as *.cpp in linux, this would be too tidious and cumberson. Linux does have it's own compiler and that does not recognise .cpp file extensions. It is better to save the file at whatever.C. This explains to the linux box that its a C++ program and it will execute it as such. However, when you are writting in binaries (That is: 0s and 1s, you can save as *.cpp. But that is too advanced for the audience at the moment.). Thanks for the checks and balances. I hope somebody learns something from here
Re: Programming in C++: A tutorial by elbaron(m): 1:36am On Nov 21, 2005
A variable is a place to store a piece of information. Just as you might store a friend's phone number in your own memory, you can store this information in a computer's memory. Variables are your way of accessing your computer's memory.

Of course, your memory changes over time. Your friend moves across country and has a new phone number, and your friend's new phone number will replace the old one in your memory. Over time, as you acquire new friends, your memory will keep changing to store different pieces of information. Likewise, a computer's memory can change over time, if you tell it to. Since variables are your access point to your computer's memory, it makes sense that you'd be able to change the information in a computer's memory; otherwise, they wouldn't be called variables (they'd be called statics).

Why should you care about variables? Variables are the essence of any computer program! Without variables, computers would be useless. Imagine a program which asks the user for two numbers and adds them together, and prints the result.

# AddTwoNumbers
Enter the first number: 2
Enter the second number: 5
The sum of 2 and 5 is 7.
#

Sounds simple, right? But let's do a little role-playing to see what the computer has to do to execute this program. Instead of this interaction between a person and a computer, let's imagine the same kind of conversation between two people, Sol and Frank.
Sol: Hey Frank, I just learned how to add two numbers together.
Frank: Cool!
Sol: Give me the first number.
Frank: 2.
Sol: Ok, and give me the second number.
Frank: 5.
Sol: Ok, here's the answer: 2 + 5 = 7.
Frank: Sheesh! This guy is unbelievable!

After Frank says "2", Sol has to store that number in his memory somewhere. It may be stored in short-term memory, but he has to store it somewhere before Frank gives him the second number. Even if Frank were to give him two numbers in the same sentence, Sol would have to store the numbers somewhere in his memory to add them together.

In the sample program described above, the computer would most likely store "2" in a variable, then store "5" in a variable, and then calculate the sum by calculating the sum of the numbers store in the two variables.

Although there are similarities between a person's memory and a computer's memory, there are some pretty big differences. In C++, you need to grab a little piece of the computer's memory before you can use it. In other words, you have to tell the computer that you're planning to store a number in a variable before you can actually do it. This is called declaring a variable. To declare a variable, you need to know what kind of information it will store (i.e., will it store a number, or a text-string, or something else) and how you plan to refer to the variable (i.e., the variable's name). C++ imposes fairly strict rules on how you can name your variables:

variable names must begin with a letter
variable names are "case-sensitive" (i.e., the variable "myNumber" is different from the variable "MYNUMBER" which is different from the variable "mYnUmBeR"wink
variable names can't have spaces
variable names can't have special characters (typographic symbols)
What can you name your variables? In general, variable names can be composed of letters, numbers, and underscores (_). However, C++ reserves certain keywords which have special meaning to the language, and you are not allowed to use any of these keywords as variables names. Some examples of C++ keywords are int, for, else, and class. You can, however, use keywords in the middle of a variable name, such as "foreign" or "classical".

The flow of control
When a programmer is crafting a program, it is good practice to break the program down into pieces that can be thought of independently. Once the program has been completed, we can think of its execution as being a series of these pieces that work together in a certain sequence. These pieces then pass the control of the program between each other. While one piece has the control, the other pieces are inactive. This is known as the flow of control in a program. If our program had three parts, called Start, Middle, and End, the flow of control could look like:




control statements
Control Statements, then, are ways for a programmer to control what pieces of the program are to be executed at certain times. The syntax of Control statements are very similar to regular english, and are very similar to choices that we make every day. There are two basic types of control statements: branching statements and loops.

branching statements
We will first look at branching statements. Let's say Julien is shopping at a mall and he finds a CD that he wants to buy. Julien then checks his pocket to see if he has enough money to pay for the CD. When he pulls his money out of his pocket Julian may be thinking: "if I have more money than the price of the CD then I will buy the CD." In pseudocode that thought could be translated into:
if (my_money > cost_of_CD) then
buy_CD
else
get_a_job
end if;

Note that the pseudocode statement end if means "end the previous if statement." This is to make it clear what statements are inside the if statement and what statements are outside of the if statement.

Depending on a certain condition a certain series of events will be executed. Another type of branching statement is called a switch statement. A switch statement is just a shorter way of writing a lot of if statements. Switch statements will be explained in more detail in the next subsection.


nesting control statements
In the preceding situation, if Julien doesn't have enough money, before going out to get a job, he could look for a friend to borrow the money from. Now the pseudocode for this could be:
if (my_money > cost_of_CD) then
buy_CD
else
if (see_a_friend) then
borrow_money
else
get_a_job
end if;
end if;

Now there is one control statement that is inside of another control statement. This is known as nesting.

loops
Let's pretend now that Julien was buying a house instead of a CD. If Julien wanted to buy the house without taking a loan from the bank, he would have to wait until he had enough money to buy the house. The pseudocode for this could be:
if (my_money > cost_of_house) then
buy_house
end if;

But this means that Julien would only check once if he had enough money to buy the house. What we want to describe is the fact that Julien needs to keep waiting until he has enough money to buy the house.
while (my_money < cost_of_house)
work_more
end while;
buy_house;

This is a loop statement. Another loop statement is the for command. Let's say Julien wanted to add up how much money he would make over the next year. Let's say Julien is paid $500 twice each month. The pseudocode to figure this out could be:
int total=0;
for x = 1 to 24
total = total + 500
next x;
output total;

A for statement execute a specified number of times. In this instance it executes 24 times (12 months * 2 pay periods per month). In this example, it would actually be easier to write this code as:
total = 24 * 500;
output total;

But, what if Julien earns interest on any money that he saves? Now a for statement will be a handy tool. Let's decide that Julien spends $400 a month on rent, $75 a month on food, and $100 a month on other expenses. Let's also assume that Julien earns 2% per month on any money that he saves. Now our pseudocode could look like:
int monthly_expenses= 400 + 75 + 100;
int monthly_income = 1000;
float interest_rate = .02

// compute the amount Julien will have saved after one year
int total = 0;
int interest_earned =0;
for x = 1 to 12
interest_earned = total * interest_rate;
total = total + interest_earned + monthly_income - monthly_expenses
next x;

// display the value
output  total;

Control statements allow a programmer to craft a program so that certain parts of code execute multiple times, or not at all based on the current state of the program. Control statements are the most basic form of logical control within a program.
Re: Programming in C++: A tutorial by elbaron(m): 9:40pm On Nov 21, 2005
Up until this point, every line of code I've shown you has done a simple task, such as performing an arithmetic operation, or checking a boolean condition, or assigning to a variable. Functions allow you to do a whole lot in one line of code. Instead of performing a simple task, a single line of code can display a menu of choices, or compute complicated three-dimensional transformations, or even play Tetris!

How is this possible? Functions allow you to group a series of steps under one name. Remember when we were baking chocolate chip cookies? We had to perform the following steps:

place two eggs in a bowl
add 1.5 c. butter to the eggs
...
bake cookies for 10-12 minutes at 375 degrees or until brown

In C++, and in most programming languages, you can give a name to a series of steps. Let's say we want to call this procedure "bake cookies". Then, our algorithm for baking cookies becomes:
bake cookies

We've just created a function to do the work for us. Don't get too excited - you still need to know how to bake the cookies. You still need to know that the first step is placing two eggs in a bowl, and that the second step is adding butter to the eggs. In this example, what you would do is write a function called bakeCookies (C++ won't let you put spaces in the names of functions or variables) that performs the series of steps above, and then whenever you wanted to bake cookies, you would call the function bakeCookies, which would execute the lines of code necessary to carry out the procedure.

Note: When we say you are calling the function bakeCookies, we do not mean that you are giving it the name bakeCookies - you've already done that by writing the function. We mean you are executing the code in the function bakeCookies. "Calling a function" really means "telling a function to execute".

What are functions good for?
At this point, we've seen one reason why functions are useful. Functions let us create logical groupings of code. If someone is reading your code, and she sees that you call a function bakeCookies, she knows immediately that you are baking cookies. If, on the other hand, she sees that your code places eggs in a bowl, then adds butter, etc., it will not be clear right away that you are trying to bake cookies. Lots of recipes start out with putting eggs in a bowl, and lots of recipes add butter to the eggs. By the time she reads the last line, she might realize that you are baking cookies, but only if she is familiar with the recipe. It's possible that she won't realize that you are baking cookies at all! The point is, functions make your code much easier to read.

There is an even better reason to use functions: they can make your code shorter. Fewer lines of code is not always desirable, but every time you write a line of code, there's the possibility that you are introducing a bug. Functions start to reduce the number of lines of code when you call them repeatedly.

Suppose that you want to mail out invitations to eight of your friends for a cocktail party. Let's assume that you need to do the following procedure in order to invite your friend Hank.

write Hank's name on the invitation
write Hank's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

It takes five lines of pseudo-code to invite one friend, so it takes 40 lines of pseudo-code to invite eight friends. It would look like this:
write Hank's name on the invitation
write Hank's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

write Ann's name on the invitation
write Ann's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

write Alicia's name on the invitation
write Alicia's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

write Whitney's name on the invitation
write Whitney's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

write Greg's name on the invitation
write Greg's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

write Mi Young's name on the invitation
write Mi Young's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

write Flavio's name on the invitation
write Flavio's name and address on the envelope
place the invitation on the envelope
seal and stamp the envelope
drop the envelope in the mail

write Brian's name on the invitation
write Brian's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

That's a lot of repeated code, and any time you repeat code like this, you are more likely to add a bug to your program. For example, look at what we're doing with Flavio's invitation - we are placing it on, not in, the envelope! We sealed his envelope and dropped it in the mail, but there was no invitation inside. Flavio will receive an empty envelope and he'll be mighty confused. That's a mistake that resulted from having to type the same lines of code over and over again.

Functions can substantially reduce the amount of pseudo-code you need to write to invite your eight friends to the party. It seems unlikely that you'd be able to reduce this at all - each of your friends has got to have their own personally addressed invitation, and all of the envelopes have to be sealed and stamped and placed in the mail. How are we going to reduce the number of lines of code? Let's create a function called inviteToParty which does the following procedure:

write Hank's name on the invitation
write Hank's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

Now that we have this function, we can call it eight times to invite our eight friends:
inviteToParty
inviteToParty
inviteToParty
inviteToParty
inviteToParty
inviteToParty
inviteToParty
inviteToParty

You probably noticed a problem with doing it this way. We're inviting Hank eight times, and none of our other friends are going to receive invitations! Hank will get invited eight times because the function invites Hank to the party, and the function is being called eight times. The solution is to modify the function so that it invites friend to the party, where friend can be any of your friends. We'll change our function so that it looks like this:
write friend's name on the invitation
write friend's name and address on the envelope
place the invitation in the envelope
seal and stamp the envelope
drop the envelope in the mail

and then we'll change the way in which we call the function:
inviteToParty (friend = Hank)
inviteToParty (friend = Ann)
inviteToParty (friend = Alicia)
inviteToParty (friend = Whitney)
inviteToParty (friend = Greg)
inviteToParty (friend = Mi Young)
inviteToParty (friend = Flavio)
inviteToParty (friend = Brian)

Now, each time we call the function, friend is a different person, and each of our eight friends will be invited. We've just reduced the number of lines of pseudo-code from 40 to 13 by using a function, and our code became much easier to read. (We also got rid of that bug whereby Flavio received an empty envelope.)

All of the examples on this page were written in pseudo-code, but the next page describes how to write functions in C++.

Summary
Think of a function as a black box.







A "black box" is a convenient analogy for something that happens by magic. How does the black box work? It takes some inputs, and swirls them around inside the box, and produces some kind of output. Each function can swirl around the inputs in a different way, however that function so chooses. How a function will use the inputs to come up with the outputs is the essence of the function.

We just said that functions are like black boxes because we throw in some inputs, and something happens by magic, and some output comes flying out. The black box metaphor is really only appropriate when you are using other people's functions. When you write the function yourself, you have to know exactly how the function swirls up the inputs. It's not magical for you, because you decided how the function works. However, if you give your function to someone else for them to use, you can tell them it's a black box.
Re: Programming in C++: A tutorial by elbaron(m): 3:01am On Nov 23, 2005
Once you have designed your objects, writing the C++ code is simple. The hard part is designing objects that will interact well with each other, that will do everything you need them to be able to do, but nothing more. There is almost no new syntax you need to learn to write objects in C++. It involves using the syntax for variables and functions, so make sure you understand this syntax before continuing.

Let's continue to flesh out our text-based adventure game. First, we'll write the code for our Player object. In Chapter 6.1, we decided that players would have the following attributes, or member data: health, strength, agility, type of weapon, and type of armor. To simplify this example, we'll just use the first three attributes. We also wanted the Player to have the following actions, or member functions: move, attack monster, and get treasure.

To write the code for our object, all we need to do is declare the member data and member functions, and wrap them up inside an object declaration. Here's how it's done:

class Player {
  int health;
  int strength;
  int agility;

  void move();
  void attackMonster();
  void getTreasure();
};

This is a completely valid, working class declaration for the Player object. All we did was declared our member data (variables for our object) and member functions (functions that our object can use), and enclosed them inside a class declaration block. The class declaration block consists of the keyword class, followed by the name of the object, in this case Player, a pair of braces, and a semi-colon.

Of course, this object won't be able to do anything, because we haven't defined its member functions. Inside the class declaration, we said that the Player object would be able to do things like move, attack monsters, and get treasures; but we did not say how a Player would execute these functions. We need to write a function body for each function, so that a Player instance knows how to attack a monster, for example.

Here's the syntax for writing a function definition for a member function:

void Player::move() {
  //function body goes here
}


In other words, it's almost identical to writing a function definition for a plain-old, stand-alone function. The only difference is that we precede the name of the function, in this case move(), with the name of the object, Player, and two colons. This tells the compiler that this function is part of the Player class.

What is a pointer

So what is a pointer? A pointer is a way to get at another object. Essentially it is a way to grab an instance of an object and then either pass that instance a message or retreive some data from that object. A pointer is actually just an address of where an instance is held in memory.

Some piece of your program can either possess an instance of an object, or know where an instance of an object is. An instance of an object is a chunk of memory that is big enough to store all the member data of that object. A pointer is an address that explains how to get to where the instance is actually held in memory. Here's a quick example:

Our Player object has three pieces of data that it owns: strength, agility, and health. These are a part of the player object. That makes sense in real world terms. The player knows about two other pieces of data: the weapon and the armor that the player possesses.

So that is how to conceptually think of pointers. Now what's really going on? Memory in a computer is a complicated thing, but let's reduce it to it's simplest form: one large string of slots with addresses that data can be put in.


If we were to access the spot in memory with address 3, we would get the value 45. If we were to access the spot in memory with address 2 we would get the value "Dave". The previous diagram over simplifies two important concepts, however. First, each spot that has an address is the same size as every other spot. Second, what's held in memory is simply data. That is, the information there is just a string of binary data, 1's and 0's. The way that the data is viewed gives it meaning.
With these new ideas in mind let's Take a look at our previous diagram about the player and see what's really going on. Here is the pseudo code for the Player in a little more detail than we have seen:

class Player {
  // attributes
  int     health;
  int     strength;
  int     agility;

  // pointers to weapons and armor
  Pointer weapon;
  Pointer armor;

  // actions that a player knows how to perform
  void    move();
  void    attackMonster();
  void    getTreasure();
};

What follows could be a view of memory. This will seem fairly complex and is not imperative to understanding the c++ language. If it does not make sense right away, come back to it.

I have translated the actual binary values to their corresponding values in the context of our program. In this view an instance of a Player is stored at memory address 4098. The first attribute (instance variable) is there: health is 12. The second attribute is strength, 14. Then agility 16. The next attribute, stored at address 4104 is a pointer to an instance of a weapon object. If we follow that to the bottom of the diagram, there is the name of the weapon, "club" stored as ASCII values at address 6144 through address 6148 (the 0 ends the string). The next attribute for a weapon after name is rating, in this case 2, which means "poor" because I have decided that the rating system should be:

1 = very poor
2 = poor
3 = average
4 = good
5 = very good

Notice that all the memory contains is binary data. It is how that data is viewed that actually gives it meaning.
Re: Programming in C++: A tutorial by wale4x35(m): 10:50am On Nov 23, 2005
Hi elbaron,
First of all I must commend your efforts in putting up this great tutorial.

Just one or two things - Looking at the class declaration below.

class Player {
  int health;
  int strength;
  int agility;

  void move();
  void attackMonster();
  void getTreasure();
};

I think it would be helpful to readers or would-be C++ programmers if you could shed some light on certain features of a class statement that makes it a bit dofferent from struct statement. Namely,

[list]
[li]Private[/li]
[li]Public[/li]
[li]Protected[/li]
[/list]

Apologies if you intend to publish these attributes in your next tutorials.

Kind Regards,
Emmanuel.
Re: Programming in C++: A tutorial by elbaron(m): 12:39pm On Nov 23, 2005
Emmanuel, thanks a lot for the pointer. I am not a proffessional teacher so I will goof from time to time regarding my teaching methods. I thank you all for your corrections and suggestions. Seun, thanks too for your initial advise. Ajisafe, I am debugging a game of chess I wrote in Java, should be posted in the gaming section soon (if seun allows me..... cheesy). On the issue of classes and structures, here is the explanation:

The support that C++ provides for OOP (Object Oriented Programming) is concentrated in the class notion. The class is the unit of data abstraction in C++. On the surface the class can be viewed like a C struct or a Pascal Record definition. The class provides the programmer with a method to encapsulate, i.e. hide, the state of the abstract data type (ADT) and specify the external interface for use of the ADT.
Here is a simple class definition for a complex number data type. Features of the definition are describedbelow.

 
  class Complex
  {
  private:
      double re;
      double im;
 
  public:
      Complex(float r,float i) {re = r; im = i;}
      Complex(float r) {re = r;im =0;}
      ~Complex() {};
 
      double Magnitude();                  // calculate magnitude
     
      double Real() {return re;}           // return real part
      inline double Imag();                // return imaginary part
 
      Complex operator+(Complex b)
  {return Complex(re + b.re,im + b.im);}
 
      Complex operator=(Complex b)
          {re = b.re;im = b.im; return *this;}
  }
 
  inline double Complex::Imag()
  {
      return im;
  }
 
  double Complex::Magnitude()
  {
      return sqrt(re*re + Imag()*Imag());
  }
 
 
Class and Structure Members

Elements of a class or structure can not only be variables storing the state of the object, such as re and im in Complex, but also functions that perform operations on objects of that type. The functions can have parameters specified, such as with Complex in Complex which is a special class member called a constructor. Note here the C++ support for polymorphism by allowing function names to be overloaded with different parameters. The compiler will determine the correct function to use based on the data type of the parameters in the function call. Complex has two Complex constructors defined with different parameter lists. Code that is part of a member function of a class, such as the code in Complex::Magnitude(), has access to all members of the class directly. Within Copmlex. Magnitude references to re or im will access the data members of that object. Note that defining a class member function is exactly the same as a regular function except that the function name is prefaced with class-name::. A class function member can also be directly accessed inside of a class function which was done to get the imaginary part of the complex number in Complex::Magnitude(). Class member functions that are very short can be declared as inline functions. If code for the member function is defined within the class definition, such as Complex::Real() it is assumed to be an inline function. Otherwise, the function must be explicitely defined as inline and code provided outside of the class definition, such as Complex::Imag().

Public, private, protected members
When defining a class the programmer can specify the level of access to members of the class from outside of the class. The keywords private, public and protected define the levels of access. Any members defined below a public label are accessible directly by any other data type. Members below a private label are accessible only from within member functions of the class. If some private members, either data or function members, must be available to other classes these can be specified using the friend designation. As with the scope of variables in your program, good practice dictates limiting access to the data members of a class. If program code outside of the class definition must modify data members provide a class function to do this. Similarly, if code must access the data members of the class, define them as private and provide public class functions to access the data. If no access designators are provided, all class members default to being private. The orignal C struct has been enhanced in that it can now define member functions as well as data. struct can be viewed as a class in which all members are public. The protected keyword is used to allow derived classes to have access to some class members that are not available as public.

Derived Class
A derived class is a new class that inherits all of the properties of the class from which it is derived and may add new features specific to this new class. An example of this from a drawing program is that the programmer has defined a base class called Object. From this base class other objects are derived such as Rectangle and Circle. The are some aspects of the Object class that are shared by all objects. Each of the new objects may add other features such as a specific technique for drawing itself or calculating its area. If functions in this derived class need access to some of the base class's non-public members then those members can be declared protected. Alternatively, you could use the friend keyword to explicitely specify which other classes get access to the private members. A more detailed discussion of inheritance and derived classes will be discussed later.

Public access to class
Access to the public members of a class is through the structure access operators provided in standard C. If a has been declared as an object of Complex type then access to the magnitude of this complex number in an expression is gotten using a.Magnitude(). If b is declared as a pointer to an object of Complex type then access to the magnitude of this complex number in an expression is gotten using a->Magnitude(). If there are public data members in the class they can be accessed using similar syntax.

I hope this clears the air. If there are any further confusions, please let me know.

The El-Baron
Re: Programming in C++: A tutorial by elbaron(m): 6:03pm On Nov 25, 2005
We've already seen how to define member functions for a class, as follows:

void Player::getTreasure() {
health++; // increments the value of the player's health by one
}

There's another way in C++ to define your member functions. You can define them "inline", inside the class declaration. Here's how you would define getTreasure inline:
class Player {
private:
int health;
int strength;
int agility;

public:
void move();
void attackMonster();
void getTreasure() { health++; } // this is the function definition
};


The braces following getTreasure() contain the entire code for the function. We don't have to define the function later in our code using the Player::getTreasure() syntax -- in fact, the compiler won't allow it, because it's already been defined here inside the class declaration.

Why inline?
As you probably noticed, it's definitely fewer keystrokes to inline a function. However, another good reason to inline is that you can sometimes speed up your program by inlining the right function. Instead of calling the function every time it is invoked, the compiler will replace the function call with a copy of the function body. If it's a small function which gets called a lot, this can sometimes speed things up.

Depending on the function, it can also be easier to read inline. If it's a function like the following:

class Math { // class declaration
public:
int addTwoIntegers(int a, int b); // function declaration
};

int Math::addTwoIntegers(int a, int b) { // function definition
return a + b;
}


it's probably easier to read if it's inlined:
class Math { // class declaration
public:
int addTwoIntegers(int a, int b) {return a + b; } // inlined function
}; // (combined declaration and definition)



Why not inline everything?
Since the compiler will copy the entire function body every time the function is called, if it is a large function (more than three or four lines), inlining can increase the size of your executable program significantly. You may want to try to see what kind of speed gains you can achieve by inlining, and also compare the increase in the size of your executable.

And, just as it is sometimes easier to read functions if they are inlined, it is sometimes harder to read inlined functions. If a function is more than one or two lines, inlining it will more than likely distract a reader who is trying to understand how the class works. In these cases, it's probably better not to inline.

Using a Class (Instantiation)
Just as writing a class declaration was an extension of concepts we've already covered, the same is true of the syntax needed to instantiate an object. Instantiating an object is what allows you to actually use objects in your program. You can write hundreds and hundreds of class declarations, but none of that code will be used until you create an instance of an object. A class declaration is merely a template for what an object should look like. When you instantiate an object, C++ follows the class declaration as if it were a blueprint for how to create an instance of that object.

Instantiating an object
The good news is, you already know how to create an instance of an object! It is exactly the same as using a variable. Let's say you want to have four players in your game, each trying to find their way to the end of a maze faster than the others. You might start by creating four instances of your Player object, like this:

Player blueHat;
Player redHat;
Player greenHat;
Player yellowHat;

It's as easy as that. Although these objects are all Players, they are completely independent of one another. They were created from the same template, but they can have different attributes. For example, "blueHat" might be a slow, strong player, while "greenHat" might be quick and weak, and "yellowHat" might be a well balanced individual, etc. The thing that makes these objects similar is that they all must have values for strength, health, and agility, but nothing else. They can all move, attack monsters, and get treasures, but that is all they can do. So -- they are similar in the kinds of things they can do and the attributes they must have, but they are different in that they can each have their own values for those attributes.

Using an object's member functions
Now that we can create objects, we need to know how to use them. That is, we need to be able to use their member functions. Calling an object's member functions is similar to calling a regular function, with a slight twist.

Suppose someone is playing your adventure game, and they are controlling the player with the green hat. When the person hits the key to attack a monster, you need to make sure that the correct code gets executed so that the right player attacks the monster. The code would look like this:

greenHat.attackMonster();

It's very similar to the way that a regular function is called, preceeded by the name of the object on which the function should be called (greenHat), and a period. So, instead of calling the function attackMonster(), we are telling greenHat to call the function attackMonster. This is the power of C++. You can very easily "delegate responsibility" to the objects you've written, so that what seems like an impossible task, writing a video game, becomes much more manageable.

Now let's suppose that greenHat picks up a treasure. Somewhere in your program, the following will get executed:

greenHat.getTreasure();

This will cause the function getTreasure to be executed for the player with the green hat only. The other players in the game will not execute this function. Perhaps you write getTreasure to look like this:
void Player::getTreasure() {
health++; // increments the value of the player's health by one
}


Suppose that before greenHat picked up the treasure, the following were the players' values for their healths:
blueHat: 14
redHat: 11
yellowHat: 8
greenHat: 11

After greenHat picked up the treasure, the values would be:
blueHat: 14
redHat: 11
yellowHat: 8
greenHat: 12

Notice that only greenHat's health increased when the function Player::getTreasure was called; that's because the member function was called on greenHat only.
Re: Programming in C++: A tutorial by c0dec(m): 8:40pm On Nov 25, 2005
tip: i particularly like to inline my sets and gets and any maths functions i use. (hey, there's also the inline keyword)
Re: Programming in C++: A tutorial by Ivvie: 12:35am On Oct 27, 2007
You aren't programming in C++ till you program object orientedly. I love C++ and it's used in Computer Aided Engineering (CAE) and Industrial Design and Styling (CAID). Object Oriented programming in C++ is it!

(1) (Reply)

How Does A Rookie Java/j2ee Programmer Get A Job? / Urgent Help On Sparql Query Ontology / Interesting Things About The Darkweb

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 147
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.