C++ Notes
C++ Notes
S6 CSC Page 1
C++ Programming 2016
1.1.1. Overview
All of you know about C already, and this course describes key features in C++ programming,
object oriented programming (OOP). A very brief introduction to C++ syntax, which is different
from C, is described first. We will talk about why we want to use C++ rather than C, then we
will go in more depth about how to use objects in our programs, the syntax on how to describe
classes and objects in C++, and also we will talk about how to declare and use an object in C++.
In C++, if you want to output a variable temp to the screen, you do:
cout << “value of temp is “ << temp << “\n”;
In C++, if you want to read a value into variable temp, you do:
cin >> temp;
In C++, in order to use cin and cout, you have to include the library <iostream.h>.
Other than these, C++ is almost the same as C. So if you already know about C, learning about
C++ is not an extremely challenging task. Making function calls, assignment, return format,
loops, arrays, are all the same as C.
C++ is an advanced version of C. Developed at ATT Bell Labs in 1982 by Bjarne Stroustrup
with precise objective: Add to C the similar classes to those of Simula language. It was thus to
graft the possibilities of Object Oriented Programming (OOP) in a classical language. C++ is
used in numerous fields, such as accounting and finance systems, and computer-aided design
(CAD). Supports object-oriented programming.
The C programming language has been conceived and developed by Dennis Ritchie at Bell
Laboratories in 1972.
In programming they always separated the programs and the data. In object-oriented languages,
the code used to write the program and the data processed by the program are grouped together
into units called objects.
The OOP gathers program and data in reusable units that are called classes. A class contains
procedures (methods, functions or routines) and data (attributes, properties or values).
In object-oriented programming language C++, the data and functions (procedures to manipulate
the data) are bundled together as a self-contained unit called an object.
Classes contain data known as members and member functions. As a unit, the collection of
members and member functions is an object. Therefore, this unit of objects makes up a class.
S6 CSC Page 2
C++ Programming 2016
A class is an extended concept similar to that of structure in C programming language; this class
describes the data properties alone. In C++ programming language, class describes both the
properties (data) and behaviors (functions) of objects. Classes are not objects, but they are used
to instantiate objects.
An instance of a class is created as one would declare a variable. The instance of a class is an
object.
Objects are further grouped into classes, which define the attributes objects must have. A simple
example of a class is the class Book. Objects within this class might be Novel and Short Story.
Objects also have certain functions associated with them, called methods.
The starting brace symbol { is placed at the beginning of the code. Following the flower brace
symbol, the body of the class is defined with the member functions data. Then the class is closed
with a brace symbol } and concluded with a semicolon;.
class class_name
{
data;
member functions;
……………
};
class CRectangle {
int width, height;
public:
S6 CSC Page 3
C++ Programming 2016
void setValues(int,int);
int area () {return (width*height);}
};
int main () {
CRectangle m,u;
m.setValues (3,4);
u.setValues (5,6);
cout << "rect area: " << m.area() << endl;
cout << "rectb area: " << u.area() << endl;
return 0;
}
There are different access specifiers for defining the data and functions present inside a class.
Access specifiers:
Access specifiers are used to identify access rights for the data and member functions of the
class. There are three main types of access specifiers in C++ programming language:
private
public
protected
A private member within a class denotes that only members of the same class have
accessibility. The private member is inaccessible from outside the class.
S6 CSC Page 4
C++ Programming 2016
When defining access specifiers, the programmer must use the keywords: private, public or
protected when needed, followed by a colon and then define the data and member functions
under it.
class AddNumbers
{
private:
int x,y;
public:
void sum()
{
………
………
}
};
In the code above, the member x and y are defined as private access specifiers. The member
function sum is defined as a public access specifier.
class classname
{
access specifier:
data member;
member functions;
access specifier:
data member;
member functions;
};
Generally, in class, all members (data) would be declared as private and the member functions
would be declared as public. Private is the default access level for specifiers. If no access
specifiers are identified for members of a class, the members are defaulted to private access.
class AddNumbers
{
int x,y;
public:
void sum()
{
………
S6 CSC Page 5
C++ Programming 2016
………
}
};
In this example, for members x and y of the class AddNumbers there are no access specifiers
identified. AddNumbers would have the default access specifier as private.
You can have functions inside class. These functions can be either under public or private, and
their syntaxes are the same.
The computer accesses an object through the use of one of the object’s methods. The method
performs some action to the data in the object and returns this value to the computer. Classes of
objects can also be further grouped into hierarchies, in which objects of one class can inherit
methods from another class. The structure provided in object-oriented languages makes them
very useful for complicated programming tasks.
Once the class is created, one or more objects can be created from the class as objects are
instance of the class.
int x;
AddNumbers e1;
class AddNumbers
{
private:
int x,y;
public:
void sum()
{
S6 CSC Page 6
C++ Programming 2016
………
………
}
};
main()
{
AddNumbers e1;
……………
……………
}
The object can also be declared immediately after the class definition. In other words the object
name can also be placed immediately after the closing brace symbol } of the class definition.
For example:
class AddNumbers
{
private:
int x,y;
public:
void sum()
{
………
………
}
}e1 ;
Attention:
Class access
After you have finished implementing your object, you can start using it.
The importance of the use of the classes in the Object Oriented Programming (OOP) is essential;
with the use of the classes you can create objects which represent the objects of the real world,
having thus attributes (name, size) and methods.
S6 CSC Page 7
C++ Programming 2016
We can write the longest programs in few lines without however repeating the definition of the
functions, the function thus should be called once you need to use it by using the objects which
can be created either statically or dynamically. As the OOP preserves a possibility of inheritance,
we can use the classes to inherit some of the properties and methods coming from the other
classes.
The attributes are the variables stored in the class. They must have a label (public, protected,
private) indicating their access.
The methods represent the necessary and possible actions that we can do with the objects of the
class.
We also use the specifiers private, public, protected with the methods.
Example:
class class1 {
data1, data2
public:
fonction1
};
class1::fonction1(param1, param2)
S6 CSC Page 8
C++ Programming 2016
We create an object which we give a name. We will then be able to call an object by calling it by
its name, as it is the same for the variable.
class1 object1;
It is the program which creates the objects according to needs. They have no name: They are
pinpointed (identified accurately/correctly) by the pointer.
Attention:
Any object created dynamically has to be destroyed at the end of its utilization. If not, a
part of the memory will not be freed at the end of the program.
The static objects are destroyed automatically at the end of the program.
We simply use “.” Between the name of the object and the name of the attribute, then we assign
the value.
ObjectA.AttributeA=Value;
S6 CSC Page 9
C++ Programming 2016
The access to attributes is done with the help of the pointer followed by a flesh (“”), then the
name of the attribute:
pointerAattributeA=Value;
C and C++
The major difference between the C and the C++ results from the insertion of the Object
Oriented Programming technology in C.
The OOP from now on is universally recognized for the advantages that it acquires. In particular:
It largely improves the productivity of the developers (facility to write and modify long
programs).
The robustness ( describes a machine program or a system which can recover "to survive
from the unexpected conditions during operation). For example enter a character instead
of entering an integer.
The portability
The facility to create objects in computer science which represent the objects of the real
world
Reutilisability of the functions
The extensibility of their programs.
2.1 Constructor
A constructor is a member function that is automatically called when an object of that class is
declared. Inside a constructor function you will do all the initialization you want on the data
members. For example you can assign the account number, put in the amount of money, etc.
A constructor has the same name as the class in which it is created. It does not return any type
and can have an unspecified number of arguments.
Notice that you are allowed to have more than one constructor. This is called overloading of
functions. Therefore, if you have more than one constructor in your class you can have more than
one method to declare an object of that kind.
S6 CSC Page 10
C++ Programming 2016
A constructor is member function, defined as other functions and is called automatically at each
creation of an object.
Objects generally need to initialize variables or assign dynamic memory during their process of
creation to become operative and to avoid returning unexpected values during their execution.
For example, what would happen if in the previous example we called the member function
area() before having called function set_values()? Probably we would have gotten an
undetermined result since the members x and y would have never been assigned a value.
In order to avoid that, a class can include a special function called constructor, which is
automatically called whenever a new object of this class is created. This constructor function
must have the same name as the class, and cannot have any return type; not even void.
We are going to implement CRectangle including a constructor:
rect area: 12
rectb area: 30
S6 CSC Page 11
C++ Programming 2016
As you can see, the result of this example is identical to the previous one. But now we have
removed the member function set_values(), and have included instead a constructor that
performs a similar action: it initializes the values of width and height with the parameters that are
passed to it.
Notice how these arguments are passed to the constructor at the moment at which the objects of this
class are created:
Constructors cannot be called explicitly as if they were regular member functions. They are only
executed when a new object of that class is created.
You can also see how neither the constructor prototype declaration (within the class) nor the
latter constructor definitions include a return value; not even void.
2.2. Destructor
A destructor is a member function which will be called immediately at the time of the destruction
of the object, it has the same name as the class, its name is preceded by a tilde (~), it does not
return any type of variable and it does not have arguments.
The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime
and at the moment of being destroyed we want to release the memory that the object was allocated.
S6 CSC Page 12
C++ Programming 2016
14
15 height = new int;
16 *width = a;
17 *height = b;
18 }
19
CRectangle::~CRectangle () {
20
delete width;
21
delete height;
22
}
23
24 int main () {
25 CRectangle rect (3,4), rectb (5,6);
26 cout << "rect area: " << rect.area() << endl;
27 cout << "rectb area: " << rectb.area() << endl;
28 return 0;
29 }
30
Output
rect area: 12
rectb area: 30
Like any other function, a constructor can also be overloaded with more than one function that have the
same name but different types or number of parameters. Remember that for overloaded functions the
compiler will call the one whose parameters match the arguments used in the function call. In the case
of constructors, which are automatically called when an object is created, the one executed is the one
that matches the arguments passed on the object declaration:
S6 CSC Page 13
C++ Programming 2016
11 };
12
13 CRectangle::CRectangle () {
14 width = 5;
15 height = 5;
16 }
17
18 CRectangle::CRectangle (int a, int b) {
19 width = a;
20 height = b;
21 }
22
23 int main () {
24 CRectangle rect (3,4);
25 CRectangle rectb;
26 cout << "rect area: " << rect.area() << endl;
27 cout << "rectb area: " << rectb.area() << endl;
28 return 0;
29 }
Output
rect area: 12
rectb area: 25
In this case, rectb was declared without any arguments, so it has been initialized with the
constructor that has no parameters, which initializes both width and height with a value of 5.
Important: Notice how if we declare a new object and we want to use its default constructor
(the one without parameters), we do not include parentheses ():
CHAP 3: INHERITANCE
3.0 Introduction
S6 CSC Page 14
C++ Programming 2016
Programmers seem to hate coding something from scratch; why code the same thing over and
over again? Fortunately, it is possible to reuse code, thanks to one of the key concepts of object-
oriented programming. That is inheritance, which is the subject of this chapter.
a. What is inheritance?
Inheritance is the process by which new classes called derived classes are created from
existing classes called base classes. The derived classes have all the features of the base
class and the programmer can choose to add new features specific to the newly created
derived class.
In Object Oriented Programming, Inheritance is the process by which objects of one class
acquire the properties and functionality of objects of another class. It supports the concept
of hierarchical classification. For example, the bird robin is a part of the class flying bird
which is again a part of the class bird.
Creating or deriving a new class using another class as a base is called inheritance in C++. The
new class created is called a Derived class and the old class used as a base, is called a Base class
in C++ inheritance terminology.
For example, a programmer can create a base class named fruit and define derived classes as
mango, orange, banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all
the features of the base class (fruit) with additional attributes or features specific to these newly
created derived classes. Mango would have its own defined features, orange would have its own
defined features, banana would have its own defined features, etc.
Another example, if we define a class ‘computer’ then it could serve as the base class for
defining other classes such as ‘laptops’, ‘desktops’ etc..
A derived class is defined by indicating its relationship with the base class in addition to its own
details. The General Form of Inheritance:
S6 CSC Page 15
C++ Programming 2016
The two points indicate that derived-class is derived from base-class. The access-specifier is
optional and if it is present can be private or public.
The mode of visibility by default is private. It indicates if the aspects of the base class are
inherited in a private way or publicly.
1. Reusability:
Inheritance helps the code to be reused in many situations. The base class is defined and once it
is compiled, it need not be reworked. Using the concept of inheritance, the programmer can
create as many derived classes from the base class as needed while adding specific features to
each derived class as needed.
The above concept of reusability achieved by inheritance saves the programmer time and effort;
since the main code written can be reused in various situations as needed.
Attention!
S6 CSC Page 16
C++ Programming 2016
For example, if the base class is student and the derived class is peter it is specified as:
The above makes peter have access to both public and protected variables of base class student.
Reminder about public, private and protected access specifiers:
Public members and variables are accessible from outside the class.
If a member functions or variables defined in a class are protected, then they cannot be
accessed from outside the class but can be accessed from the derived class.
3.2.2. Base class
A base class is a class that is created with the intention of deriving other classes from it. It is also
called super/parent/old class.
A child class is a class that was derived from another, that will now be the parent class to it. It is
also called sub/derived/inherited class.
The protected and public variables or members of the base class are all accessible in the derived
class, but a private member variable is not accessible by a derived class.
The derived class inherits some or all the features from the parent class. A class can also inherit
the properties of more than one class or more than one level.
A derived class with only one parent class is called simple inheritance. And that with several
base classes is called multiple inheritance. In addition, the features of a class can be inherited
by more than one class. This process is known as a hierarchical inheritance.
The mechanism to derive a class from another derived class is known as multilevel inheritance.
S6 CSC Page 17
C++ Programming 2016
Declaration Commentary
class john : private person john inherits uniquely from the person class in private.
The role of the inheritance modifier and the access modifier: protected
A protected attribute is not accessible outside the class but is accessible from the derived classes.
This modifier is thus intermediate between private and public. The following table recapitulates
the accesses provided by these three modifiers:
private No No
protected Yes No
S6 CSC Page 18
C++ Programming 2016
Examples
Class B
Private
Protected
Public
Class D1:public B Class D2: private B
Private Private
Protected Protected
Public Public
When a base class is inherited using private inheritance specifier by a derived class, the public
members of the base class become the private members of the derived class. The result is that no
member of the base class is accessible to the objects from the derived class.
In addition, when the base class is publicly inherited, ' the public members of the base class
become ' the public members of the derived class and thus they are accessible to the objects from
the derived class.
In both cases, the private members are not inherited and thus, the private members of a base class
will never become the members of its derived class.
Forms of inheritance
A
A B
A
B C
C B D
A
A
D C D
B B
Let us consider an example: let us assume that the result of an exam of the student is stored in the
3 different classes. Class number stores the registration number, class test stores the points
obtained in the two subjects and finally the class result contains the total of the points obtained in
the exam. The class result can inherit the details, such as the points obtained in the exam and the
registration number of the student through the multilevel heritage.
///////////MULTILEVEL INHERITANCE///////
#include<iostream.h>
class number
{
protected:
int reg_number;
public:
void get_number(int);
void display_number(void);
};
void number::get_number(int a)
{
reg_number =a;
}
void number::display_number(void)
{
cout<<"Registration number="<<reg_number<<"\n";
}
class test:public number
{
protected:
float cpp,vb;
public:
void get_marks(float,float);
void display_marks(void);
};
void test::get_marks(float b,float c)
{
cpp=b;
vb=c;
}
void test::display_marks( )
{
cout<<"The marks in cpp="<<cpp <<"\n";
S6 CSC Page 21
C++ Programming 2016
There could be situations where we must apply two types or more of inheritance to develop a
program. The following example shows how the hybrid inheritance looks like.
char name[25];
int nbr;
public:
void getident(void)
{
cout<<"What is your name?"<<endl;
cin>>name;
cout<<"and your number?"<<endl;
cin>>nbr;
}
void displayident(void)
{
cout<<nbr<<"\t"<<name;
}
};
void displaytheory(void)
{
cout<<"\t\t"<<math<<"\t"<<fr;
}
};
class practice
{
protected:
int maint,prog;
public:
void getpractice(void)
{
cout<<"Enter marks in maintenance and in programming"<<endl;
cin>>maint>>prog;
}
S6 CSC Page 23
C++ Programming 2016
void displaypractice(void)
{
cout<<"\t"<<maint<<"\t"<<prog;
}
};
cout<<"___________________________________________________________"<<endl;
cout<<endl<<"Nbr\tName\t\t\tMath\tFr\tMaint\tProg\tTotal"<<endl;
cout<<"-----------------------------------------------------------"<<endl;
for(a=0;a<29;a++)
{
ob[a].displayident( );
ob[a].displaytheory( );
ob[a].displaypractice( );
ob[a].displayresult( );
}
cout<<endl<<"-----------------------------------------------------";
getch( );
}
identification
S6 CSC Page 24
theory practice
result
C++ Programming 2016
Multiple inheritance is the construction in which objects inherit from more than one object type
or class. This contrasts with single inheritance, where objects can only inherit from one type or
class.
#include<iostream.h>
#include<conio.h>
class A
{
public:
void addition(int a,int b)
{
cout<<"Addition:"<<a+b<<endl;
}
};
class B
{
public:
void subtraction(int a,int b)
{
cout<<"Subtraction:"<<a-b<<endl;
}
};
class C
{
public:
void multiplication(int a,int b)
{
cout<<"Multiplication:"<<a*b<<endl;
}
};
class D:public A,public B,public C
S6 CSC Page 25
C++ Programming 2016
{
public:
void division(int a,int b)
{
cout<<"Division:"<<a/b<<endl;
}
};
void main( )
{
clrscr( );
int a,b;
cout<<"a and b?"<<endl;
cin>>a>>b;
D ob;
ob.addition(a,b);
ob.subtraction(a,b);
ob.multiplication(a,b);
ob.division(a,b);
getch( );
}
A B C
D
3.3.4. Simple inheritance
void test( ) {
B b; // Create instance of B
D d; // Create instance of D
S6 CSC Page 26
C++ Programming 2016
getch( );
}
We discussed up to now how the inheritance can be used to modify a class when it did not fulfill
the requirements of a particular problem.
Additional members are added by the inheritance to extend the possibilities of a class. Another
interesting application of the inheritance is to use it like support with the hierarchical design of a
program.
All the students have certain joint things and, at the same time, all the accounts have certain
common features.
Students
S6 CSC Page 28
C++ Programming 2016
In the Object Oriented programming, the inheritance is the process by which the objects of a
class acquire the properties and the functionality of the objects of another class.
First of all, let us create a class which is called vehicle containing 2 variables and 4 initialized
methods. Let us save this class in the "INCLUDE" folder of TC and with the extension of ".h" so
that we can use it like a header file.
//vehicle.h
// vehicle header file
#ifndef VEHICLE_H
#define VEHICLE_H
class vehicle {
protected:
int wheels;
float weight;
public:
void initialize (int, float);
int get_wheels (void);
float get_weight (void);
float wheel_loading (void);
};
#endif
All the attributes and the methods of the parent class will be inherited by the child class and the
child class will be able to use them.
From the three objects created by using the transport class, we will be able to call, and thus to
reach the variables and the functions of the base class, vehicle.
We created three objects statically: car, motorcycle and truck. And we can use any function of
the vehicle class by simply calling it using one of these objects. We thus have a collection of
objects.
S6 CSC Page 29
C++ Programming 2016
// transport.cpp
#include <iostream.h>
#include<vehicle.h>
#include<conio.h>
// initialize to any data desired
void vehicle::initialize (int in_wheels, float in_weight)
{
wheels = in_wheels;
weight = in_weight;
}
// get the number of wheels of this vehicle
int vehicle::get_wheels( )
{
return wheels;
}
// return the weight of this vehicle
float vehicle::get_weight( )
{
return weight;
}
// return the weight on each wheel
float vehicle::wheel_loading ( )
{
return weight/wheels;
}
class transport:public vehicle
{
public:
int a;
int number(void);
};
int transport::number( )
{
cout<<"Enter number:\n";
cin>>a;
return a;
}
void main( )
{
clrscr( );
transport car,motorcycle,truck;
car.initialize (4, 3000.0);
motorcycle.initialize (2, 900.0);
S6 CSC Page 30
C++ Programming 2016
By making the two variables wheel and weight dynamic by asking the user to enter their
values from the screen, the main function can be modified as follows:
void main( )
{
clrscr( );
int wheelcar,wheelmoto,wheeltruck;
float weicar,weimoto,weitruck;
transport car,motorcycle,truck;
cout<<"Enter wheels and weight for a car"<<endl;
cin>>wheelcar>>weicar;
cout<<"Enter wheels and weight for the motocycle"<<endl;
cin>>wheelmoto>>weimoto;
cout<<"Enter wheels and weight for the truck"<<endl;
cin>>wheeltruck>>weitruck;
car.initialize (wheelmoto, weimoto);
motorcycle.initialize (wheelmoto, weitruck);
truck.initialize (wheeltruck,weitruck);
cout<<"Number="<<car.number( );
cout << "\n\nThe car has " << car.get_wheels( ) << " wheels \n\n";
cout << "The truck has a loading of " << truck.wheel_loading( )
<< " pounds per wheel \n\n";
cout << "The motorcycle weighs\t" << motorcycle.get_weight( )
<< " pounds \n\n";
getch ( );
}
S6 CSC Page 31
C++ Programming 2016
A class can inherit the attributes of two or more classes. This is known as multiple inheritance.
Multiple inheritance enables to combine the features of several existing classes as a starting point
for defining new classes.
It is like a child inheriting the physical features of one parent and the intelligence of another.
Where, visibility can be either public or private. The base classes are separated by commas.
Let us consider a situation where all the three kinds of inheritance, namely, multilevel, multiple
and hierarchical inheritance, are involved. The child has two direct base classes ‘parent1’ and
‘parent2’ which themselves have a common base class ‘grandparent’. The ‘child’ inherits the
traits of ‘grandparent’ via two separate paths. It can also inherit directly as shown the broken
line. The ‘grandparent’ is sometimes referred to as indirect base class.
Grandparent
Parent 1 Parent 2
Child
S6 CSC Page 32
C++ Programming 2016
Inheritance by the child as shown in the figure might pose some problems. All the public and
protected members of ‘grandparent’ are inherited into ‘child’ twice, first via ‘parent1’ and again
via ‘parent2’. This means ‘child’ would have duplicate sets of the members inherited from
‘grandparent’. This introduces ambiguity and should be avoided.
The duplication of inherited members due to these multiple paths can be avoided by making the
common base class (ancestor class) as virtual base class while declaring the direct or
intermediate base classes as shown below:
class grandparent
{
….
….
};
class parent1: virtual public grandparent
{
…
…
};
class parent2: public virtual grandparent
{
….
….
};
class child: public parent1, public parent2
{
….// only one copy of grandparent
….// will be inherited
};
When a class is made a virtual base class, C++ takes necessary care to see that only one copy of
that class is inherited, regardless of how many inheritance paths exist between the virtual base
class and a derived class. Note that the keywords virtual and public may be used in either order.
test sports
S6 CSC Page 33
result
C++ Programming 2016
Assume that the class sports derives the nbr from the class student.
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int nbr;
public:
void getident(int a)
{
nbr=a;
}
void displayident(void)
{
cout<<"Number="<<nbr<<endl;
}
};
void displaytest(void)
{
cout<<"Math="<<math<<endl;
cout<<"French="<<fr<<endl;
}
};
S6 CSC Page 34
C++ Programming 2016
displayident( );
displaytest( );
displaysport( );
cout<<"Total="<<total<<endl;
}
};
void main( )
{
clrscr( );
result ob;
ob.getident(24);
ob.gettest(30.51,25.72);
ob.getsport(46.3);
ob.displayresult( );
getch( );
}
S6 CSC Page 35
C++ Programming 2016
Attention!
Multiple inheritance can cause some confusing situations, and is much more complex than single
inheritance, it has increased complexity and ambiguity. Most modern OOP languages do not
allow multiple inheritance.
Examples:
In the above program if we do not use the keyword virtual to indicate that the class student is a
virtual base class, we shall have the 2 following errors:
ABSTRACT CLASSES
An abstract class is one that is not used to create objects. An abstract class is designated only to
act as a base class (to be inherited by other classes). It is a design concept in program
development and provides a base upon which other classes may be built. In the previous
example, the student class is an abstract class since it was no used to create any objects.
S6 CSC Page 36