Previous: C++ Lesson2: Introduction
Follower: --
Last lesson we went through some basics, modified the "Hello World" sample program and implemented an own first application.
This lesson we'll talk on basics of object oriented programming to get you compfortable with it right from the start.
=======================================
concepts and code structure
First some talk on concepts and code structure again.
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 featuring preprocessor macros.
All that will become more clear while we progress.
Just remember, different to many other languages, in C++ you're coding in the .cpp 'source' files and declaring seperately in the .h 'header' files
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 what's used for OOP in C++, it's main development concept.
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.
=======================================
basics of C++ classes
Start with main.cpp from last lesson containing the following:
Code: Select all
#include <iostream>
using namespace std;
int main()
{
string input;
while(input.compare("exit") != 0)
{
cout << "post some stuff" << endl;
getline(cin, input);
}
return 0;
}
It gives you a prompt. Enter a name for your class, e.g. "lesson3", 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.
Try to compile.
If it fails telling that it couldn't find your header file, it is cause we didn't tell where to look for your header files yet.
To solve, 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 type include
Make sure you get that work!
In the header file, on top there there you see a guard using define macros to not declare things multiple times.
The class declaration is devided into three sections: 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. That's also the case for the whole class declaration so other than a namespace which is no declaration, it ends with a semicolon!
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. Then inside the main function, create an instances of your class by typing your_class_name myClassInstanceName;
afterwards call your new methods by typing
myClassInstanceName.myMethod();
Here's what I put together:
main.cpp:
Code: Select all
#include <iostream>
#include "lesson3.h"
using namespace std;
int main()
{
string input;
lesson3 myInst;
while(input.compare("exit") != 0)
{
myInst.turn();
cout << "post some stuff" << endl;
getline(cin, input);
}
return 0;
}
Code: Select all
#ifndef LESSON3_H
#define LESSON3_H
class lesson3
{
public:
lesson3();
virtual ~lesson3();
int turn();
protected:
private:
};
#endif // LESSON3_H
Code: Select all
#include "lesson3.h"
#include <iostream>
using namespace std;
lesson3::lesson3()
{
//ctor
}
lesson3::~lesson3()
{
//dtor
}
int lesson3::turn()
{
cout << "my turn" << endl;
return 0;
}
What classes come useful for is when creating multiple inctances and giving each a different state.
Therefore we need so called "member variables".
Member variables can also be seen as attributes of a class making it a logical unit.
Watch and try following code for it featuring while(true) again:
main.cpp:
Code: Select all
#include <iostream>
#include <cstdlib>
#include "lesson3.h"
using namespace std;
int main()
{
string input;
lesson3 myInst1;
lesson3 myInst2;
while(true)
{
cout << "post some stuff" << endl;
getline(cin, input);
if(input.compare("n") <= 0){
if(myInst1.turn()){
cout << "myInst1 won! exit" << endl;
break;
}
}
else if(myInst2.turn()){
cout << "myInst2 won! exit" << endl;
break;
}
}
system("PAUSE");
return 0;
}
Code: Select all
#ifndef LESSON3_H
#define LESSON3_H
class lesson3
{
public:
lesson3();
virtual ~lesson3();
int turn();
protected:
private:
// here define your member variables
// for better encapsulation put them in private section
// so they can't be accessed from outside the class
int myPrivateState;
};
#endif // LESSON3_H
Code: Select all
#include "lesson3.h"
#include <iostream>
using namespace std;
lesson3::lesson3()
{
//ctor initialize member variables on creation
// else they might contain anything
myPrivateState = 0;
}
lesson3::~lesson3()
{
//dtor
}
int lesson3::turn()
{
// increment myPrivateState, use ++ preceding it
// to increment before comparison
if(++myPrivateState > 10) return 1;
else return 0;
}
now practice with classes!
This is the fun part again.
Make some more use of above class concept than me, extend your previous application if you want.
Have fun and don't forget to share results and leave some feedback!
Only on good participation I will continue!
If you find errors, try fix and report, I didn't try compile yet.