IT.COM

[TUTORIAL] C++ - The Basics

Spaceship Spaceship
Watch
Hey everyone,

Another one of those tutorials I've been requested to write :P I'll start of with the basics and actually will be moving to intermediate throughout the tutorial.

What you'll learn in this tutorial:
  • What is C++
  • What is cross-compatibility
  • What is OOP and how to use it
  • The basic syntax of a C++ program
  • How to compile code into programs!

What is C++?
Alright, let's begin with a very beginning knowledge. If you want more than this, check out wikiepedia or something :-P All you really need to know is it came from the antiquiated C programming. It is a computer programming languages and is the most flexible out of all of them! (Others include: C, C#, ASP, Perl, the list goes on...)

What is cross-compatibility?
For those of you haven't found out yet, Windows isn't the only operating system ("ahhhh", from the man reading this who jumps out his window in terror of his world being flipped upside down) I know, it may be hard for those of you who have only known windows your entire life to accept this, but you will in time :) So, that being said, different operating systems work differently. Windows works differently than Linux, etc. That's why to keep it simple we're not going to be coding any GUI's but simply console/terminal programs that will be working both on windows and *nix. However, I won't be teaching how to cross-compile as it is a somewhat advanced system management things. Takes a lot of configuring/rebuilding depending on what you're coding for. I'll dabble slightly on an easy way to do it on Debian systems to Windows but the other stuff will take a lot of explanation. I will probably create a separate tutorial later on doing that.

What is OOP?
OOP is an acronym. It stands for ObjectOrientedProgramming. This basically deals with classes, pointers, etc. which will be explained more in depth when we get to them :D If you already know a web language like PHP this concept should not be totally new as PHP does it pretty much exactly the same!


Ok, now it's really hard to start one of these basic tutorials for C++. There is SO much there is really no good place to start. I guess I'll write the infamous "Hello World" script and explain through and through.

hello.cpp
Code:
/**
 * Hello World Script by RageD :)
 *
 * This is a comment by the way
 * it can also be done by putting "//" in front of a single line without
 * a line break. No quotes of course.
 *
 */

// Here is the second way to comment :) But it ends when hitting return
#include <iostream> // Using the IOStream include. Later we'll be using the cstdio as it's preferrable imo

using namespace std; // Declare the namespace. This way we can access the "std" library for C++ giving us certain functionality

int main() // Definition of main function - This is where all C++ programs begin
{
	cout<< "Hello World" << endl << endl << "This is a C++ Program!" << endl;
	return 0; // Because this is an "int" (for integer) return a number value to the function. 0 exits.
}

Let's begin. With comments, you can put anything in them and the compilers skip over them so you don't get any errors for having them in there.

Next on the list, the #include. This will include other files. For the standard C++ libs google but it can also be used to include your own files you've created.

As far as the namespace goes, this is all basically explained in the comment I put in.

int main() - Take note of the structure. int stands for integer. So this is a numerical output as opposed to something like bool which stands for boolean which returns a true/false value. There are others as well but we can talk about them later. This is in the main function the program will execute at startup.

cout - Seeing as we're using the "iostream" lib this is the command we use. The two less than signs make the "cout" print whatever comes after. We'll learn later with inputs that the reverse is true for a different operation. Anything within quotes is plain text. When ending quotes, the << is put in between each new item. In particular there is "<< endl << endl" endl stands for "End line". Simply creates a line break. Then, followed by more quoted text and one more endl. Be sure to end every line with a semi-colon [;].

return 0 - remember earlier I said it was necessary to return a numerical value to int, where this is where it comes into play because the function is int.

new line at the end of code. This is essential to have a new line at the end of your code or your code WON'T compile :(


Next, we'll be moving on to user inputs. Examine the code below carefully.

Code:
/**
 * Simple User Input by RageD
 * (C) RageD 2008.
 *
 * In this tutorial it is assumed you recall previously
 * covered material and all tutorials fromt here on forth
 * in this segment.
 *
 */

#include <iostream>
#include <string> // Allow us to declare things as "strings"

using namespace std;

int main()
{
	string name; // Declare variable as a "string" that comes from the #include <string> header file
		     // In all honest, you'll probably never use the "string" variable as it's eh. Not
		     // Very good programming really. But we'll go over that later this is just to start
		     // Grasping the concept of programming. Secure/efficient programming comes after this :P
	cout<< "To exit, please type 'exit' for your name.\n\nPlease enter your name: ";
	cin>> name; // This is the user input. The >> means to set the "name" variable to it
	if(name != "exit") // If is a conditional statement. It is explained below in the tutorial
	{
		cout<< "Nice, your name is " << name << endl << endl << "I like it..." << endl << endl;
		// Adding the name variable to be output is very similar to the endl as you can see :)
		return main();
	} else {
		return 0; // Loop to the main function over and over until "exit" is typed.
	}
}

Baically using strings here. Comments should say the most of it.

This is becoming very lengthy so I'm going to wrap it up with 2 or 3 more examples for you guys.


Post is too long so it must be posted across a few, continue on!
 

Attachments

  • CPP_Basics-Tutorial.zip
    864.6 KB · Views: 63
2
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
The next one is going to be dealing with classes and pointers!

main.cpp
Code:
/** 
 * Classes example script by RageD
 * (C) 2008 RageD.
 *
 */

#include "class.cpp" // This is our own header file!
#include <iostream>

using namespace std;

int main()
{
	Main * Main; // Define Main to go to the Main class
	Main->loop(); // This is a pointer. Make this go right to
		     // the loop(); function within the Main class
}

Very simple main.cpp. But how can this program actually do anything you ask? Well continue on. Main * Main is the definition for the class. Because Main is defined as the Main class, you can use the pointer (->) to go to the function "loop" inside the Main class :) Make sense? It will when you execute the application.

class.cpp
Code:
/**
 * Example class script by RageD
 * (C) 2008 RageD.
 *
 */

#include <iostream>

using namespace std;

/**
 * Create the class structure here
 *
 * Not too difficult and pretty self explanatory but take a look anyway :) 
 *
 */

class Main
{
public:
  int loop();
  int a();
  int b();
  int c();
private:
  bool w00t(); // Not coded in example :P
}; // Yes, semi-colon is supposed to be here in this one. Even with the "}"

/**
 * Now let's make the structure useful :P
 *
 */

int Main::loop()
{
	char opt; // Define opt as "char"
	cout<< "Welome to the main menu!\n\nPlease select one of the following options:"<< endl << endl << "a\nb\nc\n\nx to exit" << endl << endl << "Your option: ";
	cin>> opt;
	switch(opt)
	{
		case 'a':
			return Main::a();
		break;
		case 'b':
			return Main::b();
		break;
		case 'c':
			return Main::c();
		break;
		case 'x':
			cout<< "Exiting...\n\n";
			return 0;
		break;
		default:
			cout<< "Your option '"<< opt <<"' is not a valid option!" << endl;
			return Main::loop();
		break;
	}
}

int Main::a()
{
	cout<< "Great, you selected option A!\n\nPlease hit return to continue..." << endl << endl;
	Main::loop();
}

int Main::b()
{
	cout<< "Sweet, you picked option B!\n\nPlease hit return to continue..." << endl << endl;
	Main::loop();
}

int Main::c()
{
	cout<< "Erm.. Why C? C++ FTW! :D\n\nPlease hit return to continue..." << endl << endl;
	Main::loop();
}

This class file is where all the work is done. The functions, etc. are all coded here.

Well let's begin with our declarations. We've declared our variable "opt" as a char so it can be read as such. We could declare as int but because it is not an integer, it would crash the program, so it is important to declare variables according to type.

Next, the switch(). This is very similar to doing just if(this) { return that }. But since it's the same variable just with a different option using the case 'OPTION': stuff here break; is a better way to go really. If there's any confusion on that let me know but the syntax is all right there.

int Main::a(), etc. These are the actual functions. Remember, because everything is directly declared here you can use the Class::FUNCTION(); to call these as refrences. However, in other documents such as main you must declare something to the Main class then use pointers (->) to call the PUBLIC function. It is important that the function be public.


Compiling C++ Programs!

Windows
Now that you have all this code, I'm sure you're wondering how the hell you compile it into a program. Well, it's pretty simple depending on your operating system. If you're using Windows, I suggest downloading the free MS Visual C++ compiler. Sure it's Microsoft, but hey, it's free and it's (believe it or not) the best compiler you'll find for Windows if you're looking for a built-in GUI. Other than that, GCC (what will be used for linux) is truly the best way to compile. For Windows you will need to download MSYS and MingW which is the Windows port of GCC. For help with command line options, read on.

Linux
Ah, yes. The best place to really compile :). Well, all you'll need is GCC. However, we won't be using the gcc command as that is a C compiler. We will be using G++ :D. There are no Makefile's so we're going to be using the raw commands to get this to work!

This example is assuming that your main file is main.cpp. If there are any errors, the compilation will not complete but it will spit out an error.
Code:
g++ main.cpp -o Program_Name

As long as everything is properly linked (via #include, etc.) within the files, everything should be ok if programmed properly :D If there error log is too lengthy to read without scrolling, etc. (which often happens as you develop larger programs) try something like the following command to output the errors to a separate text file you can read at your own pace:
Code:
g++ main.cpp -o Program_Name > err.txt

And last, but certainly not least, I mentioned I'd possibly dabble into cross-compiling for Debian based systems as it's a little simpler to setup :P

Well you're going to want to run the following command. For Ubuntu/Gentoo or systems like that you may need to "sudo" in front of the command. On standard Debian you must be logged into root or at least "su" to it.
Code:
apt-get install mingw32

Once that is installed, edit your ".bash_profile" file. Add the following line:
Code:
alias ming++="/usr/bin/i586-mingw32msvc-g++"

That will make ming++ your command to cross compile for Windows!

Now, you would run it exactly like you would for normal g++:
Code:
ming++ main.cpp -o Program_Name.exe

Well I think that will about wrap this one up. If there's anything I've overlooked/wasn't thorough on due to familiarity with the subject, please let me know and I will revise!


I have also included a ZIP file. It has ALL examples listed here as well as 2 or 3 other example scripts you can take a look at explaining how to make your own namespaces, declaring variables as part of a function, etc.!

-RageD
 
0
•••
thanks for the great tutorial, i never really understood the whole pointers thing.

now if only i can understand stupid memory management.

php is so much better =D
 
0
•••
your comparing a scripting language next to a programming language.. PHP is for web development.
 
0
•••
.jd. said:
your comparing a scripting language next to a programming language.. PHP is for web development.

The are both programming languages ;)
 
0
•••
nasaboy007 said:
thanks for the great tutorial, i never really understood the whole pointers thing.

now if only i can understand stupid memory management.

php is so much better =D

Great tutorial RageD! :tu:

In terms of memory management in C++, to allocate dynamic memory on the heap, you use the "new" operator. Since, C++ doesn't have garbage collection, it is your job to free up the memory when it is no longer needed (If you don't, this leads to memory leak).

Here's an example.

Code:
struct foo{
   int blah; 
   foo(){
      blah = 42;
   }
};  

// create pointer to allocated memory
foo * ptrToFoo = new foo();

// prints 42
cout << ptrToFoo->blah;

// free up memory
delete ptrToFoo;
 
0
•••
Great tutorial! I'll be following this thread! ;) Rep added.
 
0
•••
Thanks for all the kind words! :) If there is any sort of thing you'd like to see specifically, let me know and I'd be glad to help! As far as mem leaks and stuff goes, probably should've added into here but didn't want to make things complicated, however, you do make a good point :P Why not start the right way? lol

-RageD
 
0
•••
Nice job! You should make a tutorial on using the win32 API with C++.
 
0
•••
Sure, I don't do a lot of WinAPI programming but can do it. I'll definitely start up a tutorial with more detailed notes than the usual :P otherwise I'd be recreating what's already out there lol. I'll keep working on it in my spare time :)

-RageD
 
0
•••
DecepShaun said:
The are both programming languages ;)

Yes but PHP does it's own memory management (although you can do things to help)

In c++ you do the memory management yourself.
 
0
•••
Peter said:
Yes but PHP does it's own memory management (although you can do things to help)

In c++ you do the memory management yourself.
Not necessarily. You *can* do the memory management yourself. It depends on how low-level you're talking about. It will automatically allocate memory for objects and such, but you can still use C functions (which, technically, confines itself to "C" not "C++", except for the ability to destroy pointers to objects and other unique C++ entities) to manage low-level memory.
 
0
•••
VERY nice, Rage! You really should consider writing, if you do not already, very nicely done friend.
 
0
•••
I need to know more about the file handling codes,can pls explain it briefly through post or through pm.Anyway you prefer but i need it.
 
0
•••
Thats very good of these tutorials ..Basically i need this for my college studies.
 
0
•••
i suck at these tutorials i always need visaul tutorials u should do one rofl well im just saying that cause i really need a vid tutorial for c++ if any one knows of any good ones please do pm me the site or place
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back