Benefits of C++

There are a lot of benefits that you will be able to enjoy when using the C++ language. Some of these benefits include:

  • The big library: since C++ has been around for a long time, they have a library that is pretty large. This is available for you to use so you can pick out the codes that you want inside of your script and save some time and even learn some new things. You can also create some of your own codes if you wish, but this library can be really helpful for the beginner who is learning and can make it easier than ever to get the code written.
  • Ability to work with other languages: C++ is a great language to use with some of the other programming languages out there. This makes it easier to really work on the projects that you want because you can add in the parts that you like from different coding languages and combine them together to get something really amazing.
  • Works on many projects: most other programming languages are going to focus on just one or two little projects. For example, using JavaScript means that you are just going to be working on websites. But with C++, you are able to use it to help with a lot of different projects. Whether you are looking to work on a website, looking to create a new program, or do something else with programming, you will be able to do it with the help of C++.
  • Fast and reliable: if you have used some of the other coding languages that are popular in the past, you will find that sometimes they aren’t the most reliable. Information may slip through or they won’t start working the way that you would like. If you want something that works the first time and is reliable, then it is a good idea to go with C++.
  • Offers a lot of power: those who like to work in programming and want to have a lot of power in the work that they are doing will find that C++ is the right option for them to choose. It has some of the best power for the programming languages that are out there.

These are just a few of the benefit that you can enjoy when you are using the C++ programming language. It may seem a bit more difficult to use than some of the others, such as Python, but it has a lot of the power that you need and can work well with other programming languages. With a bit of practice, you are going to get all the basics of this language down and really enjoy what you are able to do with this programming language.

Let’s Begin

Let’s begin! There are a lot of places we can start, but let’s talk about environments first. While you do not really need to set up your own environment, as there are many online. An environment is a compiler of your choice that takes your code, and does all of the functions for you. In the old days, you would have to open your command prompts and create an environment to use, but those days are over. A simple mistake back in the day could do some serious damage to their computers. Now you can practice some risky prompts without any risk to your device whatsoever.

There are many examples to try out and use on the internet. To try them out, the easiest place to go is http://www.compileonline.com Choose the “Learn C++” option down at the bottom, and it will take you to where you need to go.

Now you can choose to type these codes into the compiler directly, or you can write several, and save them to your computer, and access them whenever, so that you don’t have to retype them every time you want to mess with them. You can use several different types of text editors. However, some of them are device type specific. This means they only work on the type of device that you create them on.

The text editors that you can use are OS edit command, Brief, EMACS, epsilon, Windows Notepad, vlm or vl. However, only vlm and vl are multi-platform usable. Make sure to save the files with the extension .c or .cpp.

You should start in a text editor to get the rough draft going on your program before you even think of moving to a compiler. This is because once you get to a compiler, it is a lot easier to mess up on your program, and not catch it. However, if you have it laid out in a nice, clean-cut fashion in a text editor, then you should have no problems with getting things going in the compiler.

C++ Compilers

There are many different compilers out there, and a lot of them are pretty expensive. Those compilers are for the elite programmers who have mastered the lower level compilers already. Beginners only need a basic compiler, and most of those are free. However, just like with anything that is free, you have to be careful of what you are getting. There are more bad cheap compliers than good ones out there so on the pretense of being free, I would suggest you paying additional functions past the startup page. These additional functions are usually very cheap anyways so you won’t have to break the bank to get them.

One of the most popular compilers available is the GNU C/C++ compiler. It is used most commonly in UNIX and Linux installations. To see if you already have the compiler, pull up the command line in your UNIX/Linux application and type in the following

 $ g++ -v

If the compiler is installed, then you should see this message on the screen:

Basic Syntax

C++ can be defined as not only the program, but objects that collectively communicate by invoking other methods. When you are working with C++ you should know what four things mean above all else.

Class

This is a template or a blueprint that states the object and its support type, and describes the behaviors of an object. This means that objects are sorted by their behaviors and their actions /supports into classes that fit the description of the object in question.

Object

Objects have behaviors and states. For example, if you look at a dog, it has states. These states could be classified as color, breed, and name, standard of breed (AKC/AKA/APC registries). “Dogs” also show certain behaviors as well. They wag their tails, they bark, they pant, they eat dry kibble, and they go to the bathroom outside in the yard. These things make dogs a unique object. These objects are classified into groups know as, you guessed it, classes.

Method

This is another term for behavior. There can be as many or as few as you choose in your classes. This is where all of the data is manipulated, and actions are played out, along with the place that all of the logic is written. Methods are especially important because without them, your program would not know what it is supposed to do with the variable that you give it. It would just sit there like a dud and do nothing.

Instant Variables

These refer to each individual object. Each object is classified with a unique set of these variables that act as a fingerprint for an object. These variables are assigned to the object by using values that occur whenever the object is created.

Now let’s break down the various aspects of the program that is set out above. There are several different aspects of this language that you have to take in consideration. Each aspect is important in getting it to run, and if you do not execute them entirely.

Headers

There are several headers out there for C++, and all of them are necessary or at the very least useful to your programming operations. However, for most functions you will see the header that is above <iostream>. When you use a header be sure to enclose it properly, and put #include before it to prompt the program to use that header.

Namespace

Namespaces are a fairly new addition to C++, only coming about in the 2011 update. They do not do much, other than describe which namespace to use. While they are not necessary, they save you a lot of confusion on functions of a program. It simply act as a way to organize your functions more systematically.

Main

Here is where the main function begins. Using the line // main() instructs the program to start executing the main function of the program, and start the output process. It is essential that you set up the main function command, otherwise your program will not know what it is supposed to be running, nor will it know when it is supposed to run. This will be seen as a single line comment inside the program and it is going to tell the program that the main function is beginning.

 INT main

This is where the function execution officially begins. If you do not include this, the entire process will stop, because you did not introduce the variables, and without the variables, the program is lost.

Cout

This instructs the program to display the message that you want on the screen. If you do not put cout, chances are your program will may or may not fail. The problem is you don’t know if you succeed or not so if you want to make sure that everything runs smoothly, be sure to add cout.

Return

This returns the value back to zero, and terminates the function. It instructs the program to end the process, and go back to the beginning.

Now to compile and execute your first official C++ program.

First you must know how to save the file. Open your chosen text editor, and enter the code that is seen above. Once you have done that, hit save as, and choose a file location that is easily found. For organization purposes, it is always best to have a separate folder for all of your programs. Save the file as hello.cpp, and once you have saved it, you should open up your command prompt before heading to the directory where the file is saved.

To get the file to open inside your compiler, start by typing ‘g++ hello.cpp’. You can then press enter and the code will be opened properly. As long as there aren’t any errors, the prompt is going to generate an ‘a.out’executable file. To run the program, type out ‘o.out’ and see the compiler work. The information that you should get on the compiler from this on the computer includes:

$ g++ hello.cpp
$ ./a.out

Try This

Make sure that you are inputting all of the variables the proper way, and remember, these things are case sensitive. If you do not input the functions the right way, you will find that things tend to go awry. The thing with coding is you have to be precise. This detailed oriented personal attributed applies to all programming languages! However, anyone can do it if they are willing to pay attention.

The basic function commands are not the only things that you need to use. There are other things that are important when you are building a prompt as well, as they too instruct the program to do specific things. Some of these things are blocks and semicolons.
You probably think a pause in a sentence when you think semicolon, however, they are complete stops in C++ programs. The semicolon indicates the termination of a statement. This means that each individual statement must be indicated by the use of a semicolon. The following are three different statements.

x=y;
y=y+1;
add(x,y);

Each one of those statements were separated by not only a line break, but also a semicolon. You could also do it this way.

x=y; y=y+1; add(x,y);

Each one of those will be recognized as separate statements simply because of the semicolon. It is kind of mind blowing how something so simple can have so much of an impact.

In this coding language, a block is going to be a set of statements that you enclose with brackets. These statements are logical entities that the program puts on the screen due to the main command prompt. For example

{
cout << “I like Pizza”>>; //prints I like Pizza
return 0
}

The end of a line is not a terminator, as was indicated above. The semicolon is the only thing that terminates the statement.

Introduction

C++ is a monolith. It’s one of the most widely used programming languages of all time. Though in modernity, it has slightly fallen to the wayside in popular programming due to the prevalence of scripting languages such as Python, Ruby, and Perl, and less esoteric and more natural languages such as Java and C#, C++ is still one of the seminal languages for low-level programming. Any time you’ve got to do something that requires direct access to the hardware and fast, efficient execution, you should consider C++ as your primary option.

Additionally, since it’s so ubiquitous, C++ is an essential language to learn because, as a programmer, you very well could end up maintaining legacy code written in C++.

In other words, C++ is no question a necessity for anybody wishing to seek a serious career in programming.

On top of that, C++ can be a very useful language for hobbyists, too. Many open-source video games are written partially or completely in C++, such as OpenTTD. Arduino circuits are coded in C/C++, as are Raspberry Pi units.

If for no other reason, you should learn C++ due to the simple fact that it’s incredibly powerful. C++ will allow you to do almost anything a language could allow you to do, while also being super functional and readable. It bridges the gap between lower-level more esoteric languages like C and higher level languages like Java and Python.

Getting Started

If you have just started programming, you may find yourself asking a lot of questions. For starters, you may wonder if it is necessary to learn the language beforehand. Well, you will have an advantage if you already know the language, but you will still do well even if you don’t. Beginners should not feel compelled to study it. It is alright if they have no previous knowledge of any programming language. This may actually be an advantage because you get to start with a clean slate.

How to Write Programs

C++ is quite demanding in terms of program design. Before you can write a program, you have to design it first. There are simple problems that you can do and practice on as a beginner. As time passes by, however, you will encounter programs that are more complex and these will help you grow. Even though they may give you a headache, they still help you get better at programming by testing your skills and encouraging you to learn more.

What makes a program good? Well, a good program can solve the problem it is meant to solve. It is able to solve it at the right time and on the right budget. A good program design is also free from bugs. This means that you should not encounter an error every time you run it. It should be easy to maintain, so you do not waste time and money on it. Statistics show that 90% of the costs involved in programs are related to maintenance and debugging.

When you first get ready to design a program, you need to ask yourself what problem you are actually trying to solve. Every program has to have a specific goal that is clear and articulated properly. Then, you need to ask yourself if you can really accomplish such task without the need to use custom software. Oftentimes, it is much better to buy a software program that is already made than to create a new one.

Programmers like to use their time wisely and they are aware that creating something new from scratch will take a huge fraction of their time, as well as require them to exert a lot of effort. So, as a programmer, you have to use resources that you already have on hand. Keep in mind that the programmers who are able to find alternatives to brand new solutions never lose work. You should always be able to find solutions that are inexpensive but also effective.

How about if your problem requires you to create a new program? Before you create one, make sure that you really understand the problem. You cannot provide a solution to a problem that you do not completely understand. You need to examine it carefully and think of the possible solutions. When you are confident that you know what you need to do, you can start creating the design.

The Development Environment

If your computer features a mode wherein you can directly write to its screen, you will have it easy when it comes to graphical environment. It is recommended that you use a graphical environment in Macintosh or Windows. Some users also use compilers that feature text editors built into the system. Others use text editors or word processors that create text files. Then, again, whatever you choose to write your programs in, you should be able to save it in plain text files. In other words, it should not have word processing commands in its text.

You are allowed to use Windows Notepad, Brief, EMACS, VI, Epsilon, and the DOS Edit command among other safe editors. You can also use commercial word processors like Word and WordPerfect. The files you make using editors will be referred to as source files. In C++, they usually come with a .c, .cp, or .cpp extension. You may want to check out your compiler and find out what extension it uses for your source code files.

Always remember that most of the C++ compilers do not mind the extension that you use for your source codes. However, if you do not specify a particular extension, your source code will be named with a .cpp extension by default. This is why you have to make sure that you are on a simple text editor when you make your source codes. You can also use the built-in editor of your compiler. It is not recommended to use a word processor that features special formatting characters for saving.

If you ever use a word processor, you should not forget to save your file as an ASCII text. You need to save your source code files using the appropriate extension as well as check your documentations for any specifics with regard to your linker and compiler. This is to make sure that you really know how to link and compile your programs properly.

You can search around if you want. You will find out that most of the free and widely used compilers are GNU C/C++ compilers. Then again, you can also get one from Solaris or Hewlett-Packard (HP), whichever is compatible with your operating system.

GNU C/C++ Compiler Installation

UNIX/LINUX Installation

You can use UNIX or Linux to create programs in C++. If you are using any of these operating systems, see to it that you verify the installation of GCC in your system. Simply type in $ g++ -v on your command line. You know that you have GCC if you can see the following on your screen:

Using built-in specs.

Target : i386 – redhat – linux
Configured with: / configure – – prefix = / usr . . . . . . .
gcc version 4.1.2 20080704 ( Red Hat 4.1.2 – 46 )

 If you do not have GCC installed, you have to install it. You can go to http://gcc.gnu.org/install/. See to it that you follow the instructions carefully, so you will not have any problems during installation.

Mac OS X Installation

If you are on Mac OS X, you can get GCC by downloading an Xcode development environment from the official website of Apple and following the installation procedures. It is really as simple as that.

Windows Installation

If you are on Windows, see to it that you have MinGW installed on your system. You can go to www.mingw.org and then click on the link that redirects to its download page. Make sure that you get the most recent version of the installation program and name it with

MinGW – < version > .exe.

When you install MinGW, you should not forget to install gcc-c++, gcc-core, MinGW runtime, and binutils. You are free to install more if you want. You should put your MinGW installation’s bin subdirectory to the PATH environment variable. This way, you can identify such tools on your command line using their names. Once you have completed the installation process, you can now run g++, gcc, ranlib, ar, and dlltool among other GNU tools.

Source Code Compilation

Even if your source codes are cryptic and not easy to understand, they should still be human-readable. Remember that a source code file and a program are not the same, so it cannot be run or executed like one. If you wish to change a source code and make it a program, you have to use a compiler. The way you invoke this compiler as well as how you command it to search for your source code varies from one compiler to another.

In C++, you have to choose RUN or type in tc < filename > on this command line. Here, < filename > is your source code file’s name. You may get a different result if you use another compiler. Once the source code has been compiled, you get an object file, which usually has a .obj extension. Then again, remember that it is not possible to execute this program. If you wish to execute it, you have to run the linker.

Creating Executable Files

You can create a C++ program by linking at least one OBJ file with one library or more. The library generally contains linkable files that come with the compiler. Either you have purchased it separately or you produced and compiled it. Take note that all C++ compilers feature a vast library full of procedures or functions. They also have classes that may be included in the program. Functions are blocks of codes that perform a specific function, such as printing to screen or adding numbers. Classes are collections of data and other functions related to it.

When it comes to creating executable files, you need to follow the correct steps. First, you need to make a source code file, using .cpp as its extension. Then, you have to compile your source code into a file. Use .obj as its extension. Finally, you have to link this OBJ file using the necessary libraries in order to produce your executable program. These three steps are crucial, so do not ever forget them.

The Development Cycle

You can have a complete development cycle when your program successfully produces your desired output on your first try. Just write your program and compile the source code. Then, you have to link this program before you run it. Then again, some programs do not let you achieve your objectives.

Some programs contain bugs or errors, which is why you have to check your code carefully. There are bugs that can cause a failed compile or link. Others may only appear once you started running the program. When you find a bug, no matter what type or category it belongs to, you have to fix it immediately. You have to edit the source code right away. You need to recompile, relink, and rerun your program.

Simple Programs

‘Hello World’ is the most commonly used phrase in programs. It is actually very easy to use. Just type it in your editor and then save, compile, link, and run it. If the program is successful, you will see ‘Hello World’ printed in your screen.

Here is how your program should look like:

1 : #include < iostream.h >
2 :
3 : int main ( )
4 : {
5 : cout << “ Hello World! \n “ ;
6 : return 0 ;
7 : }

Always pay attention to your punctuations. As you can see on the fifth line, the redirection symbol ( << ) is used. You can input it by holding the Shift key on your keyboard and pressing the comma key two times. Remember that you should end your code with a semicolon ( ; ). Otherwise, your program will not run.

See to it that you follow the compiler directions properly. Many compilers link automatically, but you should still check your documentation to verify things. In case you get an error, check your code again and find out if you forgot to include something.

If you encounter an error on the first line like cannot find file iostream.h, you should view the compiler documentation and search for directions on how you can set up the environment variables or include path. If you see an error that says you do not have a prototype for main, you should type in int main ( ) ; right before the third line. You need to include this line before the start of your main function. Most compilers do not really require it, but some still do.

This is what your program should look like:

1 : #include < iostream.h >2 :

3 :

4 : int main ( ) ;

5 : {

6 : cout << “ Hello World! \n “ ;

7 : return 0 ;

8 : }

If you run HELLO.EXE, you would get the following output:

Hello World!

Compile Errors

There are many different reasons why compile-time errors occur. More often than not, they are merely caused by typographical errors or any other minor errors. A good compiler will not just tell you whatever you did that is wrong. It will also direct you to the erroneous area in your code.

The easiest way on how to find out if there are errors in your program is to intentionally include an error in it. For example, you used HELLO.CPP and it was successful. You can edit it and remove your closing brace on the sixth line. Then, you have to recompile the program. You should get an error that is similar to this:

Hello.cpp, line 5 : Compound statement missing terminating } in function main ( ) .

When you see it, you should realize what the problem or issue is. Error messages generally tell you the problem’s file and line number. In this case, your problem is on the fifth line because the error message says so. Your compiler is not sure whether or not you really intended to place your closing brace before or after cout. There are times when errors only direct you to the general area of the problem or issue. If your compiler is capable of identifying all problems and issues, it can fix your code on its own.

Text Editor versus Word Processor

There is a difference between the text editor and the word processor that many users are not aware of. The text editor produces files that contain plain text. You are not allowed to use anything else other than plain text. The word processor, on the other hand, does not have any restrictions when it comes to special symbols and formatting commands. You can use text files, and they do not have an automatic bold print, word wrap, and italics among others.

Using the Built-In Editor of the Compiler

Compilers compile codes from the text editor. When you use the built-in text editor, you can move back and forth quickly between the compile and edit steps of your development cycle. Complex compilers generally have a development environment that is fully integrated. This allows you to access any help files as well as compile and edit codes. It also lets you resolve link and compile errors without having to leave the development environment.

Ignoring Warning Messages

When you see warning messages pop up on your computer, you have the option to either ignore them or attend to them. Most of the time, nothing really bad will happen if you ignore them. Nonetheless, it is still best if you would be wary of such warnings. If you see one, you should treat it as if it was an error. C++ compilers tend to warn users whenever they do something unintentionally. When you find out what these warning messages are about, you need to take the necessary action.

Compile Time versus Link Time versus Run Time

Compile time is the time you run the compiler while link time is the time you run the linker. Run time, on the other hand, is the time you run the program. As a programmer, you have to familiarize yourself with this shorthand so you can do your work quickly and efficiently.

Programming Fundamentals

C++ programs usually consist of objects that communicate through the invoking of their methods. They feature objects, classes, methods, and instant variables. An object has behaviors and states. A class tells about an object’s behaviors and states. A method is a behavior. There can be various methods in a class. These methods are where data are manipulated, actions are executed, and logics are created. The state of an object is developed by the values allocated to the instant variables.

Structure of a Program

The following are the different parts of a program.

#include < iostream >using namespace std ;

// The program starts to execute at main ( ).

int main ( )

{

cout << “ Hello World “ ;                                           // This line prints Hello World

return 0 ;

}

You can see that there are headers containing information or data. In the given example, the header < iostream> is used. The line in which using namespace std ; was written instructs your compiler to make use of the std namespace.

In the succeeding line, a single-line comment is written. Single-line comments start with // . This signifies that that particular line is meant for a comment or note. Comments are important in programs because they serve as reminders as well as improve the readability of the program. You can use comments to organize your codes better, so you will not be confused and commit a lot of errors.

You can add comments if you know that it will take some time before you complete your program. They will help you remember exactly where you left off, as well as what your previous codes were meant for. Comments are also beneficial to the readers. With comments, they will be able understand the codes better because they will know what the programmer wants to convey.

In this sample program, int main ( ) is where the program starts to execute. After that line, cout << “ Hello World ” is written. It prompts the phrase “ Hello World “ to be displayed on your screen. Then, there is the line that contains return 0 ; , which terminates the function main ( ) and prompts it to return 0, which is your given value, to the calling process.

Cout

It is used if you want to print a certain value on your screen. Do not forget to use the insertion operator ( << ) . It consists of two characters (the less-than symbol), but C++ still treats it as a single character. You have to enter your data after this character. Take a look at the following example:

1 : // This is a cout example.2 :

3 : #include < iostream.h >

4 : int main ( )

5 : {

6 : cout << “ Hey there, what’s up? \ n “ ;

7 : cout << “ This is the number 10 : “ << 10 << “ \ n “ ;

8 : cout << “ The endl is a manipulator and it writes another line to your screen. “ << endl ;

9 : cout << “ This is a huge number : \ t “ << 10000 << endl ;

10 : cout << “ This is the sum of 2 and 3 : \ t “ << 2 + 3 << endl;

11 : cout << “ This is an example of a fraction : \ t \ t “ << ( float ) 1/3 << endl ;

12 : cout << “ This is an example of a really huge number : \ t “ << ( double ) 5000 * 5000 << endl ;

13 : cout << “ My name is Wendy! \ n “ ;

14 : cout << “ I am an engineer and a master programmer. \ n “ ;

15 : return 0 ;

16 : }

If you run the code shown above, you will get the following output:

Hey there, what’s up?

This is the number 10: 10

The endl is a manipulator and it writes another line to your screen.

This is a huge number : 10000

This is the sum of 2 and 3 : 5

This is an example of a fraction : 0.333333

This is an example of a really huge number : 2.5e+07

My name is Wendy!

I am an engineer and a master programmer.

Using the output of the program, you have to analyze the structure, one line at a time.

On the third line, you can see #include < iostream.h >. The file iostream.h was added to the source code. If you are using cout and other related functions, it is necessary for you to use it.

On the sixth line, the command cout was used in its simplest sense; thereby, printing a series or string of characters. The \ n symbol is actually a special formatting character that commands cout to print a newline character.

On the seventh line, three values are passed to cout. An insertion operator separated each one of the three values. Your first value is a string. You wrote “This is the number 10:“Take note that the space found after the colon is still part of your string. The value 10 is then passed onto the newline character and your insertion operator. You can get the output when you use single quotes or double quotes.

This is the number 10 : 10

This output gets printed on your screen. Since there are no newline characters that follow the first string, the next value is printed. When this happens, the process of concatenation is done. The two values have just been concatenated.

On the eighth line, you gave out a valuable message about endl and you had it printed on your screen. It is crucial to put endl at the end in order for a new line to appear.

On the ninth line, you introduced \ t , which is another formatting character. Its main purpose is to insert a tab character. It is present in lines 9 to 12. It has to be there to line up their output. On the ninth line, integers are not the only ones that can be displayed, but long integers as well.

On the tenth line, you performed addition. It is a basic math procedure. You used the values 2 and 3. Adding them up results in the new value 5, which is shown in your output. The value of 2 + 3 is passed on to cout, which is why 5 is printed and displayed.

On the eleventh line, you passed the value 1/3 onto cout. Since you wanted such value to be evaluated as a decimal equivalent, you used float. This term causes cout to print out a fraction.

On the twelfth line, you passed the value 5000 * 5000 onto cout. You used double to indicate that you wanted a scientific notation to be displayed.

On the fourteenth line, you gave out some information about yourself and such information was printed to your screen.

Comments

Writing a program requires you to be careful and articulate. A messy program does not only cause errors, but it also results in confusion. If you have been working on a particular program for so long, you may tend to forget some details. This is why you have to take down notes.

Comments in programs seem to be unnecessary lines. However, they are actually needed because they help bring clarity and organization to your program. Without them, your program may be unclear and confusing. If you, yourself, cannot remember the details and understand your own program, how can you expect other people to understand it? The comments in C++ are merely texts that your system ignores. So, you can write anything in your comments sections.

Comment Types

In general, comments are divided into two categories: double – slash ( // ) and slash – star ( /* ) .

Double – slash comments, also known as C++ – style comments, tell your compiler to refrain from minding the things that follow them. Whatever you write after this comment, the compiler ignores. This goes on until it reaches the end of that particular line.

Slash – star comments, also known as C – style comments, tell your compiler to refrain from minding the things that follow them. Whatever you write after the star – slash ( */ ) comment mark is not read by your computer. Always remember that each /* has to be paired with a closing */ .

In the C language, the C – style comment is also used. However, the C++ – style comment is not really a part of it. A lot of C++ programmers prefer to use the C++ – style comment in their work and only turn to the C – style comment to block out huge blocks in their program.

Using Comments

As a programmer, you are advised to put comments at the start of your programs so that you can clearly define what these programs do. The moment you read a program, you should immediately be able to tell what its main purpose is. You should also be informed about its author as well as the date it was created. Likewise, you should know about the functions used in the program.

The statements that are not that obvious must include comments so they can be noticed more easily. You should remember that comments do not really affect your programs. When you run your code, the process and the output stay the same. Thus, you should not worry too much about creating perfect comments.

To help you understand comments better, take a look at the following example:

1 : #include < iostream.h >2 :

3 : int main ( )

4 : {

5 : /* This is an example of a comment

6 : that extends to the next line

7 : and to the line after that. */

8 : cout << “ Hi Wendy Dawn! \ n “ ;

9 : // This is an example of a comment that ends when the end of the line is reached

10 : cout << “ Good morning beautiful! \ n “ ;

11 :

12 : // This shows that you can use a double slash comment

13 : /* This one shows that you can use a slash – star comment */

14 : return 0 ;

15 : }

If you run the above given example, you will get the following output:

Hi Wendy Dawn!

Good morning beautiful!

As you can see in the program, the compiler ignored the comments on lines 5 to 7. Likewise, it ignored the comments written on the ninth, twelfth, and thirteenth lines. The comment you wrote on the ninth line ended when the end of the line was reached. Then again, the comments you wrote on the fifth and thirteenth lines required closing comment marks.

Comments Seen at the Top of Every File

Ideally, you should include a comment block at the start of each file you create. Their style depends on your personal preference though. So, you should feel free to tweak your programs in any way that you think is appropriate. Nevertheless, you have to make sure that your headers include the following:

  • The name of your program or function
  • The name of your file
  • The purpose of your program or function
  • A description or summary explaining how your program works
  • Your name, if you are the author of the program
  • A history of your revisions, including the notes you made on all changes
  • The liners, compilers, and other tools you used to create your program
  • Any other additional notes

It is very important to keep descriptions and notes updated. Do not make the mistake that a lot of programmers do. They tend to neglect the comments section once they are done with their programs. They think that it is okay to leave the comments since the program is already working.

Once you complete your program, see to it that you still check their headers. If you neglect these headers, the program becomes misleading over time. Readers get confused because they are not aware that the headers are not up to date. You have to keep in mind that comments can serve as invaluable guidelines to your overall program only if they are properly maintained. See to it that you re-visit your program once in a while and update its header.

Functions

The function main ( ) is unusual yet important in the C++ programming language. Throughout the program, you have to call or invoke functions. Your program is executed one line at a time. It follows the order in which it is written in the source code. This continues to occur until a particular function is reached. Afterwards, your program attempts to execute such function. Once successful, the function gives the control back to the line of code that immediately follows the function call.

Demonstrating Function Calls

To understand functions better, take a look at the following sample program:

1 : #include < iostream.h >2 :

3 : // This shows the function Sample Function

4 : // This prints out a message that you have selected

5 : void SampleFunction ( )

6 : {

7 : cout << “ In Sample Function\ n “ ;

8 : }

9 :

10 : // This shows that the function main displays a message before

11 : // calling out SampleFunction and printing out

12 : // another message

13: int main ( )

14: {

15: cout << “ At main \ n “ ;

16 : SampleFunction ( ) ;

17 : cout << Return to main \ n “ ;

18 : return 0 ;

19 : }

If you run the sample program shown above, you will get the following output:

At main

In Sample Function

Return to main

As you can see, the function SampleFunction ( ) has been defined on the fifth, sixth, and seventh lines. When it is called, it prints out a message to your screen and returns it. However, the actual program does not really begin until the thirteenth line. On the fifteenth line, main ( ) displays a message that says it is in main ( ).

Once this message has been printed out, the sixteenth line calls SampleFunction ( ). Because of this, the commands at SampleFunction (  ) are executed. Take note that your functions consist of the code that you have on the seventh line, which in turn displays a different message.

Once SampleFunction ( ) has been completed, it goes back to where it was first called. Still referring to the sample program shown above, it goes back to the seventeenth line, wherein main ( ) prints out the last line.

Functions either return void or return a value. When a function returns void, it does not return anything. A function that adds a couple of integers may return their sum, thereby returning an integer value. A function that only prints out a message does not have anything to return and is called to return void.

In general, functions feature a body and a header. The header consists of the function name, return type, and parameters associated with that particular function. The parameters of the function allow the values to be passed onto a function. Hence, if the function was to sum up two numbers, these numbers will be the parameters to that specific function.

The following is an example of a function header:

int sum ( int y , int z )

Parameters are declarations of the types of values that you intend to pass in. Arguments are the actual values passed in by your calling function. A lot of programmers make use of these terms and treat them the same. However, you can also treat them with a distinction.

The body of the function consists of opening and closing braces as well as a statement. You can use as many statements as you want. Conversely, you can use zero statements. As long as you still follow the correct syntax, you can skip using a statement.

Statements constitute the work of the function, which may return a value through the return statement. This statement also causes a function to exit. If you do not place a return statement into the function, it automatically returns void at its end. Such value has to be a type that is declared in your function header.

The #include

The word #include is never absent in a working program. It is a directive to the preprocessor. For every time you call on to your compiler, your preprocessor runs. The #include directive causes whatever file you name after it to be read as if it was typed in at that particular location in the source code.

The // Comment versus the /* Style comment

When it comes to comments, you can choose between these two. They are different from each other though. The double – slash comment ( // ) expires by the end of the line while the slash – star ( /* ) comment stays in effect until the closing comment ( */ ) is reached. The slash – star comment cannot be terminated that easily. Even when it reaches the end of the line, it may still continue until you place a closing comment mark. If you do not put this particular comment mark, you will encounter a compile – time error.

Bad Comments versus Good Comments

It should not really be difficult for you to tell apart bad comments from good comments. A bad comment only restates the function of the code. It states what is already obvious and you can eliminate it without experiencing any problems with your program. You know that the comment is bad when you read the line of code and you already get its point, including what it is, what it does, and why it does it. A good comment, on the other hand, tells you why such code does whatever it does. It also explains what that particular code section is about.

Constants and Variables

Your program has to store the data that it uses. Constants and variables have different ways of representing and manipulating data.

Defining Variables

A variable is where you store your program information. It is found in the memory of your computer. Here, you can store values that you can retrieve later on.

The name of your variable is a label. For instance, you can use the variable name my Variable. How many memory addresses there are depends on how big your variable name is.

RAM, on the other hand, stands for random access memory. Every time you run a program, it gets loaded from a disk file to a RAM. Every variable is also made in the RAM. In programming, memory is typically used to refer to the RAM of a computer.

Setting the Memory Aside

When you define a variable, you have to inform your compiler about the type of variable you used. You have to state if it is an integer or a character. You have to tell your compiler because such information becomes the basis for determining how much room you have to reserve and what type of value you can use to store your variable in.

The type of variable that you use tells your compiler how much memory it has to reserve for such variable. Since computers make use of bytes and bits when it comes to representing values, and since memory is usually measured in bytes, you have to take note of these concepts very carefully.

Integer Sizes

Every type of variable takes up a specific room amount. For example, an integer may be three bytes on a certain machine and three on another, but never changes when it is on either computer.

You can use the variable char to hold or store characters. Usually, it is a byte long, while a short integer is a couple of bytes long. A long integer, on the other hand, tends to be four bytes, while an integer that does not have the keywords long or short may be two or four bytes.

You should also learn about character, which takes up a byte of your computer’s memory. It is usually a letter, symbol, or number.

Take a look at the following sample program. It determines the size of your variable type.

1 : #include < iostream.h >2 :

3 : int main ( )

4 : {

5 : cout << “ This is the size of the int : \t \t “ << sizeof ( int ) << “   bytes . \n “ ;

6 : cout << “ This is the size of the short int : \t “ << sizeof ( short ) << “   bytes . \n “ ;

7 : cout << “ This is the size of the long int : \t “ << sizeof ( long ) << “   bytes . \n “ ;

8 : cout << “ This is the size of the char : \t \t “ << sizeof ( char ) << “   bytes . \n “ ;

9 : cout << “ This is the size of the float : \t \t “ << sizeof ( float ) << “   bytes . \n “ ;

10 : cout << “ This is the size of the double : \t \t “ << sizeof ( double ) << “   bytes . \n “ ;

11 :

12 : return 0 ;

13 : }

If you run the sample program shown above, you will get the following output:

This is the size of the int : 2 bytes .

This is the size of the short int : 2 bytes .

This is the size of the long int : 4 bytes .

This is the size of the char : 1 bytes .

This is the size of the float : 4 bytes .

This is the size of the double : 8 bytes .

It is okay if the number of bytes is different on your screen. Do not panic because every computer is different. The example only shows you the possible output that you can get when you run the sample code.

You may have also noticed that the function sizeof ( ) was used all throughout the fifth to the tenth lines. Your compiler provides this function, and it informs you of the size of the object that you pass in as parameter. Consider the fifth line. Here, int was passed onto sizeof ( ) . When you use sizeof ( ) , you will find it much faster and easier to identify that int has the same number of bytes as short int.

Signed and Unsigned Integers

Integers are either signed or unsigned. You may need negative values at certain times, so you have to know what type of integer you need. Integers are generally assumed to be signed, unless they contain the word unsigned. This applies to both long and short integers.

Signed integers are either positive or negative. Unsigned integers, on the other hand, are always positive. Unsigned short integers have the capacity to handle numbers between 0 and 65,535. Half of the numbers represented by signed short integers are negative. Signed short integers only have the capacity to represent numbers between -32,768 and 32,767.

Basic Variable Types

There are other variable types in the C++ programming language. These variable types may be divided conveniently into integer variables, character variables, and floating point variables. Floating point variables contain values that are allowed to be expressed as fractions. However, this is only possible if they are real numbers. Character variables can also contain just one byte. They are typically used for holding the two hundred and fifty-six symbols and characters of ASCII and its extended character sets.

The ASCII character set is a set of characters standardized to be used on computers. If you still do not know what ASCII stands for, it’s American Standard Code for Information Interchange. Almost all computer operating systems support ASCII, and many of them support international character sets.

The variable types typically used in programs are written as follows. Here, you will see the variable type and how much memory it takes up. You will also learn about the types of values that these variables can store. These values can be stored and determined through the size of their variable types.

The sizes of your variables may not be exactly the same as the ones shown in the sample table above. Again, this can be a case to case basis. It depends on the computer and compiler that you have. If you get the same results, then the table applies to the compiler that you use. Otherwise, you should check out the manual of your compiler to see which values are held by your variable types.

Defining Variables Examples

You define or create variables by means of stating the type, following it by at least one space and its variable name, and closing it with a semicolon.  For your variable name, you can use any letters. You can combine uppercase with lowercase letters. You can use numbers and combine them with letters for your variable name. However, you should never include a space in your variables.

For example, w, WendyDawn, W3ndY, and wendyy are all legitimate variable names. They may seem the same, but they are actually different. Also, even if you can use any variable name you want, make sure that you choose something that is beneficial to your program. Go for a variable name that tells you and your readers what the program is about. For instance, if you are using an integer variable named myAge : , you can write it this way:

int myAge ;

A rule of thumb is to avoid using gibberish names such as haFihDR93. You cannot make any sense of this word, and someone is most certainly not named that way. Also, you should avoid restricting your variable names to single letters because they tend to cause confusion even if they are legitimate.

As much as possible, you should use variable names that already give a clue as to what your program is all about. People should know what the program does even before they read the entire code or run the program. Expressive names like myAge, SpeedLimit, and howMany are all easy to understand and direct to the point. When you see these variable names, the first thing that comes to your mind may be to find out the age, speed limit, or number of a particular object in the program.

Take a look at the following example:

main ( ){

unsigned short a ;

unsigned short b ;

ULONG c ;

c = a * b ;

}

While it is perfectly clear that the program performs the mathematical operation multiplication, as evident in the variable c where the variable a is multiplied to the variable b, it is still unclear what these variables stand for. What exactly do a, b, and c represent? Are they units of measurement? Are they specific values? The lines of code do not make it clear what these variables are about. Therefore, these variable names are not ideal. Seeing this program for the first time may baffle you, especially if you do not have any previous experience with programming.

Take a look at another example:

main ( ){

unsigned short Area ;

unsigned short Length ;

unsigned short Width ;

Area = Length * Width ;

}

Referring to the example shown above, it is clear that the variables represent the area, length, and width of a particular object. This program is much easier to comprehend than the previous one. As you can see, the objective of the program is to find the area of a particular object by multiplying the length and width.

Operators

In this programming language, constants and variables are operated or controlled by the operators. The basic operators are practically the same as arithmetic operators.

These arithmetic operators include the plus sign ( + ) for performing addition, the asterisk ( * ) for performing multiplication, the minus sign ( – ) for performing subtraction, the forward slash symbol ( / ) for performing division, the percentage sign or the modulus (% ) for finding the remainder, and the equal sign ( = ) for assigning expressions.

There are also other operators used in C++ for additional tasks. For instance, the iostream header lets you use the insertion operator ( << ) if you want to process an output. You can also access other operators even without using the #include directive. These basic operators are classified under comparison operators, increment and decrement operators, logical operators, and compound assignment operators.

Variable Declaration

Before you use variables in your operations, make sure that you declare them first. You also have to identify their values. When you declare a variable, you have to use the following syntax:

type variable ;

Do not forget to specify the data type, just like when you initialize functions. So, if you want to declare w as an integer variable type, you need to initialize it. You can do that by typing this:

int w ;

Once you are done declaring w, you can allocate a specific value to it, with the use of the assign operator ( = ). For example, if you want to assign the value 10 to the variable w, you should write the following:

w = 10 ;

See to it that you declare the variable prior to assigning it a value. Likewise, you have to declare your variable and allocate a value into it by using just one line. For example:

int w = 10 ;

Other than using these expressions for your program, you may also want to consider using operators.

Increment and Decrement Operators

The increment operator consists of two plus signs ( ++ ). The decrement operator consists of two minus signs ( – – ). The primary purpose of these two operators is to make the expression of adding and subtracting 1 from the variable shorter so that you can save space in your program. You will also spend less time and energy in your code. For instance, you can use the following:

if w = 4 , then + + w must be equal to 5 while – – w must be equal to 3.

You can include the increment and decrement operators as either a suffix or a prefix in your program. You can do this if you want to identify the values of two or more variables. When you use the increment and decrement operators as suffices ( x++ or x – – ), the original value of x prior to the addition or subtraction of 1 would be denoted. If you run them on their own, both the x++ and the ++x would have a similar meaning. Conversely, if you use it in setting other variables, you would be able to notice that their difference is much obvious.

a = 5 ;
b = ++a ;

As you can see in the example shown above, the value of b is determined only after the value of a is increased. Thus, the value of b becomes 6.

a = 5 ;
b = a++ ;

Still on the same note, you can see that the value of b is determined before the value of a is increased. Thus, the value of b becomes 6.

Compound Assignment Operators

Aside from the standard assignment operator ( = ) and the basic arithmetic operators, you can also use compound assignment operators to perform operations before you assign values. These operators are practically shortened versions of the usual expressions involved in basic arithmetic operators.

x + = 1 ;                            // It is practically the same as the expression x = x + 1 ;x – = 1 ;                            // It is practically the same as the expression x = x – 1 ;

x * = y ;                            // It is practically the same as the expression x = x * y ;

x /= y ;                              // It is practically the same as the expression x = x / y ;

Comparison Operators

You can use comparison or relational operators to compare variables and expressions. These operators can help you verify whether or not a particular value is less than, greater than, or equal to another.

Comparison operators are often used to write condition statements. You can also use them to evaluate expressions and return Boolean values. Referring to the comparison operators in the table shown above, the following are sample expressions with their respective Boolean values:

( 8 == 1 )                             // This line evaluates to “false”( 8 != 1 )                             // This line evaluates to “true”

( 8 > 1 )                              // This line evaluates to “true”

( 8 <= 1 )                             // This line evaluates to “false”

As you can see, the Boolean value false becomes equivalent to the value 0. You can also see that the Boolean value true becomes equivalent to the other non-zero integers.

Arithmetic Operators

Logical Operators

Bitwise Operators

Misc Operators

Temperature Converter Example

Now, we’re going to tie together a lot of the concepts that we have covered so far by creating something which will convert from Fahrenheit to Celsius or vice versa.

Create a new console application project titled TempConvert, then delete the contents of your main method.

To create this program, we have to consider what all we want it to do.

This, in my mind, is the basic flow of the program.

  Start program

While the user hasn’t prompted to exit:

Ask user if Fahrenheit to Celsius or Celsius to Fahrenheit

If they input a certain character, let them exit.

If they input F or C, ask them to input the temperature.

Convert it, and write the product.

End program

So let’s start thinking about how we’d execute this.

We need to start at the beginning, so we’d type

 #include <iostream> Using namespace std;

After that, we’re going to need more than one function. Let’s make a Fahrenheit conversion function and a Celsius conversion function.

float ftoc(float temp);float ctof(float temp);

We gave these the argument “temp” because they’re going to take in a temperature that the user enters. After that, we need to create a main function.

int main() {

With that done, let’s think about what variables we need.

First, we need a boolean which will tell us if the loop is active or not. Let’s create that.

bool run = true;

We’ll need a character for user input, and we’ll also need floating point decimals so that we can accept temperatures. Let’s create those.

char input;
float temp;

Perfect. Now let’s create our main program loop:

while (run == true) {

The reason for making this loop is that somebody may have multiple temperatures to execute, and it would be a pain for them to have to restart the program every single time! It also serves as a way to implement a loop in the context of a program.

After this, we need to tell the user to enter F to convert Fahrenheit to Celsius, C to convert Celsius to Fahrenheit, or E to exit the program. This can be done with a simple cout command.

Then we accept their input with a simple cin for the character variable. If they enter an E, we need to change the variable “run” to false. This will exit the loop, which is only running while run is true.

 if (input == ‘E’ || input == ‘e’){       run = false;

    }

But there’s more. We have to parse if it’s an F or C as well, so that if statement becomes:

     if (input == ‘E’ || input == ‘e’) {                            return 0;

              } else if (input == ‘F’ || input == ‘f’) {

                            // todo: put code

              } else if (input == ‘C’ || input == ‘c’) {

                            // todo: put code

              } else {

                            cout << “The character you entered was invalid, please try again.”;

        }

So now that we’ve done that, we need to put code in the Fahrenheit and Celsius sections. Under the condition which goes if the input is “F”, we need to ask them to input the variable, then print out the converted number. Let’s do that. The else if for Fahrenheit should look similar to this:

         else if (input == ‘F’ || input == ‘f’) {                            cout << “Enter the temperature in Fahrenheit.\n”                            cin >> temp;

                            cout << “The temperature in Celsius is: “ << ftoc(temp);

              }

Then do the same for Celsius, which is just inverting it.

Afterward, we have to write the logic for those functions. I’ll guide you through Fahrenheit to Celsius, but you should do Celsius to Fahrenheit on your own as an exercise.

Let’s start like this:

   float ftoc(float temp) {                            // todo: add code

              }

The equation for Fahrenheit to Celsius is (F – 32) / 1.8.

We can just implement this in our program in our return value.

 float ftoc(float temp) {                            return (temp – 32) / 1.8;}

And voilà. As I said, you likely should do the Celsius on your own.

By the end, your program should look somewhat like this:

#include <iostream>using namespace std;

float ftoc(float temp);

float ctof(float temp);

int main()

{

    bool run = true;

    char input;

    float temp;

    while (run == true) {

  cout << “Enter F for Fahr to Celsius, C for Celsius to Fahr, E to exit.\n”;

        cin >> input;

        if (input == ‘E’ || input == ‘e’) {

            run = false;

        } else if (input == ‘F’ || input == ‘f’) {

            cout << “Enter the temperature in Fahr.\n”;

            cin >> temp;

            cout << “The temperature in Celsius is: ” << ftoc(temp) << “.\n\n\n”;

        } else if (input == ‘C’ || input == ‘c’) {

            cout << “Enter the temperature in Celsius.\n”;

            cin >> temp;

            cout << “The temperature in Fahr is: ” << ctof(temp) << “.\n\n\n”;

        } else {

            cout << “The character you entered wasn’t valid. Please try again.\n\n\n”;

        }

    }

    return 0;

}

float ftoc(float temp) {

    return (temp – 32) / 1.8;

}

float ctof(float temp) {

    return (temp * 1.8) + 32;

}

It’s a bit messy on this page, but it executes very cleanly and simply. And there you go! There’s your first genuine C++ program.

Now it’s time to get into some messier concepts like arrays and pointers. After that, we’re going to jump into some Standard Template Library things like strings and vectors before finally jumping into classes. There’s a long road ahead, but you have enough of a grasp on the basics by now to do pretty simple programs.

Arrays and Array Algorithms

Now we’re getting to one of the more fun concepts. What if you need more than one of a certain object? It’s very unwieldy to create variable after variable for the same exact thing.

For example, let’s say you had a classroom full of students, and you wanted to keep all of their grades for certain assignments and let’s say there were three assignments.

This very well could end up with you having multiple variables as such:

int student1grade1, student1grade2, student1grade3, student2grade1, student2grade2, student2grade3, ; // and so on…

So what if you could simplify them? Well, you can. Let’s say your class had 16 students.

With arrays, you could just make the following variables:

int assignment1grades[16] = { };
int assignment2grades[16] = { };
int assignment3grades[16] = { };

Now you have 16 preallocated variables for each assignment.

You can fill this array with data in two ways. You can either populate them when you declare them:

int assignment1grades[16] = {95, 72, 86, 84, 90, 89, (…) };

Or you can go in and populate them manually. Arrays start counting at 0, so if you wanted to change the first grade in an array, you would say:

assignment1grades[0] = 95;

Both are perfectly fine and workable and have their own times that they work best. Choose accordingly.

Now, what if you wanted to list off all of the variables in a populated array? This is where our for loop from earlier comes in handy.

for (int i = 0; i < 16; i++) {                            cout << “Grade #” << i + 1 << “: “ << assignment1grades[i] << “\n”;              }

These are called C-style arrays, and are a tad bit deprecated. However, this is crucial knowledge because:

1)    They’re easier to use and more efficient for beginners than template options, like vectors.

2)    They feature heavily in other languages, especially C-style languages e.g. Java and C#.

Since the goal here is to make you a master programmer, let’s talk a bit of problem-solving. Let’s say we took one of those grades arrays from before, and we wanted to sort it. How could we go about this?

I’m only going to teach you one way, but this manual sort algorithm very well may come in handy, and it’s useful for teaching you programming basics. This method of sorting is called bubble sort, and it uses nested loops.

             int placeholder;

              bool swap = true;

while (swap) {

        swap = false;

        for (int i = 1; i < 15; i++) {

            placeholder = 0;

            if (grades[i] < grades[i-1]) {

                placeholder = grades[i];

                grades[i] = grades[i-1];

                grades[i-1] = placeholder;

                swap = true;

            }

        }

  }

What this does is create a variable which determines whether there’s a swap to be made. For as long as there’s still a swap to be made, the variable will be true, and the second loop will iterate all the way through the array, comparing every variable to the one before it ([i] < [i-1]) to see if the current one is smaller than the one before it. If it is, we do a swap of the two variables and set the swap boolean to true so that we don’t exit the loop.

Arrays are an excellent starting point to the concept of having more than one of a certain object, and the concept of how C++ manages memory.

There’s one more important concept of arrays to cover, which is the idea of multidimensional arrays. Generally, you’ll only be using one and two-dimensional arrays, and we’ve already covered one-dimensional. So what about two-dimensional?

It’s a little bit difficult to visualize these but imagine it like this:

   int arrayName[rows][columns]

It’s essentially an array of arrays.

For example, array[3][4] would produce an array of three rows and four columns.

You access these by giving a specific index. For the previous example, if there were a 3 by 4 array declared, you’d access them like this:

If you wanted to change the value of the first row, second from the left, you’d type:

array[0][1] = value;

That’s a very simple explanation of multidimensional arrays but should cover it pretty plainly.

Pointers

This was one of the more difficult concepts for me to grasp, especially starting out. And it’s not necessarily easy to grasp, so I’m going to take it slow explaining this because this is actually a huge part of C and C++ programming.

When you create a variable, it’s given a specific place in memory. This place in memory is where that variable’s value is stored. Any reference to that variable when it’s passed to another function is just a copy of that place in memory.

This is fine when you’re just working within one function or passing simple arguments to/from, but look at this example.

#include <iostream>

using namespace std;

void goWest(int xposition, int yposition);

int main() {

              int xposition = 3, yposition = 3;

              cout << “Your current position is: ” << xposition << “, ” << yposition << “\n”;

              cout << “Going west!\n”;

              goWest(xposition, yposition);

              cout << “But back in the main function, your position is: ” << xposition << “, ” << yposition << “\n”;

              return 0;

}

void goWest(int xposition, int yposition) {

              xposition–;

              cout << “In the goWest function, your position is: ” << xposition << “, ” << yposition << “\n”;

}

Just type that into a file and run it. We’re going to be fixing this code anyway. You’ll see that what happens is the variable changes in the goWest function, but when we return to the main function, the variable is like it was before. This is because we don’t pass the variable directly, but we pass its value, and the secondary function makes a copy.

The way to fix this is with pointers. This isn’t at all their only use, but it’s the simplest way to explain them at this level. Pointers point to a variable’s specific address in memory and allow you to access that address and value precisely.

There are two pointer operators:

* – points to a value of an address

&- gets the address of a certain variable

The way that these work is that if you had int x = 3 then &x would point to the place in memory that the variable x is stored. Meanwhile, *(&x) would point to the value of x, here 3, and allow you to modify that value directly.

This way, you can bypass the built-in variable protection of C++.

To break it down even more, I’m going to write some code and then translate it into simpler terms.

#include <iostream>
using namespace std;void changeVariable(int * i);int main() {
    int x = 5;
    cout << “The value of x is: ” << x << “\n”;
    changeVariable(&x);
    cout << “The value of x is now: ” << x << “\n”;
}void changeVariable(int * i) {
              * i = 8;
}

So if we were to rewrite this using plain terms:

include iostream

using the standard namespace

declare a function called changeVariable, which takes an argument of a pointer address.

declare the main function

create a variable called x, then print its value.

call the changeVariable function, giving it the address of the variable x,

within the changeVariable function, since we sent it the address as an argument, the argument delimiter “int * i”. the “int *” portion takes any given reference address, and since we’re sending the address of x, i becomes &x. So the shorthand for what’s happening in the function is that it asks for a reference address to give to variable *i – we give it one, the address of x (&x) – and from there, *i points to the value of that address. (5)

change the value pointed to by * i to 8,

output the new value

The only thing that really helps you get this kind of thing is practice. Pointers are easily one of the most difficult concepts to truly comprehend in C/C++, but it’s the bread and butter of these languages and is part of what makes them so quick and reliable.

Memory management is the crux of what makes up any good C++ programmer, and knowing your way around pointers is essential to being sufficiently good at programming in C++. Passing around objects, pointers, arrays, templates, all of it gets incredibly frustrating – speaking from experience – especially as a newcomer to the language. My principal piece of advice is that you avoid getting discouraged too easily with anything about C++. I want to specify this in the pointers chapter, because it’s the most frustrating concept in the entire language for a lot of people.

Strings

To a certain extent, it feels a little late to be finally getting to strings. But the difference between strings in C++ and higher-level languages like Java and C# is that there’s a lot less abstraction between the raw muscle of the string in C++ than in other languages. It’s important that you understand the underlying concepts of arrays and pointers before you jump into the more developed and abstract parts of the language. There are lots of useful tools in C++, strings included, but they take a higher level understanding of the language to really grasp and use effectively. Otherwise, you could end up with compilation errors or other problems that simply make no sense at all.

Let’s look at a string conceptually. We spoke earlier about arrays. A string is simply an abstracted character array. In fact, in C, that’s precisely what they were. Strings were once programmed as character arrays, like such:

  char[] str = “hello”;

But this is deprecated and also rather difficult to work with, and a pain even when you do know how to work with them.  The new C++ standards offer a far superior manner of handling strings.

The first thing you’ll want to do to work with these templates is import a library called “string”. The header of your file would look like this:

             #include <iostream>
             #include <string>

The strings you handle from hereon are classes from the string template, which means they have a bunch of useful functions built right in.

Learning to manipulate strings is crucial to a lot of things and could prove useful in the future.

Go ahead and create a new project and call it StringManipulation. Delete the contents of main.cpp. Import <iostream> and <string> and declare your main function.

The first thing we’re going to do is create a string. Let’s call it x.

             string x = “”;

We’re going to initialize it to have no value right now, as it doesn’t really need one and it’s not a generally good idea in terms of memory and resource management to leave uninitialized variables and objects lying around.

Before we manipulate the input, let’s allow the user to enter the value of our string. However, we can’t do this by using the standard console input stream. If we try to do this, then it’s going to cut off after the first space, because the input stream sees this as the start of a new argument/variable.

Instead, we have to use the std namespace method “getline()”, which takes the arguments of the current input stream as well as the string which is going to assume the value of the line that was received.

 getline(cin, x);

Now that we’ve got the string, we’re going to do some things with it.

First, let’s print out a substring from the second character to the second to last character.

The string class has some handy built-in functions for things like this.

The function for substring is string name.substr(), and it accepts the arguments of the beginning index and the end index.

Remember how we talked earlier about how strings were just character arrays? Well, let’s say that the user entered “cat” as the string.

This would be interpreted, ultimately, as a four character array which goes like this:

      0      1      2      3
      c      a      t      \0

Where \0 is the null termination escape character which denotes the end of a string. If you had manually entered the string, like:

string x = “cool”;

then it wouldn’t be there. However, since we got the line, it’s there per necessity.

So the index of the second character of the string would be 1, of course. But since the user can input strings of various lengths, we need to get ahold of the string length somehow to get the second to last character.

There’s a function for that, thankfully. The string.length() function helps you to find the length of a string. To find the second to last character, we first have to subtract the last technical character of the string – the null termination character – and then the last real character of the phrase. The substring method should thus look like this:

 x.substr(1, x.length() – 2)

You can output this, like anything else, straight to the console output stream. Your line should look something like this:

cout << “Substring: “ << x.substr(1, x.length() – 2) << “\n”;

The string library is chock full of useful functions that you very well could end up using in the future. For example, in addition to creating substrings, you can also append things to a string and insert characters into the middle of them.

Arrays

An array is nothing more than a list of variables, all grouped together because they share common uses. It’s more a way of keeping everything neat and tidy, as you can see from the following code:

int a[5]

It looks like a standard variable but note the use of square brackets. These brackets contain the size of the array that you want in your declaration, or the number of variables, in this case, 5 integer variables. Arrays can be whatever size you want them to be, provided your computer has the RAM to take it but they can only have one type of variable in them at any one time.

When you want to access a certain variable, you simply put the number inside the square brackets. Just keep in mind that, when C++ labels variables, or anything, it starts at 0 and not 1. This does make a kind of sense, when you consider how a computer understands numbers. If your array had 8 items in it and you started it with the number 1, your computer can only read the first 7 places (Binary – 1-7). You could let it use the 0 as well but then 0 would be the first variable. The following code shows how you would handle accessing the variable that is before the first one in your list:

One thing you should keep in mind is that you should not try to access a variable that is non-existent, for example, the 9th variable in an array that has 6 places or that hast actually had a variable assigned. In this case you would get what is known as a “garbage” Value since what the computer returns will be just that – garbage.

In the first case, you would get a segmentation fault, called as such because the computer is trying to get into a segment of memory that it isn’t allowed to get into. This may result in the program terminating unexpectedly, couple with an error report. To avoid any of this happening, get into the practice of initializing every place in the array before you begin. As with a normal variable, it would look something like this:

  • int a[5] = { 0, 0, 0, 0, 0 };

Important – note the curly brackets. Each item that is inside these brackets, marked off with a comma between them, is assigned to a specific variable in the array. The first one is set to the value that is first inside the brackets, the second to the second, and so on. If the array is not filled, every unassigned variable will come back as 0:

  • int a[5] = { 1 };

You have declared that there will be 5 variables but only specified 1 so the others will be shown as 0.

One of the most common uses for an array is to show a list, maybe ages in a group, or, as I will show you in a while, using them to co-ordinate spaces in big tables and maps.

The array above is known as a one-dimensional array. This is useful for lists but what about maps? In this case, you would need a two-dimensional array and the easiest way to do that is simply to add a second set of square brackets:

  • int array[4][5];

So, the first dimension shows 4 integers and the second is 5 integers. Thinking in terms of arrays as a physical map, we could say that this one is 4 X 5 or it could be 5 X 4. Accessing the array is the same as accessing the one-dimensional array except for the number of square brackets we are using:

  • cout << array[0][1];

In the same way that you do a one-dimensional array, you can mass define a t dimensional array – all you do is add in a second set of curly brackets:

  • int array[2][2] = { {0, 0}, {1, 1} };

That isn’t as complicated as it looks – All it is doing is setting row 1 as 0, 0 and row 2 as 1, 1. So long as you remember to pair the brackets, it will all come together. If you wanted to iterate through the 2-dimensional array, you would simply put two forloops inside of each other:

You will probably have spotted that I didn’t follow the convention I just talked about and there is a technical reason for this. Because of the way C++ handles arrays that are 2-dimensional, it is far more efficient to increment the right array index in the inner loop – put simply, and the loops are saying that for each row, go through each column and move on to the next row.

I have increased y in the outer loop and x in the inner loop and, because of this, x should be in the right array index making point (0, 1) into point [1][0]. Although this is somewhat counterintuitive, it is important that you remember it.

C++ has a very neat ability to let you not specify a particular array size, instead letting you insert square brackets with nothing between them. At the time of compiling, the size of the array should be known so the compiler will simply count the initialized elements and set the array size according to that. This is quite useful if you have a large array and you really don’t want to count all of them:

  1. // This array will be 5 elements long
  2. int array[] = { 0, 1, 2, 3, 4 };

Although this means that your array can have an unknown size at the time of compiling, this kind of array cannot be created at runtime. That would be known as a dynamic array and is somewhat more advanced than this.

Remember that C++ is a very powerful language and is able to support n-dimensional arrays – this means that you can add as many dimensions as you need to. It is highly unlikely that you will ever go above 3-dimensional, simply because the human brain is not able to see any more than that accurately.

Classes and Objects

The main purpose of designing C++ is to add the concepts of object-oriented programming in C language. In object oriented programming, classes make the central feature. These classes are called as the user-defined types.

A class can be considered as a neat package that combines the data presentation and manipulating methods for that data. The form of an object is specified by a class. The functions and the data inside a class form the members of the class.

Encapsulation

Every program in C++ will have the following two fundamental elements.

  • Program statements (code): Program statements are the part of the program which is used to perform specific actions. These are called as functions.
  • Program data: Data can be considered as the information of the given program which is affected by the functions in that program.

Encapsulation is a concept in object oriented programming which binds the functions and the data that manipulate the data. Encapsulation protects the data from the interference and misuse by outer elements. The data encapsulation gave rise to an important object oriented programming concept called data hiding.

Data encapsulation can be defined as a mechanism that bundles the data and the functions that use the data. Data abstraction can be defined as a mechanism that exposes the interfaces and hides the implementation details.

By creating user defined types called classes, encapsulation and data hiding can be performed. As we already know, a class can contain private, public or protected members. The items that are defined in a class without access specifiers will by default to be private. Here is an example.

Example:
class Box
{
  public:
     double getVolume(void)
     {
        return length * breadth * height;
     }
  private:
     double length;      // Length of a box
     double breadth;     // Breadth of a box
     double height;      // Height of a box
};

Here, the variables length, breadth, and height are private. This means that only the members of the class Box are allowed to access them. Please variables cannot be accessed by any other part of the program. This is one of the methods in which encapsulation can be performed.

If you wish that some parts of your class be public, you should define them using the public keyword. All the functions and variables that are defined after the public specifiers will be defined as public and any function in the program can access them.

By making a particular class a friend of another class will expose the implementation details and results in the reduction of encapsulation. It is always wise to keep the details of the class hidden from other classes. As many classes as possible should be hidden.

Any C++ program where class is implemented with private and public members can be considered as an example for data abstraction and data encapsulation. Consider this example below.

Here is an example on data encapsulation.

Example:
#include <iostream>
using namespace std; class Adder{
  public:
     // constructor
     Adder(int i = 0)
     {
       total = i;
     }
     // interface to outside world
     void addNum(int number)
     {
         total += number;
     }
     // interface to outside world
     int getTotal()
     {
         return total;
     };
  private:
     // hidden data from outside world
     int total;
};
int main( )
{
  Adder a;
  
  a.addNum(10);
  a.addNum(20);
  a.addNum(30);   cout << “Total ” << a.getTotal() <<endl;
  return 0;
}

When you compile and execute the above code, it will produce the following output.

Total 60

The above class will add the numbers and will return their sum. Here the members addNum and getTotal are public and they are the interfaces which the user should know for use the class. Though the private members in the class are hidden, they are needed for the proper operation of the class.

Designing Strategy

It is always wise to hide the contents of a class by making it private unless we wish to expose them. This is good encapsulation.

Mostly the data members kept hidden but this equally applies to other members also which include virtual functions too.

C++ Class Definitions

Whenever you are defining a class, you are basically defining a blueprint for a given data type. Though this won’t define any data, defines what the name of the class means, which is, the objects that the class consists of and the operations that can be implemented on those objects.

The definition of a class begins with the keyword class, which is then followed by the name of the class and the body of the class enclosed inside curly braces. A list of declarations or a semicolon should be placed after the name of the class. Consider the following example in which the Box is defined by using the class keyword.

Example:
class Box
{
  public:
     double length;   // Length of a box
     double breadth;  // Breadth of a box
     double height;   // Height of a box
};

The public keyword will determine the access attributes of the class members following it. The public members of the class can be accessed by anyone outside the class within the scope of that particular class object. The class members can also be specified as private or protected and we will discuss it in later sections.

Define C++ Objects

Every class provides a blueprint for its objects, which implies that objects can be created from a class. The declaration of objects in a class is the same kind of declaration with which variables of the basic type are declare. For example, for declaring two objects of the Box class, we use the following statements.

Box Box1;          // Declare Box1 of type Box
Box Box2;          // Declare Box2 of type Box

The objects Box1 and a Box2 will have their own set of data members.

Accessing the Data Members

With the help of the direct member access operator (.), you can access the data members of an object of a class that are public. Here is an example that will help you to get a better understanding on this.

Example:
#include <iostream> using namespace std; class Box
{
  public:
     double length;   // Length of a box
     double breadth;  // Breadth of a box
     double height;   // Height of a box
}; int main( )
{
  Box Box1;        // Declare Box1 of type Box
  Box Box2;        // Declare Box2 of type Box
  double volume = 0.0;     // Store the volume of a box here   // box 1 specification
  Box1.height = 5.0;
  Box1.length = 6.0;
  Box1.breadth = 7.0;

  // box 2 specification
  Box2.height = 10.0;
  Box2.length = 12.0;
  Box2.breadth = 13.0;
  // volume of box 1
  volume = Box1.height * Box1.length * Box1.breadth;
  cout << “Volume of Box1 : ” << volume <<endl;

  // volume of box 2
  volume = Box2.height * Box2.length * Box2.breadth;
  cout << “Volume of Box2 : ” << volume <<endl;
  return 0;
}

When you compile and execute the above code, it will produce the following output.

Volume of Box1 : 210
Volume of Box2 : 1560

You should always keep in mind that the protected and private members of the class cannot be directly accessed with the director member access operator (.). Now, we will see how the protected and private members are accessed.

Classes & Objects in Detail

Till now, we have dealt with the basic concepts of the classes and objects in C++. We will discuss some more concerts in the subsections given below.

Interfaces

The capabilities or behavior of a class in C++ without committing to an implementation of its class can be described by an interface.

The interfaces in C++ are implemented with the abstract classes. Do not confuse Data abstraction with the abstract classes. The data abstraction is it different concept where the implementation details separated from the associated data.

By declaring any one function of a class as a pure virtual function, that class can be made abstract. You can specify a pure virtual function by adding “= 0” in its declaration. It is given in the example below.

class Box
{
  public:
     // pure virtual function
     virtual double getVolume() = 0;
  private:
     double length;      // Length of a box
     double breadth;     // Breadth of a box
     double height;      // Height of a box
};

The main purpose of any abstract class is to provide a proper base class so that other classes can inherit this base class. Objects cannot be instantiated using abstract classes. Abstract classes can only serve as interfaces. A compilation error will be raised when an object of an abstract class is tried to instantiated.

If you wish to instantiate a subclass of an abstract class, each of its virtual functions should be implemented. This implies that it will support the interface declared by the abstract class. When the pure virtual function override fails in a derived class and then trying to instantiate the objects that class will give a compilation error.

In C++, the classes used for instantiating objects are defined as concrete classes.

Abstract Class Example

In the following example, The parent class gives an interface for the base class to implement the function getArea().

Example:
#include <iostream> using namespace std; // Base class
class Shape
{
public:
  // pure virtual function providing interface framework.
  virtual int getArea() = 0;
  void setWidth(int w)
  {
     width = w;
  }
  void setHeight(int h)
  {
     height = h;
  }
protected:
  int width;
  int height;
}; // Derived classes
class Rectangle: public Shape
{
public:
  int getArea()
  {
     return (width * height);
  }
};
class Triangle: public Shape
{
public:
  int getArea()
  {
     return (width * height)/2;
  }
}; int main(void)
{
  Rectangle Rect;
  Triangle  Tri;

  Rect.setWidth(5);
  Rect.setHeight(7);
  // Print the area of the object.
  cout << “Total Rectangle area: ” << Rect.getArea() << endl;

  Tri.setWidth(5);
  Tri.setHeight(7);
  // Print the area of the object.
  cout << “Total Triangle area: ” << Tri.getArea() << endl;

  return 0;
}

When you compile and execute the above code, it will produce the following output.

Total Rectangle area: 35
Total Triangle area: 17

In the above example, an interface is defined by an abstract class in terms of getArea(). The same function was implemented by two other classes but with different for calculating the area that is specific to the given shape.

Designing Strategy

An abstract base class can be used by an object oriented system for providing a standardized and a common interface that is appropriate for all of the external applications. Then, the classes can be inherited from the abstract base class and these classes will all operate similarly.

All the capabilities (public functions) better offered by the external applications will be provided as pure virtual functions from the given abstract base class.The derive the classes will provide the implementations of these pure virtual functions. Each of these are derived classes correspond to a specific type of application.

With this architecture you are allowed to add new applications to a system even after it being defined.

 

Templates

Templates can be considered as the foundation of generic programming. Generic programming involves coding in a where that is independent from any particular type.

You can think of a template as a formula or a blueprint with which generic classes or functions can be created. A few examples of the genetic programming are the library containers which are developed using the concept of template.

Every container such as vector has a single definitions. But different kinds of ver cord can be defined. For example vector <string> or vector <int>.

Using templates, apart from classes functions can be defined as well. Now we will see how it works.

Function Template

The general syntax of a template function definition is given below.

template <class type> ret-type func-name(parameter list)
{
  // body of function
}

Here, the typeface of placeholder name for a data type that is used by the function. Within the definition of the function, this name can be used. Here is an example.

Example:

The function template in the following examples will return a maximum of two values.

#include <iostream>
#include <string> using namespace std; template <typename T>
inline T const& Max (T const& a, T const& b)
{
   return a < b ? b:a;
}
int main ()
{    int i = 39;
   int j = 20;
   cout << “Max(i, j): ” << Max(i, j) << endl;    double f1 = 13.5;
   double f2 = 20.7;
   cout << “Max(f1, f2): ” << Max(f1, f2) << endl;    string s1 = “Hello”;
   string s2 = “World”;
   cout << “Max(s1, s2): ” << Max(s1, s2) << endl;

  return 0;
}

If you compile and execute the given code, it will produce the following output.

Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World

Class Template

In C++, apart from defining function template you can define class templates as well. The generic class declaration syntax is given below.

Syntax:
template <class type> class class-name {
.
.
.
}

From the syntax given above, type is the placeholder type name. This type a name will be specified during the instantiation of a class. Multiple generic data types can be defined by separating them with a (, ).

In the following example, a class Stack<> is defined. Generic method to push and pop the stack elements will be implemented.

Example:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept> using namespace std; template <class T>
class Stack {
 private:
   vector<T> elems;     // elements  public:
   void push(T const&);  // push element
   void pop();               // pop element
   T top() const;            // return top element
   bool empty() const{       // return true if empty.
       return elems.empty();
   }
}; template <class T>
void Stack<T>::push (T const& elem)
{
   // append copy of passed element
   elems.push_back(elem);    
}

template <class T>
void Stack<T>::pop ()
{
   if (elems.empty()) {
       throw out_of_range(“Stack<>::pop(): empty stack”);
   }
              // remove last element
   elems.pop_back();         
}

template <class T>
T Stack<T>::top () const
{
   if (elems.empty()) {
       throw out_of_range(“Stack<>::top(): empty stack”);
   }
              // return copy of last element
   return elems.back();      
}

int main()
{
   try {
       Stack<int>         intStack;  // stack of ints
       Stack<string> stringStack;    // stack of strings

       // manipulate int stack
       intStack.push(7);
       cout << intStack.top() <<endl;

       // manipulate string stack
       stringStack.push(“hello”);
       cout << stringStack.top() << std::endl;
       stringStack.pop();
       stringStack.pop();
   }
   catch (exception const& ex) {
       cerr << “Exception: ” << ex.what() <<endl;
       return -1;
   }
}

After compiling and running the above code, it will produce the following output.

7
hello
Exception: Stack<>::pop(): empty stack

Namespaces

In real-time programming, you will encounter situations where you will have two objects with the same name in a given class. For differentiating the members of the same class having the same name we will have to add some additional information to them along with their names. For example if there are two persons with the name Charles, you can differentiate them using their area in which they live in or any such information like that.

Now consider a situation where this happens in your applications. For example, if there is a given function with a particular name defined and there is another function with the same name in a different directory. In such cases, the compiler cannot differentiate between the two functions and eight may not call the function which you are referring inside your code.

For overcoming this difficulty, will username spaces which are specifically designed to be used as the additional information that can be added to functions, variables, and classes etc. which share the same name in different libraries. By using namespaces, the context in which the names are defined can be defined. A namespace is used for defining a scope.

Defining a Namespace

You can define a namespace by using the keyword namespace which will be followed by the name of the namespace. The syntax for a defining a namespace is given below.

Syntax:
namespace namespace_name {
  // code declarations
}

For calling the name space version of a function or a variable, the namespace name should be added in front of that function as given below.

name::code;  // code could be variable or function.

Now we will have a look at how namespace scope the entities which include functions and variables.

Example:
#include <iostream>
using namespace std; // first name space
namespace first_space{
void func(){
     cout << “Inside first_space” << endl;
  }
}
// second name space
namespace second_space{
  void func(){
     cout << “Inside second_space” << endl;
  }
}
int main ()
{   // Calls function from first name space.
  first_space::func();
  
  // Calls function from second name space.
  second_space::func();   return 0;
}

When you compile and run this code, it will produce the following output.

Inside first_space
Inside second_space

The using directive

With the using namespace directive, prepending of namespaces can be avoided. This directive will instruct the compiler that the following code is using the names in that specified namespace.

You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is used in the following example.

Example:
#include <iostream>
using namespace std; // first name space
namespace first_space{
  void func(){
     cout << “Inside first_space” << endl;
  }
}
// second name space
namespace second_space{
  void func(){
     cout << “Inside second_space” << endl;
  }
}
using namespace first_space;
int main ()
{   // This calls function from first name space.
  func();
  
  return 0;
}

When the above code is compiled and run, it will produce the following output.

Inside first_space

A particular item in a namespace can be referred by the using directive. For example if you only intend to use the cout as the std namespace, it can be referred as given below.

using std::cout;

Without prepending the given namespace, cout can be referred by the subsequent code. This only implies to the cout and the other items present in the std namespace will be explicit. It is given in the small example below.

Example:
#include <iostream>
using std::cout; int main ()
{   cout << “std::endl is used with std!” << std::endl;
  
  return 0;
}

If the above code is compiled and run, it will produce the following output.

std::endl is used with std!

All the names that are introduced in the using directive will always obey the normal scope rules.

All the entities which have the same name defined in the scope that are outside will be hidden. And from the point of using directive, the name is visible to the end of the given scope. This is the score in which the directive is present.

Discontiguous Namespaces

You can define a namespace in several parts. This implies that I name space is made up of several parts that are defined separately. It is not necessary for all the separate files to be in a single place. These parts can be spread over many files.

So if there is a part of the new space which requires a defined name in some other file, that a particular name should be declared. In the following example, either a new namespace will be defined or new elements will be added to an existing namespace with the following namespace definition.

Example:
namespace namespace_name {
  // code declarations
}

Nested Namespaces

In C++, nesting of namespaces is allowed where one namespace can be defined inside another namespace. The syntax for nested namespaces is given below.

Syntax:
namespace namespace_name1 {
  // code declarations
  namespace namespace_name2 {
     // code declarations
  }
}

By using the resolution operator, the members of the nested namespace can be accessed. The syntax for using the resolution operator is given below.

Syntax:
// to access members of namespace_name2 using namespace namespace_name1::namespace_name2; // to access members of namespace:name1
using namespace namespace_name1;

If you use of the namespace_name1 from the above statements, the elements of the namespace_name2 will be made available for the scope as follows.

Example:
#include <iostream>
using namespace std; // first name space
namespace first_space{
  void func(){
     cout << “Inside first_space” << endl;
  }
  // second name space
  namespace second_space{
     void func(){
        cout << “Inside second_space” << endl;
     }
  }
}
using namespace first_space::second_space;
int main ()
{   // This calls function from second name space.
  func();
  
  return 0;
}

If the above code is compiled and run, it will produce the following output.

NESTED NAMESPACESInside second_space

Inheritance

In object oriented programming, inheritance is considered as an important concept. With inheritance, class can be defined in terms of another class. With inheritance creation and maintenance of applications is easy. Inheritance provides faster implementation time and it also reduces the code reusability.

When creating a class, the programmer can inherit the class members of an already exist in class avoiding the city of creating new member functions and new data members. The class from which the class members are inherited is referred as the base class and the new class is called as they derived class.

With inheritance, the is-a relationship is implemented. For examples, reptile is-a animal, snake is-a reptile and hence snake is-a animal.

Base & Derived Classes

When creating a class, the class is not limited to be derived from a single class. In C++, a class can be derived from multiple base classes from which it inherits the data and functions of all those classes. The class interrogation list can be used for specifying a derived class. The class derivation list can contain the names of one or more base classes. The syntax is given below.

Syntax:class derived-class: access-specifiers base-class

Here, the access specifiers can either be of the public, private or a protected. The base class is an already defined class. If there is no access specifiers used, it will be considered as private by default.

In the example given below, let us consider a base class named Shape and a class Rectangle derived from the base class.

Example:#include <iostream>

using namespace std;

// Base class
class Shape
{
  public:
     void setWidth(int w)
     {
        width = w;
     }
     void setHeight(int h)
     {
        height = h;
     }
  protected:
     int width;
     int height;
};

// Derived class
class Rectangle: public Shape
{
  public:
     int getArea()
     {
        return (width * height);
     }
};

int main(void)
{
  Rectangle Rect;

  Rect.setWidth(5);
  Rect.setHeight(7);

  // Print the area of the object.
  cout << “Total area: ” << Rect.getArea() << endl;

  return 0;
}

When you compile and execute the above code, it will produce the following output.

Total area: 35

Access Control and Inheritance

When a class is derived from a base class, the non-private members of the base class from which it is derived from can be accessed. If the class members of the base class declared private, they derive the class cannot access them. So in cases where you don’t want your derived class to access the class members or functions of the base class, you can declare them private.

The different access types are summarized in the table below based on who can access them.

Though a derived class inherits all the class methods of its base class, there are some exceptions.

  • The constructors, copy constructors and destructors cannot be inherited by the derived class.
  • The overloaded operators of a given base class cannot be inherited by the derived class.

The derived class cannot inherit the friend functions of its base class

Types of Inheritance

When a base class is used for deriving a class, the base class maybe inherited either through the public inheritance, protected inheritance or private inheritance. The access specifiers are used for specifying the type of inheritance. If the access specifiers are not used, the inheritance will by default to be a private inheritance.

The private or protected inheritances are hardly used when programming. On the other hand, public inheritance is the most commonly used type of inheritance. The following rules will be applied when using different type of inheritance.

  • Public Inheritance: When a class is inherited from a base class, the public members of the base class will be public members in the derived class as well. This is the same for the protected members of the base class. But in the case of the private members of the base class, they cannot be inherited as they can never be accessed by a derived class directly. The private members can be accessed through calls to the protected and public members of the given base class.
  • Protected Inheritance: When a class is derived from a base class with protected members, all the public and protected members of the class will become they derive the class’ protected members.
  • Private Inheritance: when a class is derived from a base class with private members, they derive the class will have all its class members as private.

Multiple Inheritances

In C++, the class is allowed to inherit members from multiple base classes. The syntax for multiple inheritances is given below.

Syntax:
class derived-class: access baseA, access baseB….

Here, the access can be anyone of public, private or protected and it can be declared for each of the base class separated by a comma. Here is an example.

Example:

#include <iostream>

using namespace std;

// Base class Shape
class Shape
{
  public:
     void setWidth(int w)
     {
        width = w;
     }
     void setHeight(int h)
     {
        height = h;
     }
  protected:
     int width;
     int height;
};

// Base class PaintCost
class PaintCost
{
  public:
     int getCost(int area)
     {
        return area * 70;
     }
};

// Derived class
class Rectangle: public Shape, public PaintCost
{
  public:
     int getArea()
     {
        return (width * height);
     }
};

int main(void)
{
  Rectangle Rect;
  int area;

  Rect.setWidth(5);
  Rect.setHeight(7);

  area = Rect.getArea();
  
  // Print the area of the object.
  cout << “Total area: ” << Rect.getArea() << endl;

  // Print the total cost of painting
  cout << “Total paint cost: $” << Rect.getCost(area) << endl;

  return 0;
}

When you compile and execute the above code, it will produce the following output.

Total area: 35
Total paint cost: $2450

Exception

An exception an object oriented programming can be defined as an interruption in the normal flow of execution of a program. It is the same in the C++. An exception in C++ can be defined as a response for an exceptional circumstance that occurred during the running of a program. Division by zero is an example for an exception.

When an exception is raised, the control will transfer from a part of a program to another part of the program. Exception handling in C++ is based upon the keywords try, catch and throws. We will discuss about them in detail.

  • throw: Whenever a problem arises, the program will throw an exception. This can be done by using the throw keyword.
  • catch: The exception thrown will be caught by the exception and let that is placed where you want the problem to be handed in your program. The catching of an exception is indicated by the catch keyword.
  • try: The purpose of the trial block is to identify the block of code where particular exceptions are activated. One or more catch blocks will follow the try block.

A method will catch an exception with the help of the try and catch combination of keywords by ensuring block which might raise an exception. The block of code which might possibly raise an exception will be placed inside the try/catch block. Any quarter that is placed inside the try/catch block will be considered as protected code. The syntax for the try/catch block is given below.

Syntax:

try
{
  // protected code
}catch( ExceptionName e1 )
{
  // catch block
}catch( ExceptionName e2 )
{
  // catch block
}catch( ExceptionName eN )
{
  // catch block
}

In cases where multiple exceptions are expected, multiple catch statements can be added for catching different types of exceptions raised in different situations.

Throwing Exceptions

By using the throw statements, exceptions can be thrown anywhere inside the given block of code. The type of the exception will be determined by the operand of that true statement. This can be any expression and the result of that expression will determine the expression thrown.

Here is an example where an exception is thrown when they give an integer is divided by zero.

Example:
double division(int a, int b)
{
  if( b == 0 )
  {
     throw “Division by zero condition!”;
  }
  return (a/b);
}

Catching Exceptions

Any exceptions raised will be caught by the catch block that follows the try block. The type of exception that you want to catch can be specified by determining the exception declaration inside the parentheses that follow the catch keyword.

Here is an example.

try
{
  // protected code
}catch( ExceptionName e )
{
 // code to handle ExceptionName exception
}

An exception of the type ExceptionName will be caught in the above code. You can specify the type of exception that you wish to handle with the catch block by putting an ellipsis, (…) inside the parenthesis that enclose the exception declaration. It is shown in the sample code given below.

try
{
  // protected code
}catch(…)
{
 // code to handle any exception
}

The below example will throw an exception raised due to division by zero. This raised exception will be caught in the catch block.

#include <iostream>
using namespace std; double division(int a, int b)
{
  if( b == 0 )
  {
     throw “Division by zero condition!”;
  }
  return (a/b);
} int main ()
{
  int x = 50;
  int y = 0;
  double z = 0;   try {
    z = division(x, y);
    cout << z << endl;
  }catch (const char* msg) {
    cerr << msg << endl;
  }   return 0;
}

Here, the exception raised is of the type const char* and for catching this exception should use the const char* inside the catch block. If the above code is compiled and run, it will produce the following output.

Division by zero condition!

Flow of Control in the try/catch blocks

Here is a simple example program in which exception handling of C++ is shown. This will help you to get a better understanding the try/catch block flow of execution.

Example:
#include <iostream>
using namespace std;
int main()
{
  int x = -1;
  // Some code
  cout << “Before try block \n”;
  try {
     cout << “Inside try block \n”;
     if (x < 0)
     {
        throw x;
        cout << “After throw (Never executed) \n”;
     }
  }
  catch (int x ) {
     cout << “Exception is caught here \n”;
  }
  cout << “After catch block (Will be executed) \n”;
  return 0;
}

When the above code is executed, it will produce the following output.

Before try block

Inside try block

Exception caught here

After catch block (Will be executed)

C++ Standard Exceptions

In C++, the list of all the standard exceptions are defined in the <exception> and it can be used in programs. These exceptions are listed in a parent-child hierarchy as given below.

The descriptions for the above exceptions are given in the table below.

 

Define New Exceptions

In C++, you are allowed to define your own exceptions. This can be done by inheriting and overriding the functionalities of the exception class. In the example given below, you can see how the std::exception class can be used for implementing your own exceptions.

Example:
#include <iostream>
#include <exception>
using namespace std; struct MyException : public exception
{
 const char * what () const throw ()
 {
   return “C++ Exception”;
 }
}; int main()
{
 try
 {
   throw MyException();
 }
 catch(MyException& e)
 {
   std::cout << “MyException caught” << std::endl;
   std::cout << e.what() << std::endl;
 }
 catch(std::exception& e)
 {
   //Other errors
 }
}This code will produce the following output.
MyException caught
C++ Exception

The what() is a public method that is provided by the exception class. The what() is overridden by every child exception class and because of an exception will be returned by this.

Preprocessor

In C++, the preprocessors directives instruct the compiler to pre-process the information before the start of actual compilation.

Every preprocessor directive will begin with the #, and on the line of the preprocess the directive, only whitespace characters may appear. As the preprocessor directives do not belong to C++, there is no need for adding a semicolon (;) at the end of the line.

As you have already seen, in all of the examples we have used the #include directive. This micro is used for including a header file into the source file.

In C++, there are a number of preprocessor directives. Some of them #include, #line, #define, #else, #if etc. Here, we will have a look at the important directives.

The #define Preprocessor

The #define preprocessor directive is used for creating symbolic constants. My crew is another name for the symbolic constant and the syntax for using the directive is given below.

#define macro-name replacement-text

Whenever the above line is seen in a file, the replacement text will replace all the subsequent occurrences of macro in that particular file. This will be done before the compilation of the program. Here is an example.

Example:
#include <iostream>
using namespace std; #define PI 3.14159 int main ()
{    cout << “Value of PI :” << PI << endl;    return 0;
}

Now, we will perform the preprocessing for this code. We will assume that the source code is there with us. We will compile the code with the -E option and the result will be redirected to test.p. If you open test.p, you can find a lot of information on the bottom and you will see that the value is replaced.

$gcc -E test.cpp > test.p
int main ()
{    cout << “Value of PI :” << 3.14159 << endl;    return 0;
}

Function-Like Macros

You can define macros which take arguments by using the #define preprocessor as given below.

#include <iostream>
using namespace std; #define MIN(a,b) (((a)<(b)) ? a : b) int main ()
{
  int i, j;
  i = 100;
  j = 30;
  cout <<“The minimum is ” << MIN(i, j) << endl;    return 0;
}

When the above code is compiled and run, it will produce the following output.

The minimum is 30

Conditional Compilation

You can actually compile selective parts of your code instead of compiling the whole program. In C++ there are several directives which will allow you to compile selected parts of your source code. This process of compiling a selected part in your source code is called the conditional compilation.

The construct of the conditional preprocessor is similar to the selection structure. Consider the following example.

#ifndef NULL
  #define NULL 0
#endif

Programs can be compiled for debugging purposes and the debugging can be turned on or turned off with a single macro. The syntax for it is given below.

#ifdef DEBUG
  cerr <<“Variable x = ” << x << endl;
#endif

From the above code, the statement cerr will be compiled if the DEBUG symbolic constant is defined prior to the  #ifdef DEBUG directive. You can comment out a part of the program by using the #if 0 statement. It is shown below.

#if 0
  code prevented from compiling
#endif

Here is an example which will help you to get a better understanding.

Example:
#include <iostream>
using namespace std;
#define DEBUG #define MIN(a,b) (((a)<(b)) ? a : b) int main ()
{
  int i, j;
  i = 100;
  j = 30;
#ifdef DEBUG
  cerr <<“Trace: Inside main function” << endl;
#endif #if 0
  /* This is commented part */
  cout << MKSTR(HELLO C++) << endl;
#endif   cout <<“The minimum is ” << MIN(i, j) << endl;

#ifdef DEBUG
  cerr <<“Trace: Coming out of main function” << endl;
#endif
   return 0;
}

When the above code is compiled and run, it will produce the following output.

Trace: Inside main function
The minimum is 30
Trace: Coming out of main function

The # and ## Operators

The # and ## preprocessor operators in C++. You can convert a replacement text talking into a string surrounded by quotes by using the # operator.

Have a look at the macro definition given below.

#include <iostream>
using namespace std; #define MKSTR( x ) #x int main ()
{
   cout << MKSTR(HELLO C++) << endl;    return 0;
}

If the above code is compiled and run, it will produce the following output.

HELLO C++

Predefined C++ Macros

C++ provides its users with a wide range of predefined macros. These macros are described below.

C++ provides a number of predefined macros mentioned below:

Now, we will have a look at an example in which the above macros are used.

Example:
#include <iostream>
using namespace std;int main ()
{
cout << “Value of __LINE__ : ” << __LINE__ << endl;
cout << “Value of __FILE__ : ” << __FILE__ << endl;
cout << “Value of __DATE__ : ” << __DATE__ << endl;
cout << “Value of __TIME__ : ” << __TIME__ << endl;return 0;
}

When the above code is compiled and run, it will produce the following output.

Value of __LINE__ : 6
Value of __FILE__ : test.cpp
Value of __DATE__ : Feb 28 2011
Value of __TIME__ : 18:52:48

Multi-Threading

Multithreading can be considered as a specialized form of multitasking and multitasking can be defined as the feature that allows your system to run multiple programs concurrently. There are two types of multitasking in general. They are

  1. Process based and
  2. Thread based.

In process based multitasking, the execution of different programs will be done concurrently. The thread based multitasking will take care of the concurrent execution of the individual pieces of that very program.

In a multithreaded program, two or more parts will run concurrently. Each of those parts is called a thread and every thread defines a part of execution which is separate to others.

There are no built-in applications for multithreading in C++. For multithreading, it completely relies upon the OS.

Creating Threads

For creating a POSIX thread, we will use the following routine.

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)

Here, pthread_create will create a new executable thread. There is no limitation for calling this routine and it can be called multiple times and anyway from your code. The description of the parameters is given below.

The maximum number of threads that a process can create depends on its implementation. A thread can create another thread and after their creation, threads act like peers. Implied hierarchy or a dependency cannot be found between threads.

The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads.

 

Terminating Threads

You can use the following routine for terminating a POSIX thread.

#include <pthread.h>
pthread_exit (status)

For explicitly exiting a thread, the pthread_exit is used here. The pthread_exit() routine is difficulty called after a thread completing its work and when it is not required any longer.

If the main() function ends with pthread_exit(), before the the threads that it has created, the other threads will not terminate and will still continue to execute. They will be terminated automatically when the main() function ends otherwise. Here is an example.

Example:
In this example, five threads will be created by the pthread_create() routine. Each of those are five threads will print a message “Hello World!” and will terminate by calling the pthread_exit().#include <iostream>
#include <cstdlib>
#include <pthread.h> using namespace std; #define NUM_THREADS     5 void *PrintHello(void *threadid)
{
  long tid;
  tid = (long)threadid;
  cout << “Hello World! Thread ID, ” << tid << endl;
  pthread_exit(NULL);
}

int main ()
{
  pthread_t threads[NUM_THREADS];
  int rc;
  int i;
  for( i=0; i < NUM_THREADS; i++ ){
     cout << “main() : creating thread, ” << i << endl;
     rc = pthread_create(&threads[i], NULL,
                         PrintHello, (void *)i);
     if (rc){
        cout << “Error:unable to create thread,” << rc << endl;
        exit(-1);
     }
  }
  pthread_exit(NULL);
}

Using the -lpthread library, compile the program as given below.

$gcc test.cpp -lpthread

Now, if you execute the above program, it will generate the following output.

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4

Passing Arguments to Threads

This example will show you how multiple arguments are passed via a structure. As the thread callback points to void, any data type can be passed in a thread. This will be explained in the example given below.

Example:
#include <iostream>
#include <cstdlib>
#include <pthread.h>using namespace std;#define NUM_THREADS     5struct thread_data{
int  thread_id;
char *message;
};void *PrintHello(void *threadarg)
{
struct thread_data *my_data;

my_data = (struct thread_data *) threadarg;

cout << “Thread ID : ” << my_data->thread_id ;
cout << ” Message : ” << my_data->message << endl;

pthread_exit(NULL);
}

int main ()
{
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;

for( i=0; i < NUM_THREADS; i++ ){
cout <<“main() : creating thread, ” << i << endl;
td[i].thread_id = i;
td[i].message = “This is message”;
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)&td[i]);
if (rc){
cout << “Error:unable to create thread,” << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}

When you compile and execute the above code, it will produce the following output.

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Thread ID : 3 Message : This is message
Thread ID : 2 Message : This is message
Thread ID : 0 Message : This is message
Thread ID : 1 Message : This is message
Thread ID : 4 Message : This is message

Joining and Detaching Threads

C++ provides its users with two routines with which they can join or detach threads. They are given below.

pthread_join (threadid, status)
pthread_detach (threadid)

The pthread_join() subroutine will block the calling thread until the thread with the specified threaded is terminated. When a new thread is created, an attribute of that thread will define if that thread is joinable or detached. You can only join the threads that are created as joinable threads and a detachable thread cannot be joined in any case.

In this example, it is shown how to wait for the thread completions with the Pthread join routine.

Example:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h> using namespace std; #define NUM_THREADS     5 void *wait(void *t)
{
  int i;
  long tid;   tid = (long)t;

  sleep(1);
  cout << “Sleeping in thread ” << endl;
  cout << “Thread with id : ” << tid << ”  …exiting ” << endl;
  pthread_exit(NULL);
}

int main ()
{
  int rc;
  int i;
  pthread_t threads[NUM_THREADS];
  pthread_attr_t attr;
  void *status;

  // Initialize and set thread joinable
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  for( i=0; i < NUM_THREADS; i++ ){
     cout << “main() : creating thread, ” << i << endl;
     rc = pthread_create(&threads[i], NULL, wait, (void *)i );
     if (rc){
        cout << “Error:unable to create thread,” << rc << endl;
        exit(-1);
     }
  }

  // free attribute and wait for the other threads
  pthread_attr_destroy(&attr);
  for( i=0; i < NUM_THREADS; i++ ){
     rc = pthread_join(threads[i], &status);
     if (rc){
        cout << “Error:unable to join,” << rc << endl;
        exit(-1);
     }
     cout << “Main: completed thread id :” << i ;
     cout << ”  exiting with status :” << status << endl;
  }

  cout << “Main: program exiting.” << endl;
  pthread_exit(NULL);
}

When you compile and execute the above code, it will produce the following output.

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Sleeping in thread
Thread with id : 0 …. exiting
Sleeping in thread
Thread with id : 1 …. exiting
Sleeping in thread
Thread with id : 2 …. exiting
Sleeping in thread
Thread with id : 3 …. exiting
Sleeping in thread
Thread with id : 4 …. exiting
Main: completed thread id :0  exiting with status :0
Main: completed thread id :1  exiting with status :0
Main: completed thread id :2  exiting with status :0
Main: completed thread id :3  exiting with status :0
Main: completed thread id :4  exiting with status :0
Main: program exiting.

Conclusion

That concludes my run through of C++ computer language. I hope that I have been able to give you some idea of how to get started with C++ computer programming. Once you get the hang of the basics and learn how to apply each rule, the world really is your oyster when it comes to programming.

It is important that you learn how each operator, variable, loop and conditional works independently and how to put them together to produce the code for the program you are aiming to write.  It is not too difficult a language to learn, but it will require your undivided attention to get it right otherwise, your compiler will be throwing up all sorts of errors and your programs just won’t run.

Enjoy your programming adventures and good luck!