OOPs
The prime purpose of C++ programming was to add object orientation to the C programming language, which is in itself one of the most powerful programming languages.
The core of the pure object-oriented programming is to create an object, in code, that has certain properties and methods. While designing C++ modules, we try to see whole world in the form of objects. For example a car is an object which has certain properties such as color, number of doors, and the like. It also has certain methods such as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented programming:
Object
This is the basic unit of object oriented programming. That is both data and function that operate on data are bundled as a unit called as object.
Class
When you define a class, you define a blueprint for an object. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and maintained. Similar way, C++ classes provides different methods to the outside world without giving internal detail about those methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place. While working with procedural languages, it is not always clear which functions work on which variables but object-oriented programming provides you framework to place the data and the relevant functions together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name suggests Inheritance is the process of forming a new class from an existing class that is from the existing class called as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce the code size.
Polymorphism
The ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions is called polymorphism. Poly refers to many. That is a single function or an operator functioning in many ways different upon the usage is called polymorphism.
Overloading
The concept of overloading is also a branch of polymorphism. When the exiting operator or function is made to operate on new data type, it is said to be overloaded.
2. Internal EvaluationInternal Evaluation
Mid- Term Exam 15 Marks
Assignment 6 //
Quizzes/Tests 9 //
Presentation 10 //
Major Assignment 10 //
Total internal Marks 50 //
Final Term Examination
Final Term Exam 50 //
Total Marks 100 //
3. Text Books:Text Books:
Any book on Object OrientedAny book on Object Oriented
ProgrammingProgramming
Herbert Schildt, C++ form the Ground Up, 4TH
Edition.
(Harvey & Paul) Deitel & Deitel C++ How to Program, 6/E
Reference Books:
4. Brief History of C++Brief History of C++
In 1967, BCPL (Basic Combined Programming
Language) language was developed by Martin
Richards.
The BCPL language was used to write operating systems
and compilers.
After two years, Ken Thomsan developed “B” programming language.
B programming language had advance features as
compared with BCPL. Both BCPL and B were
“type less” languages.
5. Brief History of C++Brief History of C++
What does “type less” languages mean ?
It means you do not have to declare the data type
explicitly.
For example: declaring integers . . . if it's TYPED then you declare as an
integer your variable.
If “TYPELESS”, you can do
$var=39
and it will be interpreted as an integer (it will be treated as string if double-
quoted, however).
6. Brief History of C++Brief History of C++
In the early 1970s, Dennis Ritchie of Bell Laboratories
was engaged in a project to develop a new operating
system.
Ritchie discovered that in order to accomplish his task he
needed the use of a programming language that was
concise and that produced compact and speedy programs.
This need led Ritchie to develop the programming
language called C.
7. Brief History of C++Brief History of C++
In the early 1980's, a newprogramming language was
created which was based upon the C language.
This new language was developed by Bjarne Stroustrup
and was called C++.
Stroustrup states that the purpose of C++ is to make
writing good programs easier and more pleasant for the
individual programmer.
When he designed C++, he added OOP (Object Oriented
Programming) features to C without significantly
changing the C component.
8. Brief History of C++Brief History of C++
There are several versions of the C++ language, of which
Visual C++ is one of them. Other dialects include Borland
C++, Turbo C++, and Code Warrior (Mac).
All of these software packages enable you to create computer
programs with C++, but they all implement the C++ language
in a slightly different manner.
In an attempt to maintain portability of both the C and C++
languages, the American National Standards Institute (ANSI)
developed a standard of consistency for C and C++
programming.
Thus C++ is a "relative" (called a superset) of C, meaning
that any valid C program is also a valid C++ program.
9. SIMULA 1 (1962) and Simula 67 (1967) [SIMULA 1 (1962) and Simula 67 (1967) [Ole-John Dahl and KristenOle-John Dahl and Kristen
Nygaard] were the first languages with object-oriented featuresNygaard] were the first languages with object-oriented features BUTBUT
less object-oriented features when compared to C++less object-oriented features when compared to C++
after it was enriched in 1990‘safter it was enriched in 1990‘s
Brief History of OOPBrief History of OOP
“Believed that”
C++ was the first Object-Oriented Language
However !
10. C++ was powerful enough as compared to C languageC++ was powerful enough as compared to C language
Major limitation was its complexity.Major limitation was its complexity.
Java Programming [James Gosling, Bill Joy etc 1991].Java Programming [James Gosling, Bill Joy etc 1991].
Java quickly grew in popularity with the growth of WWW.Java quickly grew in popularity with the growth of WWW.
Java was replaced by C# by Microsoft in 2000.Java was replaced by C# by Microsoft in 2000.
Brief HistoryBrief History
11. PROCEDURAL PROGRAMMINGPROCEDURAL PROGRAMMING
Procedural programming is a classic programmingProcedural programming is a classic programming
where the program language is used to tell thewhere the program language is used to tell the
computer EXACTLY what to do - step by step.computer EXACTLY what to do - step by step.
A program in a procedural language is a list ofA program in a procedural language is a list of
instruction. That is, each statement in the languageinstruction. That is, each statement in the language
tell the computer to do something.tell the computer to do something.
The focus of procedural programming is to breakThe focus of procedural programming is to break
down a programming task into a collection ofdown a programming task into a collection of
variables, data structures, and subroutines.variables, data structures, and subroutines.
12. PROCEDURAL PROGRAMMINGPROCEDURAL PROGRAMMING
Examples of procedural languages include Fortran,Examples of procedural languages include Fortran,
COBOL and C, which have been around since theCOBOL and C, which have been around since the
1960s and 70s. 1960s and 70s.
13. Limitations ofLimitations of
Procedural ProgrammingProcedural Programming
The lack of encapsulation in structuredThe lack of encapsulation in structured
programming results in longer programs due to theprogramming results in longer programs due to the
repetition of code in several places within a singlerepetition of code in several places within a single
program.program.
This long code in turn makes it difficult to effectivelyThis long code in turn makes it difficult to effectively
locate and fix errors in the program.locate and fix errors in the program.
Structured programming lacks information hidingStructured programming lacks information hiding
and sometimes there is a clash of variables whenand sometimes there is a clash of variables when
different parts of the program overwrite the samedifferent parts of the program overwrite the same
variablevariable
14. Limitations ofLimitations of
Procedural ProgrammingProcedural Programming
Data EncapsulationData Encapsulation
Data encapsulation, sometimes referred to as dataData encapsulation, sometimes referred to as data
hiding, is the mechanism whereby thehiding, is the mechanism whereby the
implementation details of a class are kept hiddenimplementation details of a class are kept hidden
from the user. The user can only perform afrom the user. The user can only perform a
restricted set of operations on the hidden membersrestricted set of operations on the hidden members
of the class by executing special functionsof the class by executing special functions
commonly called commonly called methodsmethods. The actions performed. The actions performed
by the methods are determined by the designer ofby the methods are determined by the designer of
the class. the class.
15. Limitations ofLimitations of
Procedural ProgrammingProcedural Programming
A popular example you’ll hear for encapsulation is driving a car. Do you needA popular example you’ll hear for encapsulation is driving a car. Do you need
to know exactly how every aspect of a car works (engine, carburettor,to know exactly how every aspect of a car works (engine, carburettor,
alternator, and so on)? No - you need to know how to use the steering wheel,alternator, and so on)? No - you need to know how to use the steering wheel,
brakes, accelerator, and so on.brakes, accelerator, and so on.
Another example is searching for a value in an array. In Java, you can do theAnother example is searching for a value in an array. In Java, you can do the
following:following:
The above code will return true if the value 11 is in myArray, otherwise it willThe above code will return true if the value 11 is in myArray, otherwise it will
return false. How does the contains() method work? Which searchingreturn false. How does the contains() method work? Which searching
technique does it use? Does it pre-sort the array before searching? Thetechnique does it use? Does it pre-sort the array before searching? The
answer is answer is it doesn't matterit doesn't matter because the exact implementation of the method is because the exact implementation of the method is
hidden.hidden.
16. Limitations ofLimitations of
Procedural ProgrammingProcedural Programming
Structured programming is not suitable for theStructured programming is not suitable for the
development of large programs and does not allowdevelopment of large programs and does not allow
reusability of any set of codes.reusability of any set of codes.
17. Object-Oriented Programming vs.Object-Oriented Programming vs.
Procedural Programming cont…Procedural Programming cont…
One alternative to procedural programming is objectOne alternative to procedural programming is object
oriented programming.oriented programming.
Object oriented programming is meant to address theObject oriented programming is meant to address the
difficulties with procedural programming. difficulties with procedural programming.
In object oriented programming, the main modules in aIn object oriented programming, the main modules in a
program are classes, rather than procedures. The object-program are classes, rather than procedures. The object-
oriented approach lets you create classes and objects thatoriented approach lets you create classes and objects that
model real world objects.model real world objects.
18. ClassesClasses
ClassesClasses
Classes declaration & definitionClasses declaration & definition
Members of a classMembers of a class
Access SpecifiersAccess Specifiers
ObjectsObjects
Declaring objects of a classDeclaring objects of a class
Calling members of a ClassCalling members of a Class
Defining member functions outside the classDefining member functions outside the class
Storage of objects in memory.Storage of objects in memory.
19. ClassClass
The most powerful feature of C++ programming language is that itThe most powerful feature of C++ programming language is that it
support OOP.support OOP.
In OOP , the computer program is divided into object.In OOP , the computer program is divided into object.
OOP language is an easy and flexible approach for designing andOOP language is an easy and flexible approach for designing and
organizing the program.organizing the program.
The program is designed by using Class.The program is designed by using Class.
21. Classes vs StructureClasses vs Structure
Classes and Structure are similar.Classes and Structure are similar.
Both have same syntax.Both have same syntax.
ButBut
““structures are exclusively used to hold data, whereasstructures are exclusively used to hold data, whereas
Class is used to hold both Data and Functions”.Class is used to hold both Data and Functions”.
22. ClassClass
A Class is a user defined data type.A Class is a user defined data type.
It is therefore used to declare its variables or instancesIt is therefore used to declare its variables or instances
23. ObjectObject
The variable or instances of the class are calledThe variable or instances of the class are called
Objects.Objects.
24. Declaration of aDeclaration of a
classclass
class name_of_classclass name_of_class
{{
// definition of a class// definition of a class
}}
25. class Dateclass Date
{{
Private:Private:
int day ;int day ;
int month ;int month ;
int year ;int year ;
Public:Public:
Void print(void) { // body of functionVoid print(void) { // body of function
}}
} ;} ;
ExampleExample
26. main ( )main ( )
{{
Date mydate ;Date mydate ;
}}
Declaration of ObjectDeclaration of Object
27. main ( )main ( )
{{
Date mydate ;Date mydate ;
// manipulate the data members// manipulate the data members
mydate.day ;mydate.day ;
mydate.month ;mydate.month ;
mydate.year ;mydate.year ;
mydate.print();mydate.print();
}}
Calling Members throughCalling Members through
ObjectObject
28. Normally two types of accessNormally two types of access
specifiers:specifiers:
PrivatePrivate
PublicPublic
Member Access SpecifiersMember Access Specifiers
29. The member of the class that canThe member of the class that can
be accessed only from within thebe accessed only from within the
class are called Private membersclass are called Private members
PrivatePrivate
30. Default visibility ofDefault visibility of
all data andall data and
functionfunction
inside a class isinside a class is
31. The member of the class that canThe member of the class that can
be accessed both from inside thebe accessed both from inside the
class as well as outside the classclass as well as outside the class
are called Public membersare called Public members
PublicPublic
32. class Dateclass Date
{{
private :private :
// private data and functions// private data and functions
public :public :
// public data and functions// public data and functions
};};
33. class Dateclass Date
{{
private :private :
int day , month , year ;int day , month , year ;
public :public :
setMonth ( ) ;setMonth ( ) ;
print ( ) ;print ( ) ;
};};
Date ClassDate Class
35. Programming Example 1Programming Example 1
Write a program to input and printWrite a program to input and print
date on the screen by using class.date on the screen by using class.
#include<iostream>#include<iostream>
using namespace std;using namespace std;
class edate{class edate{
private:private:
int y,m,d;int y,m,d;
public:public:
void gdate (void){void gdate (void){
cout<<"Enter year:";cout<<"Enter year:";
cin>>y;cin>>y;
cout<<"Enter months:";cout<<"Enter months:";
cin>>m;cin>>m;
cout<<"Enter days:";cout<<"Enter days:";
cin>>d;}cin>>d;}
void printdate(void){void printdate(void){
cout<<"Date is:"<<endl;cout<<"Date is:"<<endl;
cout<<y<<"/"<<m<<"/"<<d<<endl;cout<<y<<"/"<<m<<"/"<<d<<endl;
}}
};};
main(){main(){
edate c;edate c;
c.gdate();c.gdate();
c.printdate();c.printdate();
}}
36. Programming Example 2Programming Example 2
/*Write a program to input the name of student and/*Write a program to input the name of student and
marks of three subjects. Calculate the totalmarks of three subjects. Calculate the total
marks and average marks. Each subject has amarks and average marks. Each subject has a
maximum of 100 marks.*/maximum of 100 marks.*/
#include<iostream>#include<iostream>
using namespace std;using namespace std;
class student {class student {
private:private:
char name[15];char name[15];
float s1,s2,s3,total,avg;float s1,s2,s3,total,avg;
public:public:
void getrec (void){void getrec (void){
cout<<"Enter name of acout<<"Enter name of a
student :";cin>>name;student :";cin>>name;
cout<<"Enter marks of istcout<<"Enter marks of ist
subject:";cin>>s1;subject:";cin>>s1;
cout<<"Enter marks of secondcout<<"Enter marks of second
subject:";cin>>s2;subject:";cin>>s2;
cout<<"Enter marks of thirdcout<<"Enter marks of third
subject:";cin>>s3;subject:";cin>>s3;
total=s1+s2+s3;avg=total/3.0;}total=s1+s2+s3;avg=total/3.0;}
void show(void){void show(void){
cout<<"Name of student is"<<name<<endl;cout<<"Name of student is"<<name<<endl;
cout<<"Marks in subject 1= "<<s1<<endl;cout<<"Marks in subject 1= "<<s1<<endl;
cout<<"Marks in subject 2 ="<<s2<<endl;cout<<"Marks in subject 2 ="<<s2<<endl;
cout<<"Marks in subject 3 ="<<s3<<endl;cout<<"Marks in subject 3 ="<<s3<<endl;
cout<<"Total Marks are "<<total<<endl;cout<<"Total Marks are "<<total<<endl;
cout<<"Average is equal = "<<avg<<endl;cout<<"Average is equal = "<<avg<<endl;
}};main(){}};main(){
student s;student s;
s.getrec();s.getrec();
s.show();s.show();
}}
37. Programming Example 3Programming Example 3
/*Write a program by using a class to input two/*Write a program by using a class to input two
values using a member function of a class.values using a member function of a class.
Display the sum of the two values by usingDisplay the sum of the two values by using
another member function of the class.another member function of the class.
*/*/
#include<iostream>#include<iostream>
using namespace std;using namespace std;
class sum {class sum {
private:private:
int n,m;int n,m;
public:public:
void get (int a ,int b){void get (int a ,int b){
n=a;m=b;n=a;m=b;
}}
void display (void){void display (void){
cout<<"sum="<<n+m;cout<<"sum="<<n+m;
}}
};};
main(){main(){
sum s;sum s;
int x, y;int x, y;
cout<<"Enter first value:";cout<<"Enter first value:";
cin>>x;cin>>x;
cout<<"Enter Second value:";cout<<"Enter Second value:";
cin>>y;cin>>y;
s.get(x,y);s.get(x,y);
s.display();s.display();
}}
38. Members functions of a class can also be defined outside the class. In thisMembers functions of a class can also be defined outside the class. In this
case, only the prototype of the member function is declared inside thecase, only the prototype of the member function is declared inside the
class.class.
The member functions are defined outside the class in the similar was as aThe member functions are defined outside the class in the similar was as a
user defined functions are defined. However, the scope resolution operatoruser defined functions are defined. However, the scope resolution operator
(::) is used in the member function declarator to define the function of class(::) is used in the member function declarator to define the function of class
outside the class.outside the class.
General Syntax:General Syntax:
Type class_name :: function_name(argument){Type class_name :: function_name(argument){
//body//body
}}
Defining Member Functions OutsideDefining Member Functions Outside
the Classthe Class
39. void Date :: display ( )void Date :: display ( )
{{
cout << day << “/ " << month << “/ " << year ;cout << day << “/ " << month << “/ " << year ;
}}
ExampleExample
40. Programming Example 4Programming Example 4
// Write a program to find volume of a BOX using Scope// Write a program to find volume of a BOX using Scope
resolution operatorsresolution operators
#include<iostream>#include<iostream>
using namespace std;using namespace std;
class Boxclass Box
{ public:{ public:
double length; // Length of a boxdouble length; // Length of a box
double breadth; // Breadth of a boxdouble breadth; // Breadth of a box
double height; // Height of a boxdouble height; // Height of a box
// Member functions declaration// Member functions declaration
double getVolume(void);double getVolume(void);
void setLength( double len );void setLength( double len );
void setBreadth( double bre );void setBreadth( double bre );
void setHeight( double hei );};void setHeight( double hei );};
// Member functions definitions// Member functions definitions
double Box::getVolume(void)double Box::getVolume(void)
{return length * breadth * height;{return length * breadth * height;
}void Box::setLength( double len )}void Box::setLength( double len )
{{
length = len;length = len;
}}
void Box::setBreadth( double bre )void Box::setBreadth( double bre )
{ breadth = bre;{ breadth = bre;
}}
void Box::setHeight( double hei )void Box::setHeight( double hei )
{ height = hei;{ height = hei;
}}
// Main function for the program// Main function for the program
int main( )int main( )
{ Box Box1; // Declare Box1 of type Box{ Box Box1; // Declare Box1 of type Box
double volume = 0.0; // Store the volume of a box heredouble volume = 0.0; // Store the volume of a box here
// box 1 specification// box 1 specification
Box1.setLength(6.0);Box1.setLength(6.0);
Box1.setBreadth(7.0);Box1.setBreadth(7.0);
Box1.setHeight(5.0);Box1.setHeight(5.0);
// volume of box 1// volume of box 1
volume = Box1.getVolume();volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;cout << "Volume of Box1 : " << volume <<endl;
return 0;return 0;
}}
41. When an object of a class is created , a space is reserved in theWhen an object of a class is created , a space is reserved in the
computer memory to hold its data members. Similarly, separatecomputer memory to hold its data members. Similarly, separate
memory spaces are reserved for each class object.memory spaces are reserved for each class object.
The member functions of a class are, however. stored at only one placeThe member functions of a class are, however. stored at only one place
in the computer memory. All objects of the class use the samein the computer memory. All objects of the class use the same
member functions to process data.member functions to process data.
Therefore, while each object has a separate memory space for dataTherefore, while each object has a separate memory space for data
members, the member functions of a class are stored in only onemembers, the member functions of a class are stored in only one
place and are shared by all objects of the class.place and are shared by all objects of the class.
Storage of objects in memoryStorage of objects in memory