Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Learn C++ (The Correct Way) - Lesson 1
#1
First of all you will require a C++ compiler; a compiler takes your code and converts to machine code so it can be executed by the operating system. To write the code you will require a text editor, luckily you can download/purchase an IDE (integrated development environment) which has a text editor and a compiler built into one. I recommend either Dev C++ (free) or Microsoft Visual C++ Express Edition (free) to begin with. Once you are feeling more confident with programming i would recommend Microsoft Visual Studio as it is an IDE for multiple languages (e.g. C++, VB, C#, J# and web development) and it includes some includes and libraries not included with the express edition. So what are you going to learn in this tutorial? Well we will be introducing the basics of a C++ program. It won’t do anything special except write a string of text to the console window. However, we will introduce how to retrieve and use user input. So let’s begin with our first program that will output the following string to the console window “Hello World!”, and then wait for the user to press a key
Open up the IDE of your choice and create a new file with the .cpp extension, call it what you want for the purpose of this tutorial I will call it HelloWorld.cpp. You should now have a blank document open, so let’s start coding.

So when you write a application in C++ and you want to add comments for later reference it can be easily done with two forwards slashes.

Code:
// This is a comment anything entered here will not be read by the C++ compiler.
Code:
/*
This is a multiline comment and will also not be read by the C++ compiler.
*/
So let’s actually write some C++ code, our first line in our HelloWorld application is:

Code:
#include <iostream>
This simply tells the C++ compiler to copy the contents of the file iostream into our application so we can use its functions. Include statements must go at the start of your program so that they can be used later in the program. Iostream is the basic input/output operations for C++ it allows you to write strings to the console window and also receive input from the user of the application.
Our next line of code goes directly below the #include statement:

Code:
using namespace std;

This line of code tells the compiler that our application will be using the standard library. Using this line of code allows us to simply write cout instead of std::cout, most people do not use this line of code which is a bad habit as it namespace pollution. Make sure you end the line of code with a semicolon (;) as it separates out your statements.
The next line goes below the last line:

Code:
int main() {
The int is short for Integral Type and is 32 bits in size. The C++ language specifies that the main has to return int. The main() tells the compiler that our program should start executing here. The curly brace after the two parenthesis tells the compiler that the main() starts here.
The next line will actually be the line which outputs the string to the console window:

Code:
cout << “Hello World!” << endl;

The cout is the standard output stream used by C++, the two less than signs is the insertion operator. Next you enter your string between two quotation marks “Example”, then call the insertion operator again (<<). Finally after the insertion operator you write endl which is short for end line which you may have guessed ends the line so no more text is written to that line, you write << endl so you don’t have to clutter up your string with \n which does the same thing.
The next line is placed directly below your cout statement:

Code:
cin.ignore();

This after the string is outputted to the screen waits for the user to press a key then shuts down the application. In other tutorials you may have seen system(“PAUSE”); which does the same as cin.ignore(); but says: Press any key to continue..., system calls are not a good thing to use. Also the cin.ignore(); doesn’t present you with a message which makes a nicer cleaner program.
The final line of code we use in this main() section is:

Code:
return 0;

This line ends the main() function, returning a value of 0 means that there was no expected errors.
After the return 0; line add the finally piece of code:

Code:
}

This tells the compiler that the main() section of code is finished.

Here is the complete source code:

Code:
#include <iostream>
using namespace std;
int main(){
    cout << "Hello World!" << endl;
    cin.ignore();
    return 0;
}
So if you copy/rewrite that into your C++ IDE then press compile and run or debug it will compile your code and turn it into an executable.

So now that we have created our first program that uses the output section of iostream include, let’s get some user input and display a message using the user input. So using our code from above place the following line after int main(){ and before cout << ... :

Code:
int age;
As mentioned before the int is a data type and stores a 32 bit value. Next there is the word age which is a variable name we are going to be using for when we retrieve and use user input (make sure you end the statement with a semicolon).
So now let’s use our age variable to retrieve an age from the user, first change the cout << string to a question the user can answer for the purpose of this tutorial the string will be “How old are you?”:

Code:
cout << "How Old Are You?" << endl;

This is the changed cout << statement.
So let’s get the users input after your cout << statement add this line of code:

Code:
cin >> age;

This line of code makes use of the iostream include and because we are using the standard library namespace we can just write cin. The cin parts asks the user to define what they should define age as e.g. (33). Like the cout statement you need the insertion operator, however for getting user input you use greater than signs rather than less than. After the insertion operator you say what variable you want the user to define and then end with a semicolon.
Add the following line under your cin line:

Code:
cout << "You Are " << age << " Years old!" << endl;

This uses the cout function and the insertion operator as used by our previous cout statement and also a string. However, unlike before you have the variable name surrounded by insertion operators then another string. The insertion operators basically take the value of age and place in the output, note: the insertion wrapped variable must be followed by two “” or a string e.g. in this case we used a string. The cout ends with the << endl; like before. The cin.ignore(); will not work here as it will end the program prematurely and having nothing will do the same so instead replace

Code:
cin.ignore(); with system(“PAUSE”);

If you know compile and run or debug this program it will ask for the users age, then allow the user to input an age then say how old they are.
Full source code listing:

Code:
#include <iostream>
using namespace std;
int main(){
    int age;
    cout << "How Old Are You?" << endl;
    cin >> age;
    cout << "You Are " << age << " Years old!" << endl;
    system("PAUSE");  
    return 0;
}

I hoped this help people in understanding the basics of a C++ program, more lessons on C++ coming soon.
Quote:Who has two thumbs and doesn't give a crap.......Bob Kelso......Have we met?
[Image: BobKelso.jpg]
Reply
#2
Great guide!
If you have any problems with the forum, feel free to email me via the User CP, or send me a Private Message.
Reply
#3
Of course its great, i wrote it. Ill transfer 2 and 3 from HF when i can be bothered.
Quote:Who has two thumbs and doesn't give a crap.......Bob Kelso......Have we met?
[Image: BobKelso.jpg]
Reply
#4
Thanks mate for this. Its awesome!
Reply
#5
I'll try to learn this someday , not in the mood for now.
Reply
#6
(10-04-2009, 06:05 PM)Code King Wrote:
Code:
using namespace std;

This line of code tells the compiler that our application will be using the standard library. Using this line of code allows us to simply write cout instead of std::cout, most people do not use this line of code which is a bad habit as it namespace pollution. Make sure you end the line of code with a semicolon (;) as it separates out your statements.

Actually, that's wrong. Using a "using namespace" IS namespace pollution. This isn't really an issue in a cpp file since it will only be polluted local to that file (unless you are using a unity build); however using it inside a header file is much worse since not only does all the contents of the std library then pollute your header file at a global scope, it also pollutes any files that include that header file. I never use "using namespace" inside a header file, even for my own namespaces (I do use it for my own namespaces inside a cpp file though).

Essentially namespace pollution gets it's name from the fact that it pollutes the "global scope" with other functions, classes, structs, enums, typedefs, etc, that were not originally there. This can lead to easily avoidable namespace conflicts.

For (a pointless) example, say you had your own class called "string" inside your own namespace called "mine", you also include the std:Confusedtring header file. Now this works all well and good, when you need to use your string you specify "mine:Confusedtring", and when you want to use the STL string, you use "std:Confusedtring". You promote your own namespace to the global scope since you know what's in it and everything is hunky dory.

Now, you add a "using namespace std;" to your file. What happens is that everything in the "std" namespace is promoted to global scope so that you can access it without adding the "std" part. You remove the "std::" qualifier and re-compile your code and see the following error.

Quote:error C2872: 'string' : ambiguous symbol could be 'mine:Confusedtring' or 'std:Confusedtring'

Why has this happened? Simple, the compiler now has two classes called "string" in the global scope and it doesn't know which one it should use. It requires you to solve this by explicitly scoping your usage of "string" with the correct namespace.

Code:
#include <iostream>
#include <string>

//! My namespace
namespace mine
{
    //! My string class
    class string {};
}

using namespace std;
using namespace mine;

int main()
{
    string stdString;
    mine::string myString;

    return 0;
}
Won't compile

Code:
#include <iostream>
#include <string>

//! My namespace
namespace mine
{
    //! My string class
    class string {};
}

using namespace std;
using namespace mine;

int main()
{
    std::string stdString;
    mine::string myString;

    return 0;
}
Will compile

I am not saying that using "using namespace" is a bad thing in all cases, it isn't and in most cases it saves a lot of unnecessary typing. I am however saying that you should only really use it for things you know the contents of. I doubt you know the name of everything that exists in the STL, and while the chance of getting a namespace conflict with it is minimal, I still wouldn't recommend it.

Ultimately it boils down to choice, namespaces were added to C++ to avoid conflicts between library code, and your code. Collapsing the namespaces of libraries is for the most part stupid, but it is your choice. It is because it is your choice that I never use a "using namespace" in my header files, because doing so would cause anyone using that header file to have their choice of whether or not they want to pollute their global namespace with my objects taken away from them, and that is not something I want to force on them.

tl;dr "using namespace" is bad in header files as it causes namespace pollution which propagates into other files.

Aside from that, the rest of the lesson is fine. Good job Yeye
[Image: sig.php]
The little boat gently drifted across the pond exactly the way a bowling ball wouldn't.
Reply
#7
Great Guide thanks!
Reply
#8
(10-04-2009, 06:05 PM)Code King Wrote: First of all you will require a C++ compiler; a compiler takes your code and converts to machine code so it can be executed by the operating system. To write the code you will require a text editor, luckily you can download/purchase an IDE (integrated development environment) which has a text editor and a compiler built into one. I recommend either Dev C++ (free) or Microsoft Visual C++ Express Edition (free) to begin with. Once you are feeling more confident with programming i would recommend Microsoft Visual Studio as it is an IDE for multiple languages (e.g. C++, VB, C#, J# and web development) and it includes some includes and libraries not included with the express edition. So what are you going to learn in this tutorial? Well we will be introducing the basics of a C++ program. It won’t do anything special except write a string of text to the console window. However, we will introduce how to retrieve and use user input. So let’s begin with our first program that will output the following string to the console window “Hello World!”, and then wait for the user to press a key
Open up the IDE of your choice and create a new file with the .cpp extension, call it what you want for the purpose of this tutorial I will call it HelloWorld.cpp. You should now have a blank document open, so let’s start coding.

So when you write a application in C++ and you want to add comments for later reference it can be easily done with two forwards slashes.

Code:
// This is a comment anything entered here will not be read by the C++ compiler.
Code:
/*
This is a multiline comment and will also not be read by the C++ compiler.
*/
So let’s actually write some C++ code, our first line in our HelloWorld application is:

Code:
#include <iostream>
This simply tells the C++ compiler to copy the contents of the file iostream into our application so we can use its functions. Include statements must go at the start of your program so that they can be used later in the program. Iostream is the basic input/output operations for C++ it allows you to write strings to the console window and also receive input from the user of the application.
Our next line of code goes directly below the #include statement:

Code:
using namespace std;

This line of code tells the compiler that our application will be using the standard library. Using this line of code allows us to simply write cout instead of std::cout, most people do not use this line of code which is a bad habit as it namespace pollution. Make sure you end the line of code with a semicolon (;) as it separates out your statements.
The next line goes below the last line:

Code:
int main() {
The int is short for Integral Type and is 32 bits in size. The C++ language specifies that the main has to return int. The main() tells the compiler that our program should start executing here. The curly brace after the two parenthesis tells the compiler that the main() starts here.
The next line will actually be the line which outputs the string to the console window:

Code:
cout << “Hello World!” << endl;

The cout is the standard output stream used by C++, the two less than signs is the insertion operator. Next you enter your string between two quotation marks “Example”, then call the insertion operator again (<<). Finally after the insertion operator you write endl which is short for end line which you may have guessed ends the line so no more text is written to that line, you write << endl so you don’t have to clutter up your string with \n which does the same thing.
The next line is placed directly below your cout statement:

Code:
cin.ignore();

This after the string is outputted to the screen waits for the user to press a key then shuts down the application. In other tutorials you may have seen system(“PAUSE”); which does the same as cin.ignore(); but says: Press any key to continue..., system calls are not a good thing to use. Also the cin.ignore(); doesn’t present you with a message which makes a nicer cleaner program.
The final line of code we use in this main() section is:

Code:
return 0;

This line ends the main() function, returning a value of 0 means that there was no expected errors.
After the return 0; line add the finally piece of code:

Code:
}

This tells the compiler that the main() section of code is finished.

Here is the complete source code:

Code:
#include <iostream>
using namespace std;
int main(){
    cout << "Hello World!" << endl;
    cin.ignore();
    return 0;
}
So if you copy/rewrite that into your C++ IDE then press compile and run or debug it will compile your code and turn it into an executable.

So now that we have created our first program that uses the output section of iostream include, let’s get some user input and display a message using the user input. So using our code from above place the following line after int main(){ and before cout << ... :

Code:
int age;
As mentioned before the int is a data type and stores a 32 bit value. Next there is the word age which is a variable name we are going to be using for when we retrieve and use user input (make sure you end the statement with a semicolon).
So now let’s use our age variable to retrieve an age from the user, first change the cout << string to a question the user can answer for the purpose of this tutorial the string will be “How old are you?”:

Code:
cout << "How Old Are You?" << endl;

This is the changed cout << statement.
So let’s get the users input after your cout << statement add this line of code:

Code:
cin >> age;

This line of code makes use of the iostream include and because we are using the standard library namespace we can just write cin. The cin parts asks the user to define what they should define age as e.g. (33). Like the cout statement you need the insertion operator, however for getting user input you use greater than signs rather than less than. After the insertion operator you say what variable you want the user to define and then end with a semicolon.
Add the following line under your cin line:

Code:
cout << "You Are " << age << " Years old!" << endl;

This uses the cout function and the insertion operator as used by our previous cout statement and also a string. However, unlike before you have the variable name surrounded by insertion operators then another string. The insertion operators basically take the value of age and place in the output, note: the insertion wrapped variable must be followed by two “” or a string e.g. in this case we used a string. The cout ends with the << endl; like before. The cin.ignore(); will not work here as it will end the program prematurely and having nothing will do the same so instead replace

Code:
cin.ignore(); with system(“PAUSE”);

If you know compile and run or debug this program it will ask for the users age, then allow the user to input an age then say how old they are.
Full source code listing:

Code:
#include <iostream>
using namespace std;
int main(){
    int age;
    cout << "How Old Are You?" << endl;
    cin >> age;
    cout << "You Are " << age << " Years old!" << endl;
    system("PAUSE");  
    return 0;
}

I hoped this help people in understanding the basics of a C++ program, more lessons on C++ coming soon.
Good TuT kiddo, keep it up.
Reply
#9
Wow, why quote all of that?
[Image: sig.php]
The little boat gently drifted across the pond exactly the way a bowling ball wouldn't.
Reply
#10
I think MrD. owned you Code King baby Smile

Great guide as always mate, I would read MrD's comment though it looks like he knows what hes talking about.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Learn C++ (The Correct Way) - Lesson 2 Code King 12 3,837 04-07-2012, 06:05 PM
Last Post: AceInfinity
  At What Age Did You Learn C++ Win 66 20,672 12-11-2011, 02:52 PM
Last Post: Neel

Forum Jump:


Users browsing this thread: 13 Guest(s)