You are on page 1of 6

The C++ tutorial is suitable for anyone even if you haven't programmed before bu

t you must have access to a computer and be able to do the following before you
start the tutorial.
* Create and edit text files.
* Download and Install a compiler, from the links provided.
* Run the chosen compiler (see list below) and compile and link files from t
he tutorial instructions.

*********
Starting with C++ classes
Objects are the biggest difference between C++ and C. One of the earliest names
for C++ was C with Classes.
Classes and Objects
A class is a definition of an object. It's a type just like int. A class resembl
es a struct with just one difference : all struct members are public by default.
All classes members are private.
Remember : A class is a type, and an object of this class is just a variable.
Before we can use an object, it must be created. The simplest definition of a cl
ass is
class name { // members }
This example class below models a simple book. Using OOP lets you abstract the p
roblem and think about it and not just arbitrary variables.
// example one #include <iostream> #include <stdio.h> class Book { int PageCoun
t; int CurrentPage; public: Book( int Numpages) ; // Constructor ~Book(){} ; //
Destructor void SetPage( int PageNumber) ; int GetCurrentPage( void ) ; }; Book:
:Book( int NumPages) { PageCount = NumPages; } void Book::SetPage( int PageNumbe
r) { CurrentPage=PageNumber; } int Book::GetCurrentPage( void ) { return Current
Page; } int main() { Book ABook(128) ; ABook.SetPage( 56 ) ; std::cout << "Curre
nt Page " << ABook.GetCurrentPage() << std::endl; return 0; }
All the code from class book down to the int Book::GetCurrentPage(void) { functi
on is part of the class. The main() function is there to make this a runnable ap
plication.
On the next page : Understanding the example.

************
Understanding the Book Class
In the main() function a variable ABook of type Book is created with the value 1
28. As soon as execution reaches this point, the object ABook is constructed. On
the next line the method ABook.SetPage() is called and the value 56 assigned to
the object variable ABook.CurrentPage. Then cout outputs this value by calling
the Abook.GetCurrentPage() method.
When execution reaches the return 0; the ABook object is no longer needed by the
application. The compiler generates a call to the destructor.
Declaring Classes
Everything between Class Book and the } is the class declaration. This class has
two private members, both of type int. These are private because the default ac
cess to class members is private.
The public: directive tells the compiler that access from here on is public. Wit
hout this, it would still be private and prevent the three lines in the main() f
unction from accessing Abook members. Try commenting the public: line out and re
compiling to see the ensuing compile errors.
This line below declares a Constructor. This is the function called when the obj
ect is first created.
Book( int Numpages) ; // Constructor
It is called from the line
Book ABook(128) ;
This creates an object called ABook of type Book and calls the Book() function w
ith the parameter 128.
Note : On the next page : Learn about Constructors.

****************
In C++, the constructor always has the same name as the class. The constructor i
s called when the object is created and is where you should put your code to ini
tialize the object.
In Book The next line after the constructor the destructor. This has the same na
me as the constructor but with a ~ (tilde) in front of it. During the destructio
n of an object, the destructor is called to tidy up the object, and ensure that
resources such as memory and file handles used by the object are released.
Remember : A class xyz has a constructor function xyz() and destructor function
~xyz(). Even if you don't declare then the compiler will silently add them.
The destructor is always called when the object is terminated. In this example t
he object is implicitly destroyed when it goes out of scope. To see this, modify
the destructor declaration to this.
~Book(){ std::cout << "Destructor called\n";} ; // Destructor
This is an inline function with code in the declaration. Another way to inline i
s adding the word inline.
inline ~Book() ; // Destructor
and add the destructor as a function like this.
inline Book::~Book ( void ) { std::cout << "Destructor called\n"; }
Inline functions are hints to the compiler to generate more efficient code. They
should only be used for small functions, but if used in appropriate places such
as inside loops can make a considerable difference in performance.
On the next page : Learn more about class methods

*************
Learn about Writing Class Methods
Best practice for objects is to make all data private and access it through func
tions known as accessor functions. SetPage() and GetCurrentPage() are the two fu
nctions used to access the object variable CurrentPage.
Change the class declaration to struct and recompile. It still compiles and runs
correctly. Now the two variables PageCount and CurrentPage are publicly accessi
ble. Add this line after the Book ABook(128) ; and it will compile.
ABook.PageCount =9;
If you change struct back to class and recompile, that new line will no longer c
ompile as PageCount is now private again.
The :: Notation
After the body of Book Class declaration there are the four definitions of the m
ember functions. Each is defined with the Book:: prefix to identify it as belong
ing to that class. :: is called the scope identifier. It identifies the function
as being part of the class. This is obvious in the class declaration but not ou
tside it.
If you have declared a member function in a class you must provide the body of t
he function in this way. If you wanted the Book class to be used by other files
then you might move the declaration of book into a separate header file perhaps
called book.h. Any other file could then include it with
#include "book.h"
On the next page : Learn about Inheritance

****************
Learn about Inheritance and Polymorphism
This example will demonstrate inheritance. This is a two class application with
one class derived from another.
#include <iostream> #include <stdio.h> class Point { int x,y; public: Point(int
atx,int aty ) ; // Constructor inline virtual ~Point() ; // Destructor virtual
void Draw() ; }; class Circle : public Point { int radius; public: Circle(i
nt atx,int aty,int theRadius) ; inline virtual ~Circle() ; virtual
void Draw() ; }; Point ::Point(int atx,int aty) { x = atx; y = aty;
} inline Point::~Point ( void ) { std::cout << "Point Destructor called\n"
; } void Point::Draw( void ) { std::cout << "Point::Draw point at " << x << " "
<< y << std::endl; } Circle::Circle(int atx,int aty,int theRadius) : Point(atx,
aty) { radius = theRadius; } inline Circle::~Circle() { std::cout << "Ci
rcle Destructor called" << std::endl; } void Circle::Draw( void ) { Point::D
raw() ; std::cout << "circle::Draw point " << " Radius "<< radius << std::endl;
} int main() { Circle ACircle(10,10,5) ; ACircle.Draw() ; return 0
; }
The example has two classes Point and Circle, modelling a point and a circle. A
Point has x and y coordinates. The Circle class is derived from the Point class
and adds a radius. Both classes include a Draw() member function. To keep this e
xample short the output is just text.
On the next page - Learn how Inheritance works.

****************
Learn about Inheritance
The class Circle is derived from the Point class. This is done in this line:
class Circle : Point {
Because it is derived from a base class (Point), Circle inherits all the class m
embers.
Point(int atx,int aty ) ; // Constructor inline virtual ~Point() ; // Destructo
r virtual void Draw() ;
Circle(int atx,int aty,int theRadius) ; inline virtual ~Circle() ; virtual void
Draw() ;
Think of the Circle class as the Point class with an extra member (radius). It i
nherits the base class Member functions and private variables x and y.
It cannot assign or use these except implicitly because they are private, so it
has to do it through the Circle constructor's Initialiazer list. This is somethi
ng you should accept for now, I'll come back to initializer lists in a future tu
torial.
In the Circle Constructor, before theRadius is assigned to radius, the Point par
t of Circle is constructed through a call to Point's constructor in the initiali
zer list. This list is everything between the : and the { below.
Circle::Circle(int atx,int aty,int theRadius) : Point(atx,aty)
Incidentally, constructor type initialization can be used for all built-in types
.
int a1(10) ; int a2=10 ;
Both do the same.
On the next page : What is Polymorphism?

************************
What is Polymorphism?
Polymorphism is a generic term that means 'many shapes'. In C++ the simplest for
m of Polymorphism is overloading of functions, for instance several functions ca
lled SortArray( arraytype ) where sortarray might be an array of ints, or double
s.
We're only interested here though in the OOP form of polymorphism. This is done
by making a function (e.g. Draw() ) virtual in the base class Point and then ove
rriding it in the derived class Circle.
Although the function Draw() is virtual in the derived class Circle, this isn't
actually needed- it's a reminder to me that this it is virtual. If the function
in a derived class matches a virtual function in the base class on name and para
meter types, it is automatically virtual.
Drawing a point and drawing a circle are too very different operations with only
the coordinates of the point and circle in common. So it's important that the c
orrect Draw() is called. How the compiler manages to generate code that gets the
right virtual function will be covered in a future tutorial.
On the next page : Learn about Constructors.

***************
Learn about C++ Constructors
Constructors
A constructor is a function that initilizes the members of an object. A construc
tor only knows how to build an object of its own class.
Constructors aren't automatically inherited between base and derived classes. If
you don't supply one in the derived class, a default will be provided but this
may not do what you want.
If no constructor is supplied then a default one is created by the compiler with
out any parameters. There must always be a constructor, even if it is the defaul
t and empty. If you supply a constructor with parameters then a default will NOT
be created.
Some points about constructors
* Constructors are just functions with the same name as the class.
* Constructors are intended to initialize the members of the class when an i
nstance of that class is created.
* Constructors are not called directly (except through initializer lists)
* Constructors are never virtual.
* Multiple constructors for the same class can be defined. They must have di
fferent parameters to distinguish them.
There is a lot more to learn about constructors, for instance default constructo
rs, assignment and copy constructors and these will be discussed in the next les
son.
On the next page : Don't forget destructors!

************
Tidying Up - C++ Destructors
A destructor is a class member function that has the same name as the constructo
r (and the class ) but with a ~ (tilde) in front.
~Circle() ;
When an object goes out of scope or more rarely is explicitly destroyed, its des
tructor is called. For instance if the object has dynamic variables, such as poi
nters then those need to be freed and the destructor is the appropriate place.
Unlike constructors, destructors can and should be made virtual if you have deri
ved classes. In the Point and Circle classes example the destructor is not neede
d as there is no clean up work to be done, it just serves as an example. Had the
re been dynamic member variables (e.g. pointer) then those would have required f
reeing to prevent memory leaks.
Also when the derived class adds members that require tidying up, virtual destru
ctors are needed. When virtual, the most derived classe destructor is called fir
st, then its immediate ancestor's destructor is called, and so on up to the base
class.
In our example,
~Circle() ; then ~Point() ;
The base classes destructor is called last.
This completes this lesson. In the next lesson, learn about default constructors
, copy constructors and assignment.

You might also like