| | |||||
| ||||||||
| CODE This forum is for posting code snippets and example scripts that aren't quite tutorials, but could be useful for others. You may post code snippets and/or completed scripts that you've written and want to share here. |
![]() |
| | LinkBack | Thread Tools |
| | THREAD STARTER #1 (permalink) |
| Senior Member Join Date: Apr 2005 Location: Joliet, Illinois
Posts: 1,177
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() | [TUTORIAL] C++ - The Basics Hey everyone, Another one of those tutorials I've been requested to write 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++? 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 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.
} ????: NamePros.com http://www.namepros.com/code/510198-tutorial-c-the-basics.html 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.
}
} ????: NamePros.com http://www.namepros.com/showthread.php?t=510198 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! |
| | |
| | THREAD STARTER #2 (permalink) |
| Senior Member Join Date: Apr 2005 Location: Joliet, Illinois
Posts: 1,177
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() | 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
} 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();
} 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++ . 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 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:????: NamePros.com http://www.namepros.com/showthread.php?t=510198 Code: g++ main.cpp -o Program_Name > err.txt ![]() 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 Code: alias ming++="/usr/bin/i586-mingw32msvc-g++" Now, you would run it exactly like you would for normal g++: Code: ming++ main.cpp -o Program_Name.exe ????: NamePros.com http://www.namepros.com/showthread.php?t=510198 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 |
| | |
| | #3 (permalink) |
| Senior Member Join Date: Jul 2005 Location: NJ
Posts: 1,219
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() | 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
__________________ Hacksar.com - Your source for random computer tips and tricks! MySiteMemberships.com - Keep track of your site registration information! Like my post? Rep is appreciated! |
| | |
| | #6 (permalink) | ||||
| Senior Member Join Date: May 2005 Location: Bay Area
Posts: 1,538
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
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; | ||||
| | |
| | THREAD STARTER #8 (permalink) |
| Senior Member Join Date: Apr 2005 Location: Joliet, Illinois
Posts: 1,177
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() | 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 Why not start the right way? lol-RageD |
| | |
| | THREAD STARTER #10 (permalink) |
| Senior Member Join Date: Apr 2005 Location: Joliet, Illinois
Posts: 1,177
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() | 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 otherwise I'd be recreating what's already out there lol. I'll keep working on it in my spare time ![]() -RageD |
| | |
| | #11 (permalink) | ||||
| NamePros Expert Join Date: Nov 2003 Location: Scotland
Posts: 5,069
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
????: NamePros.com http://www.namepros.com/showthread.php?t=510198 In c++ you do the memory management yourself.
__________________ Manage your portfolio using my new Domain Portfolio Management script. Securing Your Domain Name From Theft | ||||
| | |
| | #12 (permalink) | ||||
| DNOA Member Join Date: May 2004
Posts: 5,040
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
| ||||
| | |