ATTENTION, THIS LESSON GOT SPLIT,
THERES NO NEED TO READ THIS ANYMORE!!!
instead refer the following:
C++ Lesson2: Introduction
C++ Lesson3: Classes
==============================================================================
Previous: C++ Lesson1: Preparations
Follower: --
First, don't be shocked by the long post, like previous lesson it's actually far easier than it does look like.
However this time you've much more room to experiment.
As always I'm around for help and questiones.
In last lesson I showed how to set up MinGW GCC with Code::Blocks as a development environment. We also did build a simple "Hello World" program to proof the installation works.
This lesson you're going to build your first own program and get in touch with some C++ basics.
Normally you'd first read through a whole book of what the languague has to offer, but I'll skip that, we don't need all the details. That I'll leave for next lesson.
As by of now all of us (should) have a working environment to test, I hope to have some more discussion.
=======================================
code structure
In C++ the code is organized into header and source files. While header files commonly just declare that something exists and are included by source files or other header files, the source files are used to define what actually exists. The compiler just builds what's in the source files and copies header files in by include statements.
It becomes important to follow this rule once you start to split your code to multiple files. While definitions only are allowed to be done once in the whole project, declaring them is allowed once per source file as the compiler resets declarations every source file it does compile.
To not declare things multiple times by recursive includes in same source file, guards are used.
All that will become more clear in the samples.
You probably already noticed all the different colors the code is represented in by your Editor.
That makes the code much more readable and you'll soon find a grasp on.
Let me build on last "Hello World" example.
Lines beginning with a # symbol are pre-processor directives, so called "macros". They get evaluated before the compiler is invoked when you build an application. In this sample there's only one single include to link in a different file named "iostream". You could copy the whole content of that file and gain the same.#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
return 0;
}
iostream is part of the std library and defines cout and endl as well as the << operation on it.
to avoid naming conflicts it encapsulates all defined variables, functions and classes in a namespace. As Lathon told last lesson, "using namespace std;" tells the compiler to get all of those out of their namespace and access direct so you've less to type. Still they are accessible by their namespace, so if you have your own cout defined you could print std::cout to access the one defined by iostream.
In this sample there's just a single function named 'main'. main is a special function that is called by the os when you start the program. In Windows gui applications it looks a bit different, but for console applications and linux coding "int main()" is standard. In Java you define a main function as part of a class body, here in C and C++ it's always a standalone function.
In the end of that function you return 0 to the calling function, in this case to tell the os that no errors occured. The return is of type int which is an integer.
One important thing about C++ is you're not forced to program in C++ but also can use plain old C or with 'inline assembler' instructions you can even code assembler. Also with macro- and template-programming you have a huge range of abilities, not to talk of the std library and others.
Mixing C++ and C however leads to a bad programming style. Furthermore some old C calls like file access are scoffed and often called deprecate in C++ development for security issues.
We'll go right ahead with C++ development and so have to talk on classes.
Classes is the main development concept of C++. It's the key for object oriented programming with C++.
A class is what defines an object. Have a look around you, all of what you can see are objects. They are instances of classes with multiple methods (=function inside a class) to operate on. Maybe you find a pencil or if not use your mouse. Now take your hand and call a function to operate on that pencil or mouse object. That's the way of thinking with object oriented programming.
Even the hair on your nose is an object - each of it. Maybe down to the atoms or further if you want.
It's been invented to portion your code and gives much better maintainability than with poor C code.
Think I've talked enough of code structure for now, let's go on with some practice.
=======================================
practice with C++ classes
Start with previous "Hello World" example.
Now create a new class using File->New->Class in Code::Blocks.
It gives you a prompt, enter a name for your class, leave the rest as is and press "create".
Choose to add it to the current project, both Debug and Release.
What you get is two new files, one header and one source file.
The Debug mode btw is a bit slower than the release one but more safe and includes symbols for the debugger so when you debug your code in code::blocks you can execute line by line to see what happens.
If you try to compile right now, it might fail with telling that it couldn't find your header file.
That might be only with me as I might have changed some settings by the time, but if so it is cause we didn't tell where to look for your header files yet.
Go to Project->Build options. On the left choose your project name to change for both Debug and Release.
Open Search directories tab, compiler sub-tab should be selected. Add your project's include folder, the folder in where your header file is. To not make your project path dependent, just use the relative path to where your project is located. So if your project is in C:\folder\folder\folder\folder\folder\folder\myproject and your includes lay in myproject\include just add include
In the header file, first there's a guard using define macros to not declare things multiple times.
The class declaration is devided into three sectiones: public, protected and private. For now only public does interest as the others do prevent accessing the class methods from outside.
Two methods you see declared. Other than our "int main()" function there is no return type specified. The virtual key word is used for polymorphism but that we talk on another lesson, for now you can remove it. As a Java developer just know that in Java methods always are virtual so there is no such specifier.
That here no return type is specified is cause these are special ones. First one is the class constructor always called on object creation and second one is the destructor called when the object stops to exist. Both always equal the class name, the destructor just has a preceding ~
declarations end with a ; just like any code expression.
In the cpp source file you find the according definitions to both of them. As you can see the name of the class occures twice. First one to access class scope using a double colon ::, second for the method name.
What I want you to do now is create another method, declare in header, define in the cpp. Don't forget the return type like it's been with main.
In that print something to the console again. don't forget to add the iostream header to your source file so you can make use of cout.
Now in main.cpp, include your class header, create an instance of your class by typing your_class_name myClassInstanceName;
afterwards call your new method by myClassInstanceName.myMethod();
Test to get that work.
=======================================
build your own application
Here comes the fun part.
Open your main.cpp, we'll add a while loop that does not halt before key input.
In that loop you call your class to let it perform some action, do some crazy calculations, whatever.
Remove following portion of your main:
Code: Select all
cout << "Hello world!" << endl;
system("PAUSE");
Code: Select all
string input = "";
while(input.compare("exit") != 0)
{
cout << "post some stuff" << endl;
getline(cin, input);
}
Now inside your class header, add a member variable to the public section. e.g. use an integer, simply declare it as int myint;
In your constructor, assign zero to your int so it's sure to be zero also in release mode: myint = 0;
In your method do some calculation with your integer. Use add + substract - multiplicate * or devide /.
You'll find more on the web if you want. One very good reference I've already posted is http://www.cplusplus.com -> http://www.cplusplus.com/doc/tutorial/operators/
Print your result to the console simply by cout << myint; no need to start another line.
One last very useful construct to your program are the if and else clauses.
Code: Select all
if(myint < 77){ myint = myint + 3; }
else{ myint -= 10; }
Code: Select all
if(input.compare("BotF") > 0){
cout << "nothing is greater than BotF, type something else!" << endl;
}