You are on page 1of 120

Software Crisis

• Developments in software technology continue to be dynamic. New tools and techniques


are announced in quick succession. This forced software engineers and industry to
continuously look for new approaches to software design and development, and they are
becoming more and more critical in view of the increasing complexity of software systems
as well as the highly competitive nature of the industry. These rapid advances appear to
have created a situation of crisis within the industry. The following issues needed to be
addressed to face the crisis:

• How to represent real-life entities of problems in system design?

• How to design system with open interfaces?

• How to ensure reusability and extensibility of modules?

• How to develop modules that are tolerant of any changes in future?

• How to improve software productivity and decrease software cost?

• How to improve the quality of software?

• How to manage time schedules?


Procedural Programming
(Procedure Oriented Programming)
• In the procedure oriented approach, the problem is viewed as the sequence of processes to
be done such as reading, calculating and printing such as cobol, fortran and c. The primary
focus is on functions.
• A typical structure for procedural programming is shown below
Procedural Programming
• Procedure oriented programming basically consists of writing a list of instructions for the
computer to follow, and organizing these instructions into groups known as functions. We
normally use flowcharts to organize these actions and represent the flow of control from one
action to another.
• In a multi-function program, many important data items are placed as global so that they may
be accessed by all the functions. Each function may have its own local data. Global data are
more vulnerable to an inadvertent change by a function. In a large program it is very difficult
to identify what data is used by which function.
• Another serious drawback with the procedural approach is that we do not model real world
problems very well. This is because functions are action-oriented and do not really
corresponding to the element of the problem.
• Some Characteristics exhibited by procedure-oriented programming are:
• Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach in program design.
Object Oriented Programming
• The major motivating factor in the invention of object-oriented approach is to remove some
of the flaws encountered in the procedural approach. OOP treats data as a critical element
in the program development and does not allow it to flow freely around the system. It ties
data more closely to the function that operate on it, and protects it from accidental
modification from outside function. OOP allows decomposition of a problem into a number
of entities called objects and then builds data and function around these objects.
• The data of an object can be accessed only by the function associated with that object.
• However, a function of one object can access the functions of other objects.
Features Object Oriented Programming
Some of the features of object oriented programming are:

• Emphasis is on data rather than procedure.

• Programs are divided into what are known as objects.

• Data structures are designed such that they characterize the objects.

• Functions that operate on the data of an object are ties together in the data structure.

• Data is hidden and cannot be accessed by external function.

• Objects may communicate with each other through function.

• New data and functions can be easily added whenever necessary.

• Follows bottom up approach in program design.


Concepts of OOP
• It is necessary to understand some of the concepts used extensively in object-oriented
programming. These include:
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
Objects
• Objects are the basic run time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program has to handle.
Programming problem is analyzed in term of objects and the nature of communication
between them. Program objects should be chosen such that they match closely with the
real-world objects. Objects take up space in the memory and have an associated address
like a record in Pascal, or a structure in c.
Concepts of OOP
• When a program is executed, the objects interact by sending messages to one another. For
example, if “customer” and “account” are two objects in a program, then the customer
object may send a message to the count object requesting for the bank balance.
• Each object contains data and code to manipulate data. Objects can interact without having
to know details of each other’s data or code. It is a sufficient to know the type of message
accepted, and the type of response returned by the objects.
• An example that is popularly used in object-oriented analysis and design
Concepts of OOP
Classes
• Objects contain data, and code to manipulate that data. The entire set of data and code of an
object can be made a user-defined data type with the help of class.
• In fact, objects are variables of the type class. Once a class has been defined, we can create
any number of objects belonging to that class. Each object is associated with the data of
type class A class is thus a collection of objects similar types. For example, Mango, Apple
and Orange members of class fruit.
• Classes are user-defined that types and behave like the built-in types of a programming
language. The syntax used to create an object is not different then the syntax used to create
an integer object in C. If fruit has been defines as a class, then the statement with which
they are created.
• Fruit Mango;

Will create an object mango belonging to the class fruit.


Concepts of OOP
Data Abstraction / Encapsulation
• The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data abstraction /encapsulation are the most striking feature of a class. The
data is not accessible to the outside world, and only those functions which are wrapped in the
class can access it. These functions provide the interface between the object’s data and the
program. This insulation of the data from direct access by the program is called data hiding
or information hiding.

Abstraction
• Refers to the act of representing essential features without including the background details

or explanation. Classes use the concept of abstraction and are defined as a list of abstract

attributes such as size, weight, and cost, and functions operate on these attributes.
• The attributes are some times called data members because they hold information. The
functions that operate on these data are sometimes called methods or member function.
• Abstraction serves as a template for subclasses to fully implement the methods.
Concepts of OOP
Inheritance
• Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification.
• Inheritance represents an IS-A relationship
• For example, the bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the class
‘bird’. The principal behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived.
• In OOP, the concept of inheritance provides the idea of reusability. This means that we can
add additional features to an existing class without modifying it. This is possible by deriving
a new class from the existing one. The new class will have the combined feature of both the
classes.
• The real appeal and power of the inheritance mechanism is that it allows the programmer to
reuse a class i.e almost, but not exactly, what he wants, and to tailor the class in such a way
that it does not introduce any undesirable side-effects into the rest of classes.
Concepts of OOP
• Inheritance example
Concepts of OOP
Polymorphism
• Polymorphism is another important OOP concept.
• Polymorphism, a Greek term, means the ability to take more than one form.
• An operation may exhibit different behavior in different instances. The behavior depends
upon the types of data used in the operation. For example, consider the operation of
addition for two numbers, the operation will generate a sum. If the operands are strings,
then the operation would produce a third string by concatenation. The process of making an
operator to exhibit different behaviors in different instances is known as operator
overloading.
Concepts of OOP
• Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. This means that a general class of operations
may be accessed in the same manner even though specific action associated with each
operation may differ. Polymorphism is extensively used in implementing inheritance.

Dynamic Binding
• Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. It is associated with polymorphism and
inheritance. A function call associated with a polymorphic reference depends on the
dynamic type of that reference.
• Consider the procedure “draw” by inheritance, every object will have this procedure. Its
algorithm is, however, unique to each object and so the draw procedure will be redefined in
each class that defines the object. At run-time, the code matching the object under current
reference will be called.
Concepts of OOP
Message Passing
• An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic
steps:
• 1. Creating classes that define object and their behavior,
• 2. Creating objects from class definitions, and
• 3. Establishing communication among objects.
• Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes
it easier to talk about building systems that directly model or simulate their real-world
counterparts.
• A message for an object is a request for execution of a procedure, and therefore will invoke
a function (procedure) in the receiving object that generates the desired results. Message
passing involves specifying the name of object, the name of the function (message) and the
Concepts of OOP

• An object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive
Benefits of OOP
• OOP offers several benefits to both the program designer and the user. Object-Orientation
contributes to the solution of many problems associated with the development and quality
of software products. The technology promises greater programmer productivity, better
quality of software and lesser maintenance cost. The principal advantages are:
• Through inheritance, we can eliminate redundant code extend the use of existing
classes.
• We can build programs from the standard working modules that communicate with
one another, rather than having to start writing the code from scratch. This leads to
saving of development time and higher productivity.
• The principle of data hiding helps the programmer to build secure program that can
not be invaded by code in other parts of a programs.
• It is possible to have multiple instances of an object to co-exist without any
interference.
• It is possible to map objects in the problem domain
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables us to capture more detail of a model
• Object-oriented system can be easily upgraded from small to large system.
• Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
• Software complexity can be easily managed.
Limitations of OOP
• Size: Object Oriented programs are much larger than other programs. In the early days of
computing, space on hard drives, floppy drives and in memory was at a premium. Today
we do not have these restrictions.
• Effort: Object Oriented programs require a lot of work to create. Specifically, a great deal
of planning goes into an object oriented program well before a single piece of code is ever
written. Initially, this early effort was felt by many to be a waste of time. In addition,
because the programs were larger coders spent more time actually writing the program.
• Speed: Object Oriented programs are slower than other programs, partially because of their
size. Other aspects of Object Oriented Programs also demand more system resources, thus
slowing the program down.
• The benefits of OOP may be realized after a long period.
• Requires intensive testing procedures.
Object Based Language vs OOP language
• Object-oriented programming is not the right of any particular languages. Like structured
programming, OOP concepts can be implemented using languages such as C and Pascal.
However, programming becomes clumsy and may generate confusion when the programs
grow large. A language that is specially id designed to support the OOP concepts makes it
easier to implement them.
• The languages should support several of the OOP concepts to claim that they are object-
oriented. Depending upon the features they support, they can be classified into the
following two categories:
• 1. Object-based programming languages, and
• 2. Object-oriented programming languages.
• Object-based programming is the style of programming that primarily supports
encapsulation and object identity. Major feature that are required for object based
programming are:
• Data encapsulation
• Data hiding and access mechanisms
• Automatic initialization and clear-up of objects
• Operator overloading
Object Based Language vs OOP language
• Languages that support programming with objects are said to the objects-based
programming languages. They do not support inheritance and dynamic binding.. Object
based programming language follows all the features of OOPs except Inheritance.
JavaScript , Ada, and VBScript are examples of object based programming languages.
• Object-oriented programming language incorporates all of object-based programming
features along with two additional features, namely, inheritance and dynamic binding.
Object-oriented programming can therefore be characterized by the following statements:
• Object-based features + inheritance + dynamic binding
Application of OOP
• OOP has become one of the programming buzzwords today. There appears to be a great
deal of excitement and interest among software engineers in using OOP. Applications of
OOP are beginning to gain importance in many areas. The most popular application of
object-oriented programming, up to now, has been in the area of user interface design such
as window. Hundreds of windowing systems have been developed, using the OOP
techniques.
• Real-business system are often much more complex and contain many more objects with
complicated attributes and method. OOP is useful in these types of application because it
can simplify a complex problem. The promising areas of application of OOP include:
• Real-time systems
• • Simulation and modeling
• • Object-oriented databases
• • Hypertext, Hypermedia, and expertext
• • AI and expert systems
• • Neural networks and parallel programming
• • Decision support and office automation systems
• • CIM/CAM/CAD systems
History of C++
• C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell
Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s.
• Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both
the languages and create a more powerful language that could support object-oriented programming
features and still retain the power and elegance of C. The result was C++. Therefore, C++ is an
extension of C with a major addition of the class construct feature of Simula67.
• Since the class was a major addition to the original C language, Stroustrup initially called the new
language ‘C with classes’. However, later in 1983, the name was changed to C++. The idea of C++
comes from the C increment operator ++, thereby suggesting that C++ is an augmented version of C.
• C+ + is a superset of C. Almost all c programs are also C++ programs. However, there are a few minor
differences that will prevent a c program to run under C++ complier.
• The most important facilities that C++ adds on to C care classes, inheritance, function overloading and
operator overloading. These features enable creating of abstract data types, inherit properties from
existing data types and support polymorphism, thereby making C++ a truly object-oriented language.
Summary
• Software technology has evolved through a series of phases during the last five decades.
• POP follows top-down approach where problem is viewed as sequence of task to be performed and
functions are written for implementing these tasks.
• POP has two major drawbacks:
1. Data can move freely around the program.
2. It does not model very well the real-world problems.
• OOP was inventing to overcome the drawbacks of POP. It follows down -up approach.
• In OOP, problem is considered as a collection of objects and objects are instance of classes.
• Data abstraction refers to putting together essential features without including background details.
• Inheritance is the process by which objects of one class acquire properties of objects of another class.
• Polymorphism means one name, multiple forms. It allows us to have more than one function with the
same name in a program.
• Dynamic binding means that the code associated with a given procedure is not known until the time of the
run time.
• Message passing involves specifying the name of the object, the name of the function and the information
to be sent.
• C++ is a superset of C language.
• C++ ads a number of features such as objects, inheritance, function overloading and operator overloading
to C.
• C++ supports interactive input and output features and introduces anew comment symbol // that can be
used for single line comment.
• Like C programs, execution of all C++ program begins at main() function.
Keywords
Keywords
Structure of a program
• C++ is a versatile language for handling very large programs; it is suitable for virtually any
programming task including development of editors, compilers, databases, communication
systems and any complex real life applications systems.
• Since C++ allows us to create hierarchy related objects, we can build special object-
oriented libraries which can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get closed to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to be
implemented, it is very easy to add to the existing structure of an object.
• • It is expected that C++ will replace C as a general-purpose language in the near future.

Structure of a c++ program


#include<iostream>
using namespace std;
int main()
{
cout<<” c++ is better than c \n”;
return 0;
}
Structure of a program
iostream File
• We have used the following #include directive in the program:
• #include <iostream>
• The #include directive instructs the compiler to include the contents of the file enclosed within angular
brackets into the source file. The header file iostream.h should be included at the beginning of all
programs that use input/output statements.
namespace
• Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a scope
for the identifiers that are used in a program. For using the identifier defined in the namespace scope
we must include the using directive, like
using namespace std;
• Here, std is the namespace where ANSI C++ standard class libraries are defined. All ANSI C++
programs must include this directive. This will bring all the identifiers defined in std to the current
global scope. using and namespace are the new keyword of C++.
NB: If the statement is not included then the code then a some statements will not be recognised e.g
cout, endl as they will require a scope resolution operator i.e
# include<iostream>
int main()
{
std::cout<<” c++ is better than c ”<<std::endl;
return 0;
}
Which will be monotonous
Structure of a program
Comments
• C++ introduces a new comment symbol // (double slash). Comment start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the
line, and whatever follows till the end of the line is ignored. Note that there is no closing
symbol.
• The double slash comment is basically a single line comment. Multiline comments can be
written as follows:
• // This is an example of
• The C comment symbols /*,*/ are still valid and are more suitable for multiline comments.
The following comment is allowed:
/* This is an example of
C++ program to illustrate some of its features
*/
• Curly brackets { } indicate the beginning and end of a function, which can also be called
the function's body. The information inside the brackets indicates what the function does
when executed.
• The entry point of every C++ program is main(), irrespective of what the program does.
Structure of a program
return type of main()
In C++, main () returns an integer value to the operating system. Therefore, every main () in
C++ should end with a return (0) statement; otherwise a warning an error might occur. Since
main () returns an integer type for main () is explicitly specified as int.
NB: The default return type for all functions in C++ is int.
Output operator
• . The statement
cout<<”C++ is better than C.”;
• Causes the string in quotation marks to be displayed on the screen. This statement introduces two new
C++ features, cout and <<. The identifier cout(pronounced as C out) is a predefined object that
represents the standard output stream in C++. Here, the standard output stream represents the screen. It
is also possible to redirect the output to other output devices. The operator << is called the insertion or
put to operator.
• -in C++, streams are used to perform input and output operations.
• -In most program environments, the standard default output destination is the screen. In C++, cout is the
stream object used to access it.
• -In C++, the semicolon is used to terminate a statement. Each statement must end with a semicolon. It
indicates the end of one logical expression.
The \n is known as an escape character which instructs the compiler to jump a line after
printing a message. There are other escape codes such as
\t for a tab sequence
\b for a backspace
Structure of a program
Multiple New Lines

-Using a single cout statement with as many instances of \n as your program requires
will print out multiple lines of text.

#include <iostream>

using namespace std;

int main()

cout << " Hello \n world! \n I \n love \n programming!";

return 0;

}
Structure of a program
Rearrange the code blocks to form a valid C++ program:

using namespace std;

cout << "Awesome!"; return 0;

int main() {

#include <iostream>

=======================================================
New Line
• The cout operator does not insert a line break at the end of the output. One way to print two lines
is to use the endl manipulator, which will put in a line break.

#include <iostream>

using namespace std;

int main(){

cout << "Hello world!" << endl;

cout << "I love programming!";

return 0; }
Accepting user input
• Let us consider a slightly more complex C++ program. Assume that we should like to read
two numbers from the keyboard and display their average on the screen. C++ statements to
accomplish this is shown in the program below:
#include<iostream> // include header file
using namespace std;
int main()
{
float number1, number2,sum, average;
cin >> number1; // Read Numbers
cin >> number2; // from keyboard
sum = number1 + number2;
average = sum/2;
cout << ”Sum = “ << sum << endl;
cout << “Average = “ << average << endl;
return 0;
} //end of example
The output would be:
Enter two numbers: 6.5 7.5
Sum = 14
Average = 7
Accepting user input
• The program uses four variables number1, number2, sum and average. They are declared as
type float by the statement.
• float number1, number2, sum, average;
• All variable must be declared before they are used in the program.
Input Operator
• The statement
• cin >> number1;
• Is an input statement and causes the program to wait for the user to type in a number. The
number keyed in is placed in the variable number1. The identifier cin (pronounced ‘C in’)
is a predefined object in C++ that corresponds to the standard input stream.
• Here, this stream represents the keyboard. The operator >> is known as extraction or get
from operator. It extracts (or takes) the value from the keyboard and assigns it to the
variable on its right . This corresponds to a familiar scanf() operation. Like <<, the operator
>> can also be overloaded.
Cascading the input and output operators
• We have used the insertion operator << repeatedly in the last two statements for printing
results.
• The statement
cout << “Sum = “ << sum << “\n”;
• First sends the string “Sum = “ to cout and then sends the value of sum. Finally, it sends the
newline character so that the next output will be in the new line. The multiple use of << in
one statement is called cascading. When cascading an output operator, we should ensure
necessary blank spaces between different items. Using the cascading technique, the last two
statements can be combined as follows:
cout << “Sum = “ << sum << “\n” << “Average = “ << average << “\n”;
• This is one statement but provides two line of output. If you want only one line of output,
the statement will be:
cout << “Sum = “ << sum << “,”
<< “Average = “ << average << “\n”;
• The output will be:
• Sum = 14, average = 7
We can also cascade input operator >> as shown below:
cin >> number1 >> number2;
• The values are assigned from left to right. That is, if we key in two values, say, 10 and 20,
then 10 will be assigned to munber1 and 20 to number2.
Cascading the input and output operators
• We have used the insertion operator << repeatedly in the last two statements for printing results.
• The statement
cout << “Sum = “ << sum << “\n”;
• First sends the string “Sum = “ to cout and then sends the value of sum. Finally, it sends the newline
character so that the next output will be in the new line. The multiple use of << in one statement is
called cascading. When cascading an output operator, we should ensure necessary blank spaces
between different items. Using the cascading technique, the last two statements can be combined as
follows:
cout << “Sum = “ << sum << “\n” << “Average = “ << average << “\n”;
• This is one statement but provides two line of output. If you want only one line of output, the statement
will be:
cout << “Sum = “ << sum << “,”
<< “Average = “ << average << “\n”;
• The output will be:
• Sum = 14, average = 7
We can also cascade input operator >> as shown below:
cin >> number1 >> number2;
• The values are assigned from left to right. That is, if we key in two values, say, 10 and 20, then 10 will
be assigned to munber1 and 20 to number2.
Accepting input for string types
• We normally use the cin >> for a string character eg Thompson, but there are situations
where you
may want to accept a string that contains spaces eg Thompson Marufu
• In such a case we use the getline() method e.g

string name;
cout<<“Enter the full name”<<endl;
getline(cin,name);

NB: Such variables that contain spaces should be prompted first before other variables as an
anomaly can occur in the program flow
Datatypes and Variables
Datatypes can be primitive or reference types. The following are examples of primitive
datatypes

Variable : A variable is a storage location in memory

Rules for naming variables

• variable names can contain letters, digits and underscore characters

• they cannot contain special characters such as ‘, & , @etc

• they cannot start with a number but can start with an underscore character or a letter

• spaces are not allowed

• Should be unique within their scope


Variable Declaration and Initialisation
datatype identifier

• int myInt;

• int _my32Int;

• int myInt@32 //incorrect as it constains a special character

• int new //incorrect as it contains reserved words

• int 32Int;//incorrect as it starts with a number

Variable Assignation

• Syntax

1.datatype identifier = value;

2. datatype identifier(initial value); - this is known as constructor initialisation 

• variables are assigned using the (=) operator

e.g int Age =50; int Age(50);

• we can assign more than one variable of the same type in one line

e.g int Age=50, mark=30; int Age(50), mark(30);


Variable Declaration and Initialisation
Case-Sensitivity

• C++ is case-sensitive, which means that an identifier written in uppercase is not equivalent
to another one with the same name in lowercase.

• For example, myvariable is not the same as MYVARIABLE and not the same as
MyVariable. These are three different variables.

• Choose variable names that suggest the usage, for example: firstName, lastName.

Which of the following are legal variable names in C++?


• 14var
• name3_var
• salary
• &*^var
Review Questions
Pointers
• A pointer is a variable that stores the address location of another variable.
• The pointer variable defines where to get the value of a specific data variable instead of
defining actual data.
• The pointers are one of the most useful and strongest features of C++. There are three
useful reason for proper utilization of pointer :
(i) The memory location can be directly accessed and manipulated.
(ii) Dynamic memory allocation is possible.
(iii) Efficiency of some particular routines can be improved.
• Any variable declared in a program has two components:
(i) Address of the variable
(ii) Value stored in the variable.
For example, int x = 386;
• The above declaration tells the C++ compiler for :
• (a) Reservation of space in memory for storing the value.
• (b) Associating the name x with his memory location.
• (c) Storing the value 386 at this location.
• It can be represented with the following figure :

Pointers
Here, the address 3313 is assumed one, it may be some other address also.
• The pointers are one of the most useful and strongest features of C++.
• Declaring a pointer
• We can declare a pointer variable similar to other variables in C++.
• The declaration is based on the data type of the variable it points to.
• The declaration of a pointer variable will take the following form:
datatype * pointervariable;
In this case the pointer variable is the name of the pointer and the datatype any valid C++ type such
as int, char, float etc. The datatype is followed by an asterisk(*) symbol so as to distinguish a pointer variable from other variables to the compiler.
• We can locate asterisk(*) immediately before the variable or between the datatype and the pointer variable or immediatley after the datatype.
Both cases will not affect the execution process.
• A pointer variable can point to any type of data available in C++ but it is necessary to understand that a pointer is able to point to only one data
type at the specific time for example
int * ptr;
ptr is a pointer variable that points to an integer variable which means that the vairable should contain the memory location of any integer variable
and we can also declare pointer variables for other data types also.
• There is need to initialise the variable before making use of it in a C++ program . The pointer variable also needs to be initiitialised in the
following manner
int *ptr, a; //declaration
ptr= &a; //initialisation


Pointers
• The pointer variable ptr contains the address of the variable a. The assignment statement
stored the address location of the variable.
• In pointers there are two operators that are used:
* Reference Operator (value pointed by)
& Deference Operator (address of )
Manipulation of pointers using the dereference operator
• The dereference operator allows us to get the content of the memory location that the
pointer points to
• After the assigning the address of the variable to a pointer, there may be need to change the
content of the variable making use of the dereference operator.
Example

int a=10, *ptr;


ptr= &a;
cout<<“The value of a is: ”<<a<<endl;
*ptr= (*ptr)/2;
cout<<“The value of a is: ”<<(*ptr)<<endl;

Before dereferencing a pointer it is essential to assign a value to the pointer. If we attempt to


dereference an unitialised pointer, a runtime error will occur
Pointer manipulation example 2
#include <iostream>
using namespace std;
int main (){
int value1 = 5, value2 = 15;
int * mypointer;
mypointer = &value1;
*mypointer = 10;
mypointer = &value2;
*mypointer = 20;
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
}
Notice how the values of value1 and value2 have changed indirectly. First we have
assigned to mypointer the address of value1 using the deference ampersand sign
(&). Then we have assigned 10 to the value pointed by mypointer, which is pointing to
the address of value1, so we have modified value1 indirectly
Pointer Arithmetic
C++ allows pointers to perform the following arithmetic operations
• A pointer can be incremented (++) or decremented(--)
• Any integer can be added to or subtracted from a pointer
int x=25;

int *p= &x;

cout<<p; //address of the variable

cout <<*p; //25 -dereference

x=x+5; //30

x= *p+5;//35

*p= *p+5;//40
• One pointer can be subtracted from another
#include <iostream>
Pointers in Arrays
using namespace std;
int main(){
int num[ ]= {56,75,22,18,90}, *ptr;
ptr= num;
/* Printing the value in the array * /
cout<<“\n Value of ptr : ”<<*ptr<<endl;
ptr++;
cout<<“\n Value of ptr++ : ”<<*ptr<<endl;
ptr--;
cout<<“\n Value of ptr-- : ”<<*ptr<<endl;
ptr= ptr+2;
cout<<“\n Value of ptr+2 : ”<<*ptr<<endl;
ptr=ptr-1;
cout<“Value of ptr-1”<<*ptr<<endl;
ptr+=3;
cout<“Value of ptr+=3”<<*ptr<<endl;
ptr-=2;
cout<“Value of ptr-=2”<<*ptr<<endl;
return 0; }
Pointers in Arrays: Accepting user input
#include <iostream>
using namespace std;
int main(){
int num[5], *p;
ptr= num;
//acepting user input
for(int i=0; i<5; i++){
cout<<“Enter an element”<<endl;
cin>>*ptr;
ptr++;
}
//dispaying the output
for(int i=0; i<5; ++){
cout<<num[i]<<endl;
}
return 0;
}
Pointers in Arrays: Accepting user input
• We can create an array of pointers in C++ which represents a collection of
addresses
• By declaring an array of pointers we can save a substantial amount of space.
• An array of pointers point to an array of data items
• Each element of the pointer array points to an item of the data array.
• The data items can be accessed either directly or by dereferencing the elements of
pointer array
• We can recognise the pointer elements without affecting the data items
• We can declare an array of pointers as follows:

int *inarray[10];
• The statement declares an array of 10 pointers each of which points to an integer.
• The address of the first pointer is inarray[0] and the last address is inarray[9]
• An example is given below::
Pointers in Arrays: Accepting user input
#include<iostream>
#include<ctype.h>
#include<string>
using namespace std;
int main(){
int i=0;
char *ptr[ 10] = { “books”,”television”, “computer”, “sports”};
char str[25];
cout<<“Enter your favourite leisure pursuit”<<endl;
cin>>str;
for(i=0; i<4; i++) {
if(!strcmp(str, *ptr[i]) )
{
cout<<“Your favourite pursuit is available here”<<endl;
break;
}}
if(i==4)
cout<<“Your favourite is not available here!”<<endl;
return 0;
}
Pointers to Functions
• Pointers can be used to refer to functions
• The pointer to function is known as a callback function
• Function pointers allow us to select a function dynamically at runtime.
• We can pass a function as an argument to another to another function where it will be
passed as a pointer
• We cannot dereference a function pointer
• C++ provides two types of function pointers (1) pointers that point to static member functions (2)
pointers that point to non-static member functions
Declaring a pointer variable
• We declare a function pointer in C++ in the following form

datatype (* function_name )( );
The datatype is any valid data type is any valid data type used in c++ , the function name is the name of the
function which is preceeded by an asterisk which is any valid name.

e.g int (*num_function(int x));


Declaring a pointer only creates a pointer not an actual function. The function must have the same return
type and arguments
Pointers to Functions: Example
# include<iosteam>
using namespace std;
typedef void (*FuncPtr) (int, int);
void Add(int I, int j){
cout<<“i + j: ”<< i+j<<endl;
}
void Subtract( int I, int j){
cout<<“i -j: ”<< i-j<<endl;
}
int main( ){
FuncPtr ptr= & Add;
cout<<ptr(1,2)<<endl;// cout<<(*ptr) ( 1,2)<<endl;
ptr= &Subtract;
cout<<ptr(3,2)<<endl; // cout<<(*ptr) ( 1,2)<<endl;
return 0;
}
NB: the declaration of the pointer variable can be made in the main without the typedef statement e.g
int main(){
void (*p)(int, int);
P= & Add;

Pointers to Functions: Example 2
# include<iosteam>
using namespace std;
double base, height;
void setValues(){
cout<<“Enter the base”<<endl;
cin>>base;
cout<<“Enter the height”<<endl;
cin>>height;
}
double calcArea(){
return (base *height *0.5);
}
int main( ){
void (*p) ( );
double (*r)( );
p= & setValues;
r= & calcArea;
p( );
cout<<“The area is : ”<<(*r)( )<<endl;
return 0;
}
Pointers , Arrays and Functions:
# include<iosteam>
using namespace std;
void answer(double *p, int num){

int sum=0;

for(int i=0; i<num; i++){

cout<<“Enter an element”<<endl;

cin>>*p;

sum+ =*p;

cout<<“The sum is: ”<<sum<<endl;

int main( ){
double r[7];
answer(r,7);
return 0;
}
Pointers as function arguments
# include<iosteam>
using namespace std;
int calc(int *p, int *e) {
return (*p) * (*e);
}
int main( ){
int a= 20, b=10;
cout<<“The result is: “ <<calc(&a, &b)<<endl;

return 0;
}
Pointers as function arguments
Dynamic Memory Allocation
• This deals with the allocation of memory and deallocation of memory during runtime
• In our programs, we have only had as much memory as we have requested in declarations of variables,
arrays and other objects that we included, having the size of all of them fixed before the execution of the
program. But, what if we need a variable amount of memory that can only be determined during the
program execution (runtime), for example, in case that we need an user input to determine the necessary
amount of space?
• The answer is dynamic memory, for which C++ integrates the operators new and delete.
New Operator
• If we wish to allocate memory as and when required new operator helps in this context.
• The syntax of the new operator is given below :
pointer_variable = new data_type;
• Where the data type is any allowed C++ data type and the pointer variable is a pointer of the same data
type. For example,
#include<iostream>
using namespace std;
int main(){
int *ptr;
ptr= new int;
*ptr= 10;
*ptr+=127;
cout<<*ptr<<endl;
delete ptr;
return 0; }
Dynamic Memory Allocation
char * cptr
cptr = new char;
• The above statements allocate 1 byte and assigns the address to cptr.
Dynamic Memory Allocation for Arrays
Assume that a teacher wants to input the final exam mark for each of the 30 students in her
class. She wants this program to be made at the beginning of the year. Therefore the
programmer creates an array to hold 30 spaces
int examMark[30];
Three weeks before examination half of her class drops out. 5 of those remaining don’t show
up on examination day. This results in roughly 20 students not having an exam mark at all.
Why would we allocate memory to hold the final exam grade for the entire class
(30 students) when in reality only 10 of them will write the exam
Through memory allocation we can allocate the necessary memory required during run time

• The following statement allocates 21 bytes of memory and assigns the starting address to cptr :
• char * cptr;
• cptro = new char [21];
• We can also allocate and initialize the memory in the following way :
Pointer_variable = new data_type (value);
Dynamic Memory Allocation
#include<iostream>
using namespace std;
int main(){
int size;
cout<<”How big is your array size”;
cin>>size;
int *array= new int[size];
for(int i= 0; i<size; i++){
array[i]= 7*i;//(*array(i+1)
}
cout<<”--------Array------------”<<endl;
for(int i=0; i<size; i++)}{
cout<<array[i];
}
return 0;
}
-it is important to free the memory you have allocated as it will stay in RAM and will be
inaccessible once your pointer either points to a different address or is set to zero.
Dynamic Memory Allocation
• Where value is the value to be stored in the newly allocated memory space and it must also
be of the type of specified data_type. For example,
• Char *cptr = new char (‘j’];
• Int *empno = new int [size]; //size must be specified
• Delete Operator
• It is used to release or deallocate memory. The syntax of delete operator is :
• delete_pointer_variable;
• For example,
• delete cptr;
• delete [ ] empno; //some versions of C++ may require size
Structures
Suppose you are writing an inventory program for a warehouse. The warehouse is filled with

bins, each containing a bunch of parts. All the parts in a bin are identical, so you don't have to

worry about mixed bins or partials.

For each bin you need to know:


• The name of the part it holds (30-character string).
• The quantity on hand (integer).
• The price (integer cents).

In previous example we have used arrays for storing a groupof similar data types, but in this

example you have a mixed bag: two integers and a string. Instead of an array, you will use a

new data type called a structure. In an array, all the elements are of the same type and are

numbered. In a structure, each element, or member, is named and has its own data type.
• A structure is a data type that can hold several different values. Unlike an array, these
values don’t have to have the same type. Each item or field in the data structure has it own
name.
Structures
• The general form of a structure definition is:
struct structure-name {
member-type member-name; // Comment
member-type member-name; // Comment
member-type method(){
..
}
....
} object;

• For example, say you want to define a bin to hold printer cables. The
structure definition is:
struct bin {
char name[30]; // Name of the part
int quantity; // How many are in the bin
int cost; // The cost of a single part
} printer_cable_box;
Structures
• We can create an array of objects in structures
e.g
struct employee{
string name;
float age;
public:
void getdata(){
cout<<“enter name”<<endl;
cin>>name;
cout<<“enter age”<<endl;
cin>>age;
}
void putdata(){
cout<<name<<setw(10)<<age<<endl;
}
};
• The setw( 10) is an inbluilt method under the <iomanip> header file which creates a space
in between characters in this case we are instructing the compiler to move 10 spaces after
printing the name.
Structures
The identifier employee is a userdefined data type and can be used to create objects that relate
to different categories of employees e.g
employee manager[3]; //array of manager
employee foreman[15]; //array of foreman
employee worker[75]; //array of worker

• The array manager contains three objects (managers) namely manager[]0


, manager[1], and manager[2] of type employee class.
• The same applies to foreman array which contains 15 objects(foreman) and the worker
array which contains 75 object (workers)
• Since an array of objects behaves like any other array we can use the ususal array accessing
methods to access indivisual elements and then the dot member operator to access the member
functions For example
for(int i=0; i<3; i++)
manager[i].putdata();
Will display the data of the ith element of the array manager. That is this statement requests the
object manager[i] to invoke the member function putdata( ).
Structures
Question
A certain university wants to adopt an electronic system that computes the degree class at the
end of a program. They have approached you a C++ expert to come up with a solution. The
table below shows how the degree class is computed.

The degree class is computed as follows:

Using concepts of structures write a program which captures Student details (Name,
IDNumber, Programme) for a specific number of students and then compute the degree class
based on the tables given above.
Structures
include<iomanip>
using namespace std;
struct Grade{
string name, reg, prog;
double score[4], aggregate=0; double level[4];
void setValues(int n){
cout<<"Enter details for Student "<<(n+1)<<endl;
cout<<"Enter reg"<<endl;
cin>>reg;
cout<<"Enter name"<<endl;
cin>>name;
cout<<"Enter programe"<<endl;
cin>>prog;
for(int i=0; i<4; i++){
cout<<"Enter score for level "<<(i+1)<<endl;
cin>>level[i];
if(i==0){
score[i]= level[i]*0.1;
aggregate+= score[i];
} else if(i==1){
score[i]= level[i]*0.2;
aggregate+= score[i]; }
else if(i==2){ Structures
score[i]= level[i]*0.3;
aggregate+= score[i];
} else if(i==3){
score[i]= level[i]*0.4; aggregate+= score[i];
} else{ cout<<"Invalid range"; }
}}
void output()
{ cout<<reg<<setw(7)<<name<<setw(7)<<prog<<setw(7)<<level[0]<<setw(7)<<score[0]<<setw(7)<<level[1]<<setw(7)
<<score[1]<<setw(7)<<level[2]<<setw(7)<<score[2]<<setw(7)<<level[3]<<setw(7)<<score[3]<<setw(7)<<aggregate<<
endl;
} };
int main() {
int n;
cout<<"Enter number of students"<<endl;
cin>>n;
Grade a[n]; //input
for(int i=0; i<n; i++){
a[i].setValues(i);
}
cout<<"Reg "<<setw(7)<<"Name"<<setw(7)<<"Prog"<<setw(7)<<"Level 1"<<setw(7)<<"Score"<<setw(7)<<"Level
2"<<setw(7)<<"Score"<<setw(7)<<"Level 3"<<setw(7)<<"Score"<<setw(7)<<"Level
4"<<setw(7)<<"Score"<<setw(7)<<"Aggregate"<<endl;
//input for(int i=0; i<n; i++){
a[i].output();
}
return 0;
}
Structures Question for practice
. Create a structure called Investment which contains the following members:
Variables
Item Data Type Description
 
name string name of the investor
invest double amount invested
interest double interest rate for investment
balance double amount after interest calculation
Functions
Item Return type Description
calcInterest double computes the interest(interest/100 x invest)
calcInvestment double computes the balance after interest (invest+ interest calculation)
The program should allow the user to specify the number of investors within the main. It

should also prompt the user to specify the elements to be input (name, invest interest) for

each investor. Sample output should be as follows:


Classes
• A class in C++ combines related data and functions together. It makes a data type which is
used for creating objects of this type.
• Classes represent real world entities that have both data type properties (characteristics) and
associated operations (behavior).
• The syntax of a class definition is shown below :
class name_of _class
{
private :
variable declaration; // data member
Function declaration; // Member Function (Method)
protected:
Variable declaration;
Function declaration;
public :
variable declaration;
Function declaration;
};
Classes
• Here, the keyword class specifies that we are using a new data type and is followed by the class name.
• The body of the class has three keywords namely :

(i) private (ii) public (iii) protected


• C++, the keywords private and public are called access specifiers.
• Private

Private data and functions can only be accessed from within the class itself and friends of the

class. The data hiding concept in C++ is achieved by using the keyword private. Data hiding is a

security measure is used to protect unauthorized users from performing any operation(read/write

or modify) on the data. The data declared under Private section are hidden and safe from

accidental manipulation. Though the user can use the private data but not by accident.
• Protected

Accessible in the same class, derived classes and friends of the class
• Public

These are accessible anywhere where the object is visible. There are less restrictions

imposed on the public modifier. The functions that operate on the data are generally public so

that they can be accessed from outside the class but this is not a rule that we must follow.
Classes
• Here, the keyword class specifies that we are using a new data type and is followed by the class name.
• The body of the class has three keywords namely :

(i) private (ii) public (iii) protected


• C++, the keywords private and public are called access specifiers.
• Private

Private data and functions can only be accessed from within the class itself and friends of the

class. The data hiding concept in C++ is achieved by using the keyword private. Data hiding is a

security measure is used to protect unauthorized users from performing any operation(read/write

or modify) on the data. The data declared under Private section are hidden and safe from

accidental manipulation. Though the user can use the private data but not by accident.
• Protected

Accessible in the same class, derived classes and friends of the class
• Public

These are accessible anywhere where the object is visible. There are less restrictions

imposed on the public modifier. The functions that operate on the data are generally public so

that they can be accessed from outside the class but this is not a rule that we must follow.
Classes
• The only difference between a structure and a class in C++ is that by default the members of

a class are private while by default the members of a structure are public.
• If labels are missing in a class by default all members are private and such a class will be
hidden from the outside world and does not serve any purpose
• Variables that are declared inside a class are referred to as data members and the function
are referred to as member functions. Member functions have access to private variables and
functions and can be accessed from outside.

Example

class Item{

Int number; //variables declaration

float cost; //private by default

public:

void getdata(int a, int b);

void putdata(void); //function declaration using prototype

};
Classes
The name item becomes a new type identifier that can be used to declare instances of that class

type. Class Item has two private data members and two public member functions . The function

getdata() can be used to assign values to member fields number and cost while putdata() for

displaying values. The functions provide access to the data members from outside the class.

Data from the class cannot be accessed by any function that is not a member of the class Item

Creating objects
• Declaring of item does not define any objects but will specify what they contain. After creation

of a class we need to create variables of the class type just like any other built in type for e.g

Item x; //such statements creates memory for the x of type Item.


• We can also create more than one object in one statement :: Item x,y,z;
• The declaration of an object is similar to that of a variable of any basic type.
• We can create objects by placing their names immediately after the closing brace but this method is rarely used:
class Item
{
.........
.........

} x,y,z;
Accessing Class members
Private members of a class can only be accessed through member functions of that class. The

main() cannot contain statements that access variables directly i.e number and cost from

previous example. The syntax is as follows:

object-name.function-name(actual-arguments);

For example call to the function

x.getdata(100,75.5);

Which will assign two variables some values of the object x by implementing the getdata()

function
• A member function can be invoked only using an object of the same class therefore we cannot directly call
methods outside the class i.e getdata(100,75.5);
• We can no also initialise private members or protected members directly outside the class

i.e x.number =100 since they are indirectly accessible by public methods.
• Objects communicate by sending and receiving messages which is achieved through member functions
e.g x.putdata() will send a message to object x requesting it to display its contents.
Accessing Class members
A variable declared as public can be accessed by the other objects directly

class xyz{

int x,y;

public:

int z;

};

int main(){

xyz p;

p.x=0; //illegal

p.z=10; //ok

return 0;

Using data in this manner defeats the idea of data hiding and should be avoided.
Defining function members
Member functions can be defined in two phases but both performing the same task
• Outside the class definition
• Inside the class definition

Outside the class definition

Member functions that are declared inside a class have to be defined separately outside the
class. The definitions are much like normal functions

Syntax

return_type class-name:: functionname(argument declaration){

function body

}
• The membership label class-name:: tells the compiler that the function function-name belong
to the class class-name which means the scope of the function is restricted to the class-name
specified in the header line.
• The symbol :: is called the scope resolution operator.
• With reference to the Item class members putdata() and getdata() may be defined as follows
Defining function members

void Item:: getdata(int a, float b){

number= a;

cost=b;

void Item:: putdata(void){

cout<<“Number:”<<number<<endl;

Cout<<“Cost: ”<<cost<<endl;

Member functions have some special characteristics that are often used in progam development

which are:
• Several classes can use the same function name and the membership label will resolve their
scope
• Member functions can access the private data of the class while a non-member function
cannot do so except for a friend function
• A member function can call another member function directly without using the dot operator
Inside the class defintion
• The second method involves defining the actual function inside the class
• When a member function is defined inside a class, we do not require to place a membership
label along with the function name. We use only small functions inside the class definition and
such functions are known as inline functions.
• In case of inline function the compiler inserts the code of the body of the function at the place
where it is invoked (called) and in doing so the program execution is faster but memory
penalty is there.
Inside the class defintion
class Item{

int number;

float cost;

public:

void getdata(int a, float b){

number= a;

cost= b;

void outdata(void){

cout<<number<<endl;

cout<<cost<<endl;

};
Types of members in a class
There are two types of members found within a class namely

I. Static

II. Instance

Static
• Data members and member functions of a class in C++, may be qualified as static. We can
have static data members and static member function in a class which are declared with the
static keyword
– Static data member
• It is generally used to store value common to the whole class. The static data
member differs from an ordinary data member in the following ways :
• (i) Only a single copy of the static data member is used by all the objects regardless
of the number of objects.
• (ii) It can be used within the class but its lifetime is the whole program.

• (iii) Does not require an object to be accessed instead it uses a scope resolution
opearator
Example creating an object using a pointer variable
class Circle{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r) {
radius = r;
}
double Circle::getArea(){
return radius * radius * (22.0/7);
}
double Circle:: getCircumference(){
return 2 * radius * (22.0/7);
}
 
 
 
 
Example creating an object using a pointer variable
Method 1: Creating an object
int main(){
Circle c1,c2(7);
cout<<“The area of c1:”<<c1. getArea()<<“\n”;
//c1.raduis = 5;//syntax error
c1.setRadius(5);
cout<<“The circumference of c1:”<< c1.getCircumference()<<“\n”;
cout<<“The Diameter of c2:”<<c2.getDiameter()<<“\n”;
return 0;
}
Method 2: Pointers

int main( ) {
Circle c(7);
Circle *cp1 = &c;
Circle *cp2 = new Circle (7);

cout<<“The area of cp2:”<<cp2->getArea()<<endl;

}
 
 
 
 
Static Variables
• - Shared by all objects of the class

• -Like a “global variable” among objects of the class

1. Must be declared in class with keyword static:

class IntVal {

public:

intVal(int val = 0) { value = val; valCount++ }

int getVal();

void setVal(int);

private:

int value;

static int valCount;

};
Static Variables
2) Must be defined outside of the class:

class IntVal{

//In-class declaration

static int valCount;

//Other members not shown

};

//Definition outside of class

int IntVal::valCount = 0;
Static Variables
3) Can be accessed or modified by any object of the class: Modifications by one object are visible to all
objects of the class:

intVal val1, val2;

class MyCircle{

public:

double r;

static double pi;

};

double MyCircle::pi=3.14;

- this initialisation will only take place once throughout the life of the application

To access the static member outside the class

int main(){

double p= MyCircle:: pi;

- this means that we don’t have to create an instance of the class in order to access static members
Static Variables
• For making a data member static, we require :
(a) Declare it within the class.
(b) Define it outside the class.
• For example
class student
{
Static int count; //declaration within class
-----------------
-----------------
-----------------
};

• The static data member is defined outside the class as :

int student :: count; //definition outside class

• The definition outside the class is a must.

• We can also initialize the static data member at the time of its definition as:

• int student :: count = 0;


Static Member Functions
Static Member Function: A static member function can access only the
static members of a class. We can do so by putting the keyword static before
the name of the function while declaring it for example,
class student
{
static int count;
-----------------
public :
-----------------
-----------------
static void showcount (void) //static member function
{
cout<<”count=”<<count<<”\n”;
}
};
int student ::count=0;
Static Member Functions
• Here we have put the keyword static before the name of the function shwocount ().
• In C++, a static member function differs from the other member functions in the following
ways:
• (i) Only static members (functions or variables) of the same class can be accessed by a
static member function.
• (ii) It is called by using the name of the class rather than an object as given below:
Name_of_the_class :: function_name
For example, student::showcount();

• We use static variables to maintain values common to the entire class for example we can
use a static data member as a counter that records the occurrences of all objects
Static Member Functions
• Can be used to access static member variables

• Can be called before any objects are created

1)Declared with static before return type:

class IntVal{

public:

static int getValCount() { return valCount; }

private:

int value;

static int valCount;

};

2) Can be called independently of class

objects, through the class name:

cout << IntVal::getValCount();


Static Member Functions
3) Can be called before any objects of the class have been created

4) Used mostly to manipulate static member variables of the class

#include <iostream>

using namespace std;

class MyCircle{

public:

double r;

static double pi;

static double area(double a){ return a * a* pi; };

};

double MyCircle::pi=3.14;

int main(){

double p= MyCircle::pi;

double a= MyCircle::area(2);

cout<<"Pi is"<<p<<endl;

cout<<"Area is:"<<a;

return 0; }
Static Member Functions
#include<iostream>

using namespace std;

class Item{

static int count;

int number;

public:

void getdata(int a){

number=a;

count++;

void getcount(void){

cout<<“count:”<<endl;

cout<<count<<endl;

int item::count;

Int main( ){

Item a,b,c; //count is intialised to zero

a.getcount(); //display count


Static Member Functions

a.getdata(1000);

b.getdata(2000);

c.getdata(3000);

cout<<“After reading data”<<endl;

a.getcount();

b.getcount();

c.getcount();

return 0;

}
Instance members
• Data members and member functions of a class in C++, may be qualified as instance. We can
have instance data members and instance member functions in a class.

Instance data members


• Multiple copies exist in a class as each object has its own copy.
• Requires an object to be accessed
• Changes made by an object will not affect other objects accessing the same instance variable

Instance functions
• In contrast instance methods can use both static and instance members of a class
class MyCircle{
public:
double r;
static double pi;
static double area(double a){ return a * a* pi; };
double getArea(){ return pi*r*r; }
};
double MyCircle::pi=3.14;
int main(){
double p= MyCicle:: pi;
double a= MyCircle::Area(1);
}
Arrays as class members
• The array can be used as member variables in a class e.g

const int size=10;

class array{

int a[size]; //a is int type array

public:

void setval(void);

void display(void);

};

The array element a[] can be used by member function to perform operations on it
• Consider a shopping list of items for which we place an order with a dealer every month.

The list consists of details such as codenumber and price of each item. We may want to perform

operations such as adding, deleting and print the total value of the order which can be

represented as follows
Arrays as class members
#include <iostream>

using namespace std;

const int m=50;

class ITEMS{

int itemCode[m];

float itemPrice[m];

int count;

public:

void CNT(void){ count =0; }

void getitem(void){

cout<<“Enter item code”<<endl;

cin>>itemCode[count];

cout<<“Enter item cost”<<endl;

cin>>itemPrice[count];

count++;

}
Arrays as class members
void displaysum(){

float sum=0;

for(int i=0; i<count; i++)

Sum= sum+ itemPrice[i];

cout<<“Total Value: ”<<sum<<endl;

void remove(void) {

int a;

cout<<“Enter item code:”<<endl;

Cin>>a;

for(int i=0; i<count; i++)

if(itemCOde[i]==a)

itemPrice[i]=0;

}
Arrays as class members
void displayItems(){
cout<<“Code Price”;
for(int i=0; i<count; i++){
cout<<itemCode[i]<< “ ” <<itemPrice[i]<<endl;
}
int main(){
ITEMS order;
order.CNT();
int x;
do{
cout<<“You can do the foollowing…..”<<endl;
cout<<“1: Add an item”<<endl;
cout<<“2: Display total value”<<endl;
cout<<“3: Delete an item”<<endl;
cout<<“4: Display all items”<<endl;
cout<<“5: Quit”<<endl;
cout<<“What is your option”<<endl;
cin>>x;
Arrays as class members
switch(x){
case 1: order.getitem(); break;
case 2: order.dispalySum(); break;
case 3: order.remove(); break;
case 4: order.displayItems(); break;
case 5: break;
default: cout<<“Error input try again”<<endl;
}
while(x!=5);
return 0;
}
Objects as Function Arguments
• An object may be used as a function argument in two ways
– A copy of the entire object is passed to the function(pass by value)
– Only the address of the object is transferred to the function(pass by reference)
• The pass by value method will pass a copy of the object to the function and any changes
made to the object inside the function will not affect the object used to call the function
• The pass by reference method is when an address of the object is passed the called function
works directly on the actual object used in the call. This means that any changes made to the
object inside the function will reflect on the actual object. The passbyreference is more
efficient since it requires to pass only the address of the object and the entire object
Objects as Function Arguments
#include<iostream>

using namespace std;

class time{

int hours, minutes;

public:

void gettime(int h, int m){

hours= h; minutes=m;

void puttime(){

cout<<hours<< and “<< minutes << “minutes ”<<endl;

void sum(time t1, time t2){

minutes= t1.minutes + t2.minutes;

hours= minutes/60;

minutes= minutes% 60

hours= hours+ t.minutes+ t2. hours;

int main(){

time T1, T2,T3;

T1.gettime(2,45);

T2.gettime( 3,30);
Objects as Function Arguments
T3.sum(T1,T2); //T3= T1+T2

cout<<“T1==”;

T1.putme();

cout<<“\n T2==”;

T2.putme();

cout<<“\n T3==”;

T3.putme();

return 0;

}
Objects as Function Arguments
• The type and scope of each static member variable must be defined outside the class
definition.
• This is important as static data members are stored separately rather than as part of an
object.
• They are associated with the class itself rather than with any class object hence they are
called class variables. The static variable count is initialized to zero when the objects are
created.
• The count is incremented whenever the data is read into an object. Data is read into objects
three times, the variable count is incremented three times as one copy of count is shared by
all three objects.
• All three output statements cause the value of 3 to be displayed.

Constructors
• A constructor (having the same name as that of the class) is a member function which is
automatically used to initialize the objects of the class type with legal initial values.

It has the following properties


• Same name as the class
• No return type
• Can have parameters or no parameters or default
• Can be overloaded
• Automatically invoked when the object is created. When invoked the signature of the call
must match the constructor definition
• Always declared under the public section
• Cannot be inherited
• They cannot be virtual

Syntax of a cconstructor
• It is defined like other member functions of the class, i.e., either inside the class definition or
outside the class definition. For example,
Syntax of a constructor
#include <iostream.h>
using namespace std;
class rectangle {
private :
float length, breadth;
public:
rectangle ()//constructor definition
{
//displayed whenever an object is created
cout<<”I am in the constructor”;
length-10.0;
breadth=20.5;
}
float area()
{
return (length*breadth);
}
};
int main()
{
rectangle rect; //object declared
cout<<”\n The area of the rectangle with default parameters is:”<<rect.area()<<”sq.units\n”;
}
Types of constructor
1. Overloaded constructor
• Besides performing the role of member data initialization, constructors are no different from other functions. This
included overloading also. In fact, it is very common to find overloaded constructors. For example, consider the following
program with overloaded constructors for the figure class :
#include<iostream.>
class figure {
private:
float radius, side1,side2,side3; //data members
public:
figure(float r) { //constructor for circle
radius=r;
}
figure (float s1,float s2) { //constructor for rectangle
side1=s1;
side2=s2;
side3=radius=0.0; //has no significance in rectangle strcpy(shape,”rectangle”);
}
figure (float s1, floats2, float s3) //constructor for triangle
{
side1=s1;
side2=s2;
side3=s3;
radius=0.0;
}
Types of constructor
void area(){ //calculate area
float ar,s;
if(radius==0.0)
{
if (side3==0.0)
ar=side1*side2;
else
ar=3.14*radius*radius;
cout<<”\n\nArea of the “<<shape<<”is :”<<ar<<”sq.units\n”;
}
};
int main() {
figure circle(10.0); //objrct initialized using constructor
figure rectangle(15.0,20.6);//objrct initialized using onstructor
figure Triangle(3.0, 4.0, 5.0); //objrct initialized using constructor
Rectangle.area();
Triangle.area();
return 0;
}
Types of constructor
2 Copy Constructor
• It is of the form classname (classname &) and used for the initialization of an object from
another object of same type. For example,
class fun {
float x,y;
public:
fun (floata,float b){//constructor
x = a;
y = b;
}
fun (fun &f){ //copy constructor
cout<<”\ncopy constructor at work\n”;
x = f.x;
y = f.y;
}
void display (void) {
cout<<””<<y<<end1;
}
};
Here we have two constructors, one copy constructor for copying data value of a fun object to
another and other one a parameterized constructor for assignment of initial values given.
Dynamic Initialisation of objects
In C++, the class objects can be initialized at run time (dynamically). We have the flexibility of
providing initial values at execution time. The following program illustrates this concept:
#include <iostream>
using namespace std;
class employee {
int empl_no;
float salary;
public:
Employee() {} //default constructor
Employee(int empno,float s){//constructor with arguments
Empl_no=empno;
Salary=s;
}
Employee (employee &emp){ //copy constructor
cout<<”\ncopy constructor working\n”;
empl_no=emp.empl_no;
salary=emp.salary;
}
void display (void) {
Cout<<”\nEmp.No:”<<empl_no<<”salary:”<<salary<<end1;
}
};
Dynamic Initialisation of objects
int main()
{
int eno;
float sal;
cout<<”Enter the employee number and salary\n”;
cin>>eno>>sal;
employee obj1(eno,sal);//dynamic initialization of object

cout<<”\nEnter the employee number and salary\n”;


cin>eno>>sal;

employee obj2(eno,sal); //dynamic initialization of object

obj1.display(); //function called


employee obj3=obj2; //copy constructor called
obj3.display();
getch();
}
Constructor with Default arguments
In C++, we can define constructor s with default arguments. For example, The following code
segment shows a
constructor with default arguments:
class add {
private:
int num1, num2,num3;
public:
//Default constructor definition
add(int n1, int n2) {
num1=n1;
num2=n2;
num3=n0;
}
void sum() {
num3=num1+num2;
}
void add::display () {
cout<<”\nThe sum of two numbers is “<<num3<<end1;
}
Constructor with Default arguments
Using the previous code objects of type add can be created with no initial values, one initial

values or two initial values.

For Example,

add obj1, obj2(5), obj3(10,20);

Here, obj1 will have values of data members num1=0, num2=0 and num3=0

Obj2 will have values of data members num1=5, num2=0 and num3=0

Obj3 will have values of data members num1=10, num2=20 and num3=0
Destructors
Special Characteristics of Destructors

Some of the characteristics associated with destructors are :

(i) These are called automatically when the objects are destroyed.

(ii) Destructor functions follow the usual access rules as other member functions.

(iv) No argument and return type (even void) permitted with destructors.

(v) These cannot be inherited.

(vi) Static destructors are not allowed.

(vii) Address of a destructor cannot be taken.

(viii) A destructor can call member functions of its class.


Destructors
The syntax for declaring a destructor is :
-name_of_the_class()
{
}
• So the name of the class and destructor is same but it is prefixed with a ~ (tilde).
• It does not take any parameter nor does it return any value.
• Overloading a destructor is not possible and can be explicitly invoked. In other words, a class
can have only one destructor. A destructor can be defined outside the class. The following
program illustrates this concept :
#include<iostream.h>
using namespace std;
class add {
private :
int num1,num2,num3;
public :
//Destructor definition ~add()
~add(void) { //destructor called automatically at end of program
num1=num2=num3=0;
cout<<”\nAfter the final execution, me, the object has entered in the” <<”\ndestructor to destroy myself\n”;
}
Destructors
//Constructor definition add()
add(int n1,int n2) {
num1=n1;
num2=n2;
num3=0;
}
//function definition sum ()
void sum() {
num3=num1+num2;
}
//function definition display ()
void add::display () {
cout<<”\nThe sum of two numbers is “<<num3<<end1;
}
int main() {
add obj1,obj2(5),obj3(10,20): //objects created and initialized clrscr();
obj1.sum(); //function call
obj2.sum();
obj3.sum();
cout<<”\nUsing obj1 \n”;
obj1.display(); //function call
cout<<”\nUsing obj2 \n”;
obj2.display();
cout<<”\nUsing obj3 \n”;
obj3.display();
}
const objects
• We may create and use constant objects using const keyword before object declaration. For example
we may create X as a constant object as follows:
const matrix X(m,n); // object X is a constant
• Any attempt to modify the values of m and n will generate compile time errors. A constant object can
only call const member functions.
• Any attempt to invoke non-const member functions will generate an error.
Friendship in c++
• If functions or individual classes are used in conjunction with another class, you may want
to grant
them access to the private and all the members of that class. This is made possible by a friend
declaration,
which eliminates data encapsulation in certain cases.
• Even though the prototypes for friend functions appear in the class definition, friends are
not member
functions.
• A friend can be a function, function template, or member function, or a class or class
template, in
which case the entire class and all of its members are friends.
• Implementing a friend function can be done in two ways
– In the same class
– Defining a prototype in the class then defining it outside
Friend functions
• Need for friendship
• A function that is not a member or an external class will not be able to access the private
data. A programmer may have a situation where he or she would need to access private
data from non-member functions and external classes. For handling such cases, the concept
of Friend functions is a useful tool
Friendship in c++
Properties of a friend function
• Declared with the friend keyword
• One of its arguments is the object of the class to be used in accessing class members
• In the function body we use the object to access class members i.e the (dot.) operator
• When calling the friend function within the main we do not use the dot operator but directly
call and pass the object as an argument ie
Triangle x;// object x of type Triangle
cout<<area(x)<<endl;// assuming the friend function is area
Friend function method 1
#include <iostream>
using namespace std;
class Box{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
// Member function definition
void Box::setWidth( double wid ){
width = wid;
}
// Note: printWidth() is not a member function of any class.
void printWidth( Box box ){
/* Because printWidth() is a friend of Box, it can directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}
int main( ){
Box box;
// set box width without member function
box.setWidth(10.0);
// Use friend function to print the wdith.
printWidth( box );
return 0;
}
Friend function method 2
#include <iostream>
using namespace std;
class Box{
double width;
public:
void setWidth( double wid ){
width = wid;
}
// Note: printWidth() is not a member function of any class.
void printWidth( Box box ){
/* Because printWidth() is a friend of Box, it can directly access any member of this class */
cout << "Width of box : " << box.width <<endl;}
};
int main( ){
Box box;
// set box width without member function
box.setWidth(10.0);
// Use friend function to print the wdith.
printWidth( box );
return 0;
}
Friend classes
• A friend class is a class whose members have access to the private or protected members of another class
• It is also possible to make an entire class a friend of another class. This gives all of the members of the friend class
access to the private members of the other class.
• If a class wants to use the members of another class it has to be declared with the friend keyword in the class i.e
class Y{
friend class X;
};
==========================================================================
class secret{
int x; //private access
friend class no_secret;
};
class no_secret{
secret t;
public:
no_secret(int x1) {
t.x= x1;
}
void display( ){
cout<<“Value of x: ”<<t.x<<endl;
} };
int main(){
no_secret r(10) ;
r.display();
return 0; }
Friend classes
#include <iostream>
using namespace std;
class exforsys {
private:
        int a,b;
public:
   void test( ){
                a=100;
                b=200;
    }
      friend int compute(exforsys e1);
};
int compute(exforsys e1){
  //Friend Function Definition which has access to private data
        return int(e1.a+e1.b)-5;
}
int main(){
        exforsys e;
        e.test();
        cout << "The result is:" << compute(e);
                //Calling of Friend Function with object as argument.
}// output is 295
 
 
 
Friend classes: Question
1. Create a class called shape which contains elements length and width. Include a
non-parameterised constructor to initialise the members and a method to compute the area of a
rectangle.
Given that perimeter class is a friend class to shape, demonstrate how you can compute the
perimeter of rectangle and display it together with the area from shape class.

You might also like