Professional Documents
Culture Documents
Software Crisis
Software Crisis
• 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.
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.
-Using a single cout statement with as many instances of \n as your program requires
will print out multiple lines of text.
#include <iostream>
int main()
return 0;
}
Structure of a program
Rearrange the code blocks to form a valid C++ program:
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>
int main(){
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
• they cannot start with a number but can start with an underscore character or a letter
• int myInt;
• int _my32Int;
Variable Assignation
• Syntax
• we can assign more than one variable of the same type in one line
• 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.
•
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
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.
int sum=0;
cout<<“Enter an element”<<endl;
cin>>*p;
sum+ =*p;
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
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
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
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 :
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{
public:
};
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
} 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
object-name.function-name(actual-arguments);
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
Member functions that are declared inside a class have to be defined separately outside the
class. The definitions are much like normal functions
Syntax
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
number= a;
cost=b;
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:
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);
}
Static Variables
• - Shared by all objects of the class
class IntVal {
public:
int getVal();
void setVal(int);
private:
int value;
};
Static Variables
2) Must be defined outside of the class:
class IntVal{
//In-class declaration
};
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:
class MyCircle{
public:
double r;
};
double MyCircle::pi=3.14;
- this initialisation will only take place once throughout the life of the application
int main(){
- 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
-----------------
-----------------
-----------------
};
• We can also initialize the static data member at the time of its definition as:
• 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
class IntVal{
public:
private:
int value;
};
#include <iostream>
class MyCircle{
public:
double r;
};
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>
class Item{
int number;
public:
number=a;
count++;
void getcount(void){
cout<<“count:”<<endl;
cout<<count<<endl;
int item::count;
Int main( ){
a.getdata(1000);
b.getdata(2000);
c.getdata(3000);
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 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
class 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>
class ITEMS{
int itemCode[m];
float itemPrice[m];
int count;
public:
void getitem(void){
cin>>itemCode[count];
cin>>itemPrice[count];
count++;
}
Arrays as class members
void displaysum(){
float sum=0;
void remove(void) {
int a;
Cin>>a;
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>
class time{
public:
hours= h; minutes=m;
void puttime(){
hours= minutes/60;
minutes= minutes% 60
int main(){
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.
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
For Example,
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
(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.