SlideShare a Scribd company logo
1 of 59
UNIT-VUNIT-V
1. introduction to c++ programming –1. introduction to c++ programming –
2. object oriented programming concepts,2. object oriented programming concepts,
3.Structured Vs OOP.3.Structured Vs OOP.
4.Classes and objects-class definition4.Classes and objects-class definition
5. Objects5. Objects
6. class scope and accessing members6. class scope and accessing members
7. Constructors-default constructor7. Constructors-default constructor
8. parameterized constructor8. parameterized constructor
9. constructor initialization list9. constructor initialization list
10.copy constructor10.copy constructor
11. Destructors11. Destructors..
Sathi Durga Devi, Department of
IT,SNIST
History of C++
 Extension of C
 Early 1980s: Bjarne Stroustrup (Bell Laboratories)
 Originally named “C with Classes”.
 Provides capabilities for object-oriented programming.
• Objects: Reusable Software Components
– Model items in real world
• Object-Oriented Programs
– Easy to understand, correct and modify
 Hybrid language
• C-like style
• Object-oriented style
• Both
Sathi Durga Devi, Department
of IT,SNIST
Procedure-Oriented programming
/ structured oriented programming
• To do a particular task the list of instructions are given to the
computer to follow, and organizing these instructions into
groups known as functions. Such languages are called
procedure- oriented programming.
• COBOL, FORTRAN, C is commonly known as procedure-
oriented programming (POP).
Sathi Durga Devi, Department of
IT,SNIST
Procedure-oriented programming
Sathi Durga Devi, Department of
IT,SNIST
Main program
Function-5
Function-2 Function-3
Function-4
Function-1
Function-6 Function-7 Function-8
Relationship of data and functions in
procedural programming
Sathi Durga Devi, Department of
IT,SNIST
Global data Global data
Function-1
Local data
Function-2
Local data
Function-3
Local data
/* Write a c program to implement the selection sort*/
#include<stdio.h>
void select_sort(int x[], int size);
int find_min(int x[],int k,int size);
int n,size,a[10],i,j,x,k,pass,temp,min,loc; -> global data
void main() {
printf("nEnter the size of array: ");
scanf("%d",&n);
printf("nEnter the array elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("nElements in array before swapping: ");
for(i=0;i<n;i++)
printf("t%d",a[i]);
printf("n");
select_sort(a,n);
printf("nntElements after swapping: ");
for(i=0;i<n;i++)
printf("t%d",a[i]);
getch();
Sathi Durga Devi, Department of
IT,SNIST
void select_sort(int x[],int size)
{
for(k=0;k<n;k++)
{
loc = find_min(x,k,size);
temp=x[k];
x[k]=x[loc];
x[loc]=temp;
}
}
int find_min(int x[],int k,int size)
{
min=x[k];
loc=k;
for(j=k+1;j<=size-1;j++)
{
if(min>x[j])
{
min=x[j];
loc=j;
}
}
return loc;
}
X, k, size are local data
to function selection sort
Sathi Durga Devi, Department of
IT,SNIST
Characteristics of procedure-oriented programming
 Emphases on algorithms
 Large programs are divided into smaller programs known as
functions/procedures.
 Procedures functions are independent of each other.
 Most of the functions share global data
 Functions transform data from one form to another
 Employs top-down approach in program design- instead of
writing one long list of instructions and execute from start
to end, we can separate out the instructions into the
functions it is called top- down approach.
Sathi Durga Devi, Department of
IT,SNIST
Advantages of Procedural Programming:
• Its relative simplicity, and ease of implementation of compilers
and interpreters.
• The ability to re-use the same code at different places in the
program without copying it.
• An easier way to keep track of program flow.
• The ability to be strongly modular or structured.
• Needs only less memory.
Disadvantages of Procedural Programming:
• Works well for the smaller projects.
• Difficult to maintain when code gets larger.
• Data is exposed to whole program, so no security for data.
• Difficult to relate with real world objects.
• More difficult to debug large programs.
• Importance is given to the operation on data rather than the
data.
Sathi Durga Devi, Department of
IT,SNIST
Sathi Durga Devi, Department of
IT,SNIST
A way of viewing the world
• In order to clearly understand the object orientation, let’s take
your “hand” as an example. The “hand” is a class. Your body has
two objects of type hand, named left hand and right hand. Their
main functions are controlled/ managed by a set of electrical
signals send through your shoulders (through an interface). So
the shoulder is an interface which your body uses to interact
with your hands. The hand is a well architected class. The hand
is being re-used to create the left hand and the right hand by
slightly changing the properties of it.
Object-oriented programming
Oops decompose the problem into number of entities called
objects and it contains the data and functions
Sathi Durga Devi, Department of
IT,SNIST
Object A Object B
Data
Functions
Data
Functions
Data
Functions
Object C
communication
Characteristics of object-oriented programming
• Emphasis on data rather than procedure
• Programs are divided into objects
• Functions that operate on the data of an object
are tied together in the data structure
• Data is hidden and cannot be accessed by
external functions
• Objects may communicate with each other
through functions
• New data and functions can be easily added
whenever necessary.
• Example are java,c++, smalltalk etc.
Sathi Durga Devi, Department of
IT,SNIST
Advantages of oops
• simplicity: software objects model real world objects, so the
complexity is reduced and the program structure is very clear;
• modifiability: it is easy to make minor changes in the data
representation or the procedures in an OO program. Changes
inside a class do not affect any other part of a program.
• extensibility: adding new features or responding to changing
operating environments can be solved by introducing a few new
objects and modifying some existing ones;
• OOP makes it easy to maintain and modify existing code as new
objects can be created with small differences to existing ones.
• maintainability: objects can be maintained separately, making
locating and fixing problems easier;
• re-usability: objects can be reused in different programs.
• Software complexity is managed easily.
• Builds secured programs due to data hiding.
Sathi Durga Devi, Department of
IT,SNIST
Pops vs oops
Sathi Durga Devi, Department of
IT,SNIST
Procedure Oriented Programming Object Oriented Programming
1. Emphases on algorithm 1. Emphases on data
2. Gobal data accessible to all the
functions . Hence , it reduces the
security
2. Data is hided and localizes the data
and restrict other objects
3. Modules 3. Objects
4. Variables Attributes
5. Calling 5. Messaging
6. Top- down approach 6. Bottom- up approach
object oriented programming conceptsobject oriented programming concepts
1.Objects1.Objects
2. Classes2. Classes
3.Data abstraction and Encapsulation3.Data abstraction and Encapsulation
4. Inheritance4. Inheritance
5. Polymorphism5. Polymorphism
6. Dynamic Binding6. Dynamic Binding
7. Message passing7. Message passing
Sathi Durga Devi, Department of
IT,SNIST
1. Objects
 Object is instance of a class.
 Objects are basic run-time entities in an object- oriented
system and it contains the data and functions.
 In this an object is considered to be a partitioned area of
computer memory that stores data and set of operations
that can access that data. Since the memory partitions are
independent, the objects can be used in variety of programs
without modification and provides more security.
 Objects interacts with each other by sending messages.
Sathi Durga Devi, Department of
IT,SNIST
State and behavior of an object
• Every object has a state. That is, at any point in time it can be
described about what data it has.
ex- class person to store the following data about the person:
name, address, color, height, weight, when a person object is
created it stores the data about him. These are call state of an
object.
• An object can perform a set of related activities. The set of
activities that the object performs defines the object's
behavior.
• Every object has behavior. That is, an object has a certain set
of actions that it can perform
ex- for average marks of a student, call the method average();
Sathi Durga Devi, Department of
IT,SNIST
2. class
• A class is collection of objects are of similar type,
where the variables and methods are defined.
• Ex: fruit mango;
• Example- Apple, orange,banana are of type class fruit.
• Each object is associated with the data of type class.
• Classes are user-defined data types and behave like the
built-in types of programming language
• Objects which follows the definition of the class is
called instances of the class.
Sathi Durga Devi, Department of
IT,SNIST
class object
3.Data Encapsulation
 The wrapping up of data and functions into a single
unit is known as encapsulation
 The class is used to achieve the encapsulation.
 The data is not accessible to the outside world, and
only those functions which are wrapped in the class
can access it
 So it achieves data hiding or information hiding.
Sathi Durga Devi, Department of
IT,SNIST
 Data abstraction- it refers to provide only essential features
to the outside world and hiding their background details
 Abstraction shows only what it does rather than how it does or
works.
Sathi Durga Devi, Department of
IT,SNIST
4. Inheritance
Inheritance is the process by which objects of one class acquire
the properties of another class.
Inheritance is a mechanism of reusing and extending existing classes
without modifying them.
uses
It support the concept of hierarchical classification
Supports the reuse the software components ( reusability).
Increases reliability and decreases the maintenance cost.
3. Data Abstraction
5. polymorphism
• A Greek term, means that ability to take more than one form.
• Polymorphism relates to object methods.
• A method may exhibit different behaviors in different instances.
• Behaviour depends on the types of data used in the operations.
• All the objects share the same function name but their implementation is
differ.
• Polymorphism used to implement the inheritance.
Sathi Durga Devi, Department of
IT,SNIST
Shape
Draw()
Circle object
Draw()
Box object
Draw()
Triangle
Draw()
Why this oops are better to model the real world objects?
Example-
Ram- raju r u hungry?
Raju- yes, I am .
Here Raju and Ram are two objects they send messages like raju
r u hungry and yes I am
If you ask same question to the robot as different object it gives
different answer.
- Objects are created based on how to respond to the messages.
- Different objects might respond to same message in different
ways.
- This can be achieved by the polymorphism
Sathi Durga Devi, Department of
IT,SNIST
7. Message passing
• Set of objects that communicate with each other.
1. create the classes that define data and functions.
2. creating the objects for that class
3. establish communication among objects.
example
account. Balance_enquiry(accountno);
Object message information
Sathi Durga Devi, Department of
IT,SNIST
6. Dynamic binding
Linking of procedure call to the code to be executed in response to the call.
In which the code associated with the given procedure call is not known until time
of run- time of a program is called dynamic binding.
Sathi Durga Devi, Department of
IT,SNIST
Benefits of OOP
Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
The principle of data hiding helps the programmer to build secure programs
that cannot be invaded by code in the parts of the program.
 It is easy to partition the work in a project based on objects.
 Object oriented system easily upgraded from small to large systems.
 Software complexity can be easily managed.
Applications of OOP
Real-time systems.
Object-Oriented Databases.
Neural Networks and Parallel Programming.
Decision Support and Office Automation Systems.
I/O in C++
 Since C++ is a superset of C, all of the C I/O functions such as printf and
scanf which are found in the stdio.h header file, are still valid in C++.
 C++ provides an alternative with the new stream input/output features by
including “iostream.h”.
Several new I/O objects available when you include the iostream header file.
Two important ones are:
 cin // Used for keyboard input
 cout // Used for screen output
Both cin and cout can be combined with other member functions for a wide
variety of special I/O capabilities in program applications.
Sathi Durga Devi, Department of
IT,SNIST
Sathi Durga Devi, Department of
IT,SNIST
 Since cin and cout are C++ objects, they are somewhat "intelligent":
 They do not require the usual format strings and conversion specifications.
 They do automatically know what data types are involved.
 They do not need the address operator, &.
 They do require the use of the stream extraction (>>) and insertion (<<)
operators.
 Example with cin and cout:
// program to find average of two numbers
#include<iostream.h>
void main()
{
float n1,n2,avg;
cout<<”Enter two valuesn”;
cin>>n1>>n2;
avg = (n1+n2)/2;
cout<<”nAverage is “<<avg;
}
Sathi Durga Devi, Department of
IT,SNIST
• A sample C++ program
-cout is a predefined object that represents the standard output
stream in C++. Here the standard output stream represents the
screen.
-The operator << is called the insertion or put to operator. It
inserts the content on its right to the object on its left.
-we have used #include<iostream.h>. It contains the declarations
for the cout and the operator <<.
-The header file iostream should be included at the beginning of
all programs that use input/output statements.
#include<iostream.h>
void main()
{
cout<<” Hello World”;
}
Sathi Durga Devi, Department of
IT,SNIST
• A sample C++ program
// program to find average of two numbers
#include<iostream.h>
void main()
{
float n1,n2,avg;
cout<<”Enter two valuesn”;
cin>>n1>>n2;
avg=(n1+n2)/2;
cout<<”nAverage is “<<avg;
}
• cin is a predefined object that represents the standard input stream in C++.
Here the standard input stream represents the keyboard.
• The operator >> is known as extraction or get from operator. It extracts the
values from the keyboard and assigns it to the variables on its right.
• At a time, more than one variable can be read using cin.
• The multiple use of << (along with cout) or >> (along with cin) in one
statement is called cascading
Implementing classes and objects
• Class:-
the class is basis for the oops. Class is a expanded concept of data
structure, where it holds both data and functions. The class is used to
define the nature of an object, and also it is basic unit for the
encapsulation.
-> the class combines the data and its associated functions together. It
allows the data to be hidden.
-> the keyword class is used to create a class. The class declaration
defines the new data type used to create the objects of that type.
Class has two parts:
1. Data members declaration
2. Prototype of member function declarations
Note: Data members can’t be initialized with in the class. They can be
initialized using member functions.Sathi Durga Devi, Department of
IT,SNIST
Sathi Durga Devi, Department of
IT,SNIST
Syntax of declaring a class:
class class-name {
access-specifier:
data and functions;
access-specifier:
data and functions;
// ...
access-specifier:
data and functions;
}object-list;
 -When defining a class, we are creating a new abstract data type that can be
treated like any other built-in data type.
 Class should enclose both data declaration and function declaration part between
curly parenthesis and class definition should be ended with semicolon.
 Members (data members and member functions) are grouped under access specifiers,
namely private, public and protected, which define the visibility of members.
 Data which is declared in a class is by default treated as private which can be
accessed only to the functions which are declared inside of the same class.
 The object-list is optional. If present, it declares objects of the class
class: item
Data
number
cost
Functions
getdata()
putdata()
(a)
getdata()
putdata()
item
(b)
number
cost
Representation of
class
Data members are number and cost
member functions are getdata(), putdata()
data members + member functions- members of the class.
Sathi Durga Devi, Department of
IT,SNIST
Sathi Durga Devi, Department of
IT,SNIST
Creating objects
 The process of creating objects of a class is called class
instantiation.
 Object is instance of the class.
 Once the class is created we can create any number of
objects.
class class-name
{
------;
------;
}object-list;
class student
{
------;
------;
}s1,s2,s3;
class_name object-name1,object-name2,object-name3;
student s1, s2, s3;
Syntax1: Example1:
Syntax2:
Example2:
Sathi Durga Devi, Department of
IT,SNIST
Accessing class members:
 Once an object of a class has been created, then we can access
the members of the class. This is achieved by using the
member access operator, dot(.).
Syntax:
Object-Name.DataMember;
Object-Name.Memberfunction(arguments);
Example:
x.getdata(10,20);
x.number;
Here x.number accessing is illegal, if number is private data
member of the class. Private data members are accessed only
through the member functions not directly by objects.
Structure of C++ program:
Sathi Durga Devi, Department of
IT,SNIST
Include files
Class declaration
Member functions definitions
Main function program
Sathi Durga Devi, Department of
IT,SNIST
Access control specifiers
The following are the access control specifiers.
1. Private 2. public 3. protected.
1. Private members:
 Private members of a class have strict access control.
 Only the member functions of the same class can access these members.
 They prevents the accidental modifications from the outside world.
Example:
class person
{
private:
int age;
int getage();
};
Access- control specifiers- determines the accessibility of the members of the class.
person p1;
int a=p1.age; //error
p1.getage(); // error
p1.age=5; // error
A private member functions is only called by the member function of the same
class . Even an object cannot invoke a private function using the dot operator.
Note- by default are members in a class are private – using keyword private is
optional.
Sathi Durga Devi, Department of
IT,SNIST
2. Public members
 All members declared with public can have access to outside
of the class without any restrictions
 Ex-
class person
{
public:
int age;
int getage();
};
person p1;
a=p1.age;//correct
p1.getage();// correct
3. Protected:
 Similar to the private members and used in inheritance.
 The members which are under protected, can have access to the members
of its derived class.
Example: class A
{
private:
//members of A
protected:
//members of A
public:
//members of A
};
class B: public A //Here class B can have access on
{ protected data of its parent class as
//members of B well as public data.
};
Sathi Durga Devi, Department of
IT,SNIST
Visibility of the class members
Sathi Durga Devi, Department of
IT,SNIST
Access specifiers own class members objects of class
Private yes No
Public yes yes
Protected yes No
#include <iostream.h>
#include <string.h>
class student
{
public:
string name;
int rollno;
};
int main()
{ student a, b;
a.name = "Calvin";
b.name = "Hobbes";
a.rollno = 4 01; b.rollno= 402;
cout << a.name << ": " << a.rollno << endl;
cout << b.name << ": " << b.rollno << endl;
return 0;
}
Sathi Durga Devi, Department of
IT,SNIST
endl in c++ is similar to the n in c
language.
Defining the member functionsFunctions are defined in two ways
1. outside the class definition 2. inside the class definition
1. outside the class definition
if a member function is declared within the class, it may also defined out side
of the class. General form is
Sathi Durga Devi, Department of
IT,SNIST
Return_type classname:: functionname(argmlist)
{
----
----
}
- scope resolution operator tells to the compiler that which function belongs to
hich class in the program.
It uses the scope resolution operator :: to define a function out side of the class.
2. inside the class definition- functions are directly defined inside of the class definition.
#include<iostream.h>
#include<string.h>
class student {
private:
int rollno;
char name[30];
public:
void setdata(int rn, char *n)
void putdata()
};
void student :: setdata(int rn, char *n)
{
rollno=rn;
strcpy(name, n);
}
void student :: putdata()
{
cout<<“roll o=“<<rollno<<“n”;
cout<<“name=“<<name<<“n”;}
Example on functions defined outside the class
Void main()
{
student s1,s2;
s1.setdata(001,”rajesh”);
s2.setdata(002,”shanker”);
s1.putdata();
s2.putdata();
}
Sathi Durga Devi, Department of
IT,SNIST
Example on Member functions defined inside the class
#include<iostream.h>
• #include<string.h>
class student
{
private:
int rollno;
char name[30];
public:
void setdata(int rn, char *n)
{
rollno=rn;
strcpy(name, n);
{
void putdata()
{
cout<<“roll no=“<<rollno<<“n”;
cout<<“name=“<<name<<“n”;
};
Void main()
{
student s1,s2;
s1.setdata(001,”rajesh”);
s2.setdata(002,”shanker”);
s1.putdata();
s2.putdata();
}
Sathi Durga Devi, Department of
IT,SNIST
roll no=001
name= rajesh
roll no= 002
name= shanker
Sathi Durga Devi, Department of
IT,SNIST
Class Scope:
 It tells in which parts of the program (or in which
functions), the class declaration can be used.
 Class scope may be local or global.
Local:
 If class is declared inside the function, then objects can
be created inside that function only.
Global:
 If class is declared outside the functions, then object can
be created in any function.
Sathi Durga Devi, Department of
IT,SNIST
#include<iostream.h>
#include<conio.h>
void print() {
class point
{
int a;
public:
void getdata() {
cout<<"Enter an integer
number: ";
cin>>a;
}
void display() {
cout<<"Entered number
is: "<<a;
}
};
point p;
p.getdata();
p.display();
}
void main()
{
print();
}
//Example program for class inside a member
function
Sathi Durga Devi, Department of
IT,SNIST
#include<iostream.h>
#include<conio.h>
class point
{
int a;
public:
void getdata()
{
cout<<"nEnter value of a :";
cin>>a;
}
void display( )
{
cout<<"nValue of a is: "<<a;
}
};
void print() {
point p;
p.getdata();
p.display();
}
void main() {
clrscr();
print();
point m;
m.getdata();
m.display();
getch();
}
//Example program for class outside a member function
Sathi Durga Devi, Department of
IT,SNIST
Characteristics of member functions
1. several classes in the same program may use the same member function.
The ambiguity of the compiler in deciding which function belongs to
which class can be resolved by the scope resolution operator.
2. Private member of a class can be accessed by all the members of the class.
Whereas non member functions are not allowed to access.
3. Member functions of the same class can access all the members of their
own class without the dot operator.
4. Private member function cannot invoke even with the object.
ex-
class test
{
int x;
void read();
public:
void display();
}t1
t1.read();// illegal
However, the function read() can be called
by the function display
void test :: display()
{
read();
}//display()
Sathi Durga Devi, Department of
IT,SNIST
Memory allocation for objects• The separate space is allocated for the objects when they are declared.
• Memory is allocated for the functions when they are defined and no separate space
is allocated when the objects are created. That space is common for all the objects.
• Separate space is allocated for the data members of the each object.
Member funciton1
Member function 2
Common for all the objects
Member variable1
Member variable 2
Member variable1
Member variable 2
Member variable1
Member variable 2
object1 object2 object3
class test
{
int a,b;
public:
void display(int x,int y)
{
a=x;
b=y;
cout<<“a=“<<a’;
cout<<“b=“<<b;
}
};
void main()
{
test t;
t.display(10,20);
}
When object t created, it is not
initializing the data members
of class. It is performed by a call
to the function display
Display function cannot initialize its
members when the object created.
Sathi Durga Devi, Department of
IT,SNIST
Sathi Durga Devi, Department of
IT,SNIST
constructors
 A constructor is a special member function whose task is to initialize the
objects of its class when they are created. This is also known as automatic
initialization of objects.
 It is special because its name is the same as the class name
 The constructor is executed automatically whenever an object of its
associated class is created.
 It is called constructor because it constructs the values of data members of
the class.
 The constructor is executed every time an object of that class is created.
Syntax
class classname{
//private members
public:
classname(); //constructor declaration
----------
----------
};
classname :: classname (void) //constructor definition
{
}
The constructor is invoked automatically when
the objects of that class are created . No need to
write the special statement.
Sathi Durga Devi, Department of
IT,SNIST
Characteristics of constructors
 Constructor name is same as class name.
 They should be declared in the public section
 They are invoked automatically when the objects are created
 They do not have return types, not even void and therefore,
they cannot return values.
 Constructor can access any data members but cannot be
invoked explicitly.
 They cannot be inherited, through a derived class can call the
base class constructor
 Like other , they can have default arguments
 They cannot refer to their address
 They make ‘implicit calls’ to the operators new and delete
when memory allocated or de allocation is required
 Note: when a constructor is declared for a class, initialization
of the class objects become mandatory
Example of constructor
Sathi Durga Devi, Department of
IT,SNIST
void main()
{
test t(10,20);
test s(40,50);
}
output
a=10
b=20
a=40
b=50
Class test
{
int a,b;
public:
test(int x,int y);
};
test::test(int x,int y)
{
a=x;
b=y;
cout<<“a=“<<a’;
cout<<“b=“<<b;
}
Sathi Durga Devi, Department of
IT,SNIST
Types of Constructors:
1) Default Constructor 2) Parameterized Constructor
3) Copy Constructor
1. Default constructor:
 Constructor without parameters is called default constructor.
#include<iostream.h>
class Test{
int a;
public:
Test( ) { //Default constructor
a=1000;
}
void display( ){
cout<<”a value is “<<a;
}
};
void main( ) {
Test t; //constructor is invoked after creation of object t
t.display();
}
Sathi Durga Devi, Department of
IT,SNIST
2. Parameterized Constructor:
 Constructor which takes parameters is called Parameterized Constructor.
Example:
#include<iostream.h>
class Test
{
public:
Test(int x, int y)//// parameterized constructor
{
cout<<“x=“<<x<<“ y=“<<y<<endl;
};
void main()
{
Test t1(10,20); or Test(10,20);
}
Sathi Durga Devi, Department of
IT,SNIST
 Constructor can also accepts the address of its own class as an argument. In
such case the constructor is called copy constructor.
 Copy constructor is a member function which is used to initialize an object
from another object.
 Copy Constructor is used to create an object that is a copy of an existing
object.
 By default, the compiler generates a copy constructor for each class.
3. Copy constructor
Syntax:
class-name (class-name &variable)
{
-----;
-----;
};
You can call or invoke copy constructor in the following way:
class obj2(obj1);
or
class obj2 = obj1;
Sathi Durga Devi, Department of
IT,SNIST
#include<iostream.h>
class point{
int a;
public:
point( ) //Default constructor
{
a=1000;
}
point(int x) //Parameterized constructor
{
a = x;
}
point(point &p) //Copy constructor
{ //p is an alternative name (alias) of
object p1
a = p.a;
}
void display( )
{
cout<<endl<<”a value is “<<a;
}
};
void main( )
{
point p1;
point p2(500);
point p3(p1);
p1.display();
p2.display();
p3.display();
}
Sathi Durga Devi, Department of
IT,SNIST
• We must pass some initial values as
arguments to the constructor when an object is
created.
• This can be done in two ways.
1. explicitly.
2. implicitly.
1. test t1= test(10,20);// explicitly
2. test t1(20,30);// implicit call.
Sathi Durga Devi, Department of
IT,SNIST
#include<iostream.h>
Class integer
{
int m,n;
public:
integer(int,int);
void display( )
{
cout<<“m=“<<m<<“n”;
cout<<“n=“<<n<<“n”;
}//display()
};//class
Integer:: integer(int x,int y)
{
m=x;
n=y;
}
main(){
integer I1(0,100); // constructor called implicitly
integer I2= integer(10,20);// constructor called explicitly
cout<<“n object1”<<“n”;
I1.display();
Cout<<“nobject2”<<“n”;
I2.display();
return 0;
}//main
Sathi Durga Devi, Department of
IT,SNIST
 Destructor is a member function which is used to destroy an object when an
object is no longer needed.
 Destructor name is same as class name preceded by tilde mark (~).
 Destructor does not include return-type, not even void.
 Destructor does not return any value.
 Destructor cannot be overloaded.
 Single destructor is used in a class without arguments.
 Destructor is invoked when the object goes out of the scope.
 If no user-defined destructor exists for a class, the compiler implicitly
declares a destructor.
 Ex: class X
{
public:
X(); // Constructor for class X
~~X(); // Destructor for class X
};
Destructor
Sathi Durga Devi, Department of
IT,SNIST
include<iostream.h>
class test
{
public:
test( ); //Default constructor
~ test();
};
test:: test()
{
cout<<“n constructor of a class”;
}
test :: ~test()
{
cout<<“n destructor of a class”;
}
void main( )
{
test T; //constructor is invoked after creation of object T
cout<<“n main();
}// object T goes out of the scope, destructor is called.

More Related Content

What's hot

A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
M Hussnain Ali
 

What's hot (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
object oriented programming using c++
 object oriented programming using c++ object oriented programming using c++
object oriented programming using c++
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Introduction on Data Structures
Introduction on Data StructuresIntroduction on Data Structures
Introduction on Data Structures
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Freshers
 
SQL Interview Questions For Experienced
SQL Interview Questions For ExperiencedSQL Interview Questions For Experienced
SQL Interview Questions For Experienced
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
Oops in java
Oops in javaOops in java
Oops in java
 

Viewers also liked

class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 

Viewers also liked (14)

object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Need of object oriented programming
Need of object oriented programmingNeed of object oriented programming
Need of object oriented programming
 
class and objects
class and objectsclass and objects
class and objects
 
Object-Oriented Programming Concepts
Object-Oriented Programming ConceptsObject-Oriented Programming Concepts
Object-Oriented Programming Concepts
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++
 

Similar to Unit v(dsc++)

Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
farhan amjad
 
22601221182_RAHUL_MODAK_BCAC301.pdf
22601221182_RAHUL_MODAK_BCAC301.pdf22601221182_RAHUL_MODAK_BCAC301.pdf
22601221182_RAHUL_MODAK_BCAC301.pdf
ssuser736e06
 
1 unit (oops)
1 unit (oops)1 unit (oops)
1 unit (oops)
Jay Patel
 
Basics of object oriented programming c++ [autosaved]
Basics of object oriented programming c++ [autosaved]Basics of object oriented programming c++ [autosaved]
Basics of object oriented programming c++ [autosaved]
RAVIPUROHIT22
 

Similar to Unit v(dsc++) (20)

OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
 
OOP-1.pptx
OOP-1.pptxOOP-1.pptx
OOP-1.pptx
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 
OOP ppt.pdf
OOP ppt.pdfOOP ppt.pdf
OOP ppt.pdf
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++
 
Software_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxSoftware_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptx
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in c
 
A Hand Book of Visual Basic 6.0.pdf.pdf
A Hand Book of Visual Basic 6.0.pdf.pdfA Hand Book of Visual Basic 6.0.pdf.pdf
A Hand Book of Visual Basic 6.0.pdf.pdf
 
22601221182_RAHUL_MODAK_BCAC301.pdf
22601221182_RAHUL_MODAK_BCAC301.pdf22601221182_RAHUL_MODAK_BCAC301.pdf
22601221182_RAHUL_MODAK_BCAC301.pdf
 
Object Oriented Programming using C++.pptx
Object Oriented Programming using C++.pptxObject Oriented Programming using C++.pptx
Object Oriented Programming using C++.pptx
 
Object Oriented Program Class 12 Computer Science
Object Oriented Program Class 12 Computer ScienceObject Oriented Program Class 12 Computer Science
Object Oriented Program Class 12 Computer Science
 
Principles of OOPs.pptx
Principles of OOPs.pptxPrinciples of OOPs.pptx
Principles of OOPs.pptx
 
CPP-Unit 1.pptx
CPP-Unit 1.pptxCPP-Unit 1.pptx
CPP-Unit 1.pptx
 
1 unit (oops)
1 unit (oops)1 unit (oops)
1 unit (oops)
 
Chapter1 introduction
Chapter1 introductionChapter1 introduction
Chapter1 introduction
 
Basics of object oriented programming c++ [autosaved]
Basics of object oriented programming c++ [autosaved]Basics of object oriented programming c++ [autosaved]
Basics of object oriented programming c++ [autosaved]
 
Chapter17 oop
Chapter17 oopChapter17 oop
Chapter17 oop
 

Recently uploaded

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 

Recently uploaded (20)

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 

Unit v(dsc++)

  • 1. UNIT-VUNIT-V 1. introduction to c++ programming –1. introduction to c++ programming – 2. object oriented programming concepts,2. object oriented programming concepts, 3.Structured Vs OOP.3.Structured Vs OOP. 4.Classes and objects-class definition4.Classes and objects-class definition 5. Objects5. Objects 6. class scope and accessing members6. class scope and accessing members 7. Constructors-default constructor7. Constructors-default constructor 8. parameterized constructor8. parameterized constructor 9. constructor initialization list9. constructor initialization list 10.copy constructor10.copy constructor 11. Destructors11. Destructors.. Sathi Durga Devi, Department of IT,SNIST
  • 2. History of C++  Extension of C  Early 1980s: Bjarne Stroustrup (Bell Laboratories)  Originally named “C with Classes”.  Provides capabilities for object-oriented programming. • Objects: Reusable Software Components – Model items in real world • Object-Oriented Programs – Easy to understand, correct and modify  Hybrid language • C-like style • Object-oriented style • Both Sathi Durga Devi, Department of IT,SNIST
  • 3. Procedure-Oriented programming / structured oriented programming • To do a particular task the list of instructions are given to the computer to follow, and organizing these instructions into groups known as functions. Such languages are called procedure- oriented programming. • COBOL, FORTRAN, C is commonly known as procedure- oriented programming (POP). Sathi Durga Devi, Department of IT,SNIST
  • 4. Procedure-oriented programming Sathi Durga Devi, Department of IT,SNIST Main program Function-5 Function-2 Function-3 Function-4 Function-1 Function-6 Function-7 Function-8
  • 5. Relationship of data and functions in procedural programming Sathi Durga Devi, Department of IT,SNIST Global data Global data Function-1 Local data Function-2 Local data Function-3 Local data
  • 6. /* Write a c program to implement the selection sort*/ #include<stdio.h> void select_sort(int x[], int size); int find_min(int x[],int k,int size); int n,size,a[10],i,j,x,k,pass,temp,min,loc; -> global data void main() { printf("nEnter the size of array: "); scanf("%d",&n); printf("nEnter the array elements: "); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("nElements in array before swapping: "); for(i=0;i<n;i++) printf("t%d",a[i]); printf("n"); select_sort(a,n); printf("nntElements after swapping: "); for(i=0;i<n;i++) printf("t%d",a[i]); getch(); Sathi Durga Devi, Department of IT,SNIST
  • 7. void select_sort(int x[],int size) { for(k=0;k<n;k++) { loc = find_min(x,k,size); temp=x[k]; x[k]=x[loc]; x[loc]=temp; } } int find_min(int x[],int k,int size) { min=x[k]; loc=k; for(j=k+1;j<=size-1;j++) { if(min>x[j]) { min=x[j]; loc=j; } } return loc; } X, k, size are local data to function selection sort Sathi Durga Devi, Department of IT,SNIST
  • 8. Characteristics of procedure-oriented programming  Emphases on algorithms  Large programs are divided into smaller programs known as functions/procedures.  Procedures functions are independent of each other.  Most of the functions share global data  Functions transform data from one form to another  Employs top-down approach in program design- instead of writing one long list of instructions and execute from start to end, we can separate out the instructions into the functions it is called top- down approach. Sathi Durga Devi, Department of IT,SNIST
  • 9. Advantages of Procedural Programming: • Its relative simplicity, and ease of implementation of compilers and interpreters. • The ability to re-use the same code at different places in the program without copying it. • An easier way to keep track of program flow. • The ability to be strongly modular or structured. • Needs only less memory. Disadvantages of Procedural Programming: • Works well for the smaller projects. • Difficult to maintain when code gets larger. • Data is exposed to whole program, so no security for data. • Difficult to relate with real world objects. • More difficult to debug large programs. • Importance is given to the operation on data rather than the data. Sathi Durga Devi, Department of IT,SNIST
  • 10. Sathi Durga Devi, Department of IT,SNIST A way of viewing the world • In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals send through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.
  • 11. Object-oriented programming Oops decompose the problem into number of entities called objects and it contains the data and functions Sathi Durga Devi, Department of IT,SNIST Object A Object B Data Functions Data Functions Data Functions Object C communication
  • 12. Characteristics of object-oriented programming • Emphasis on data rather than procedure • Programs are divided into objects • Functions that operate on the data of an object are tied together in the data structure • Data is hidden and cannot be accessed by external functions • Objects may communicate with each other through functions • New data and functions can be easily added whenever necessary. • Example are java,c++, smalltalk etc. Sathi Durga Devi, Department of IT,SNIST
  • 13. Advantages of oops • simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear; • modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program. • extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; • OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones. • maintainability: objects can be maintained separately, making locating and fixing problems easier; • re-usability: objects can be reused in different programs. • Software complexity is managed easily. • Builds secured programs due to data hiding. Sathi Durga Devi, Department of IT,SNIST
  • 14. Pops vs oops Sathi Durga Devi, Department of IT,SNIST Procedure Oriented Programming Object Oriented Programming 1. Emphases on algorithm 1. Emphases on data 2. Gobal data accessible to all the functions . Hence , it reduces the security 2. Data is hided and localizes the data and restrict other objects 3. Modules 3. Objects 4. Variables Attributes 5. Calling 5. Messaging 6. Top- down approach 6. Bottom- up approach
  • 15. object oriented programming conceptsobject oriented programming concepts 1.Objects1.Objects 2. Classes2. Classes 3.Data abstraction and Encapsulation3.Data abstraction and Encapsulation 4. Inheritance4. Inheritance 5. Polymorphism5. Polymorphism 6. Dynamic Binding6. Dynamic Binding 7. Message passing7. Message passing Sathi Durga Devi, Department of IT,SNIST
  • 16. 1. Objects  Object is instance of a class.  Objects are basic run-time entities in an object- oriented system and it contains the data and functions.  In this an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in variety of programs without modification and provides more security.  Objects interacts with each other by sending messages. Sathi Durga Devi, Department of IT,SNIST
  • 17. State and behavior of an object • Every object has a state. That is, at any point in time it can be described about what data it has. ex- class person to store the following data about the person: name, address, color, height, weight, when a person object is created it stores the data about him. These are call state of an object. • An object can perform a set of related activities. The set of activities that the object performs defines the object's behavior. • Every object has behavior. That is, an object has a certain set of actions that it can perform ex- for average marks of a student, call the method average(); Sathi Durga Devi, Department of IT,SNIST
  • 18. 2. class • A class is collection of objects are of similar type, where the variables and methods are defined. • Ex: fruit mango; • Example- Apple, orange,banana are of type class fruit. • Each object is associated with the data of type class. • Classes are user-defined data types and behave like the built-in types of programming language • Objects which follows the definition of the class is called instances of the class. Sathi Durga Devi, Department of IT,SNIST class object
  • 19. 3.Data Encapsulation  The wrapping up of data and functions into a single unit is known as encapsulation  The class is used to achieve the encapsulation.  The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it  So it achieves data hiding or information hiding. Sathi Durga Devi, Department of IT,SNIST
  • 20.  Data abstraction- it refers to provide only essential features to the outside world and hiding their background details  Abstraction shows only what it does rather than how it does or works. Sathi Durga Devi, Department of IT,SNIST 4. Inheritance Inheritance is the process by which objects of one class acquire the properties of another class. Inheritance is a mechanism of reusing and extending existing classes without modifying them. uses It support the concept of hierarchical classification Supports the reuse the software components ( reusability). Increases reliability and decreases the maintenance cost. 3. Data Abstraction
  • 21. 5. polymorphism • A Greek term, means that ability to take more than one form. • Polymorphism relates to object methods. • A method may exhibit different behaviors in different instances. • Behaviour depends on the types of data used in the operations. • All the objects share the same function name but their implementation is differ. • Polymorphism used to implement the inheritance. Sathi Durga Devi, Department of IT,SNIST Shape Draw() Circle object Draw() Box object Draw() Triangle Draw()
  • 22. Why this oops are better to model the real world objects? Example- Ram- raju r u hungry? Raju- yes, I am . Here Raju and Ram are two objects they send messages like raju r u hungry and yes I am If you ask same question to the robot as different object it gives different answer. - Objects are created based on how to respond to the messages. - Different objects might respond to same message in different ways. - This can be achieved by the polymorphism Sathi Durga Devi, Department of IT,SNIST
  • 23. 7. Message passing • Set of objects that communicate with each other. 1. create the classes that define data and functions. 2. creating the objects for that class 3. establish communication among objects. example account. Balance_enquiry(accountno); Object message information Sathi Durga Devi, Department of IT,SNIST 6. Dynamic binding Linking of procedure call to the code to be executed in response to the call. In which the code associated with the given procedure call is not known until time of run- time of a program is called dynamic binding.
  • 24. Sathi Durga Devi, Department of IT,SNIST Benefits of OOP Through inheritance, we can eliminate redundant code and extend the use of existing classes. The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in the parts of the program.  It is easy to partition the work in a project based on objects.  Object oriented system easily upgraded from small to large systems.  Software complexity can be easily managed. Applications of OOP Real-time systems. Object-Oriented Databases. Neural Networks and Parallel Programming. Decision Support and Office Automation Systems.
  • 25. I/O in C++  Since C++ is a superset of C, all of the C I/O functions such as printf and scanf which are found in the stdio.h header file, are still valid in C++.  C++ provides an alternative with the new stream input/output features by including “iostream.h”. Several new I/O objects available when you include the iostream header file. Two important ones are:  cin // Used for keyboard input  cout // Used for screen output Both cin and cout can be combined with other member functions for a wide variety of special I/O capabilities in program applications. Sathi Durga Devi, Department of IT,SNIST
  • 26. Sathi Durga Devi, Department of IT,SNIST  Since cin and cout are C++ objects, they are somewhat "intelligent":  They do not require the usual format strings and conversion specifications.  They do automatically know what data types are involved.  They do not need the address operator, &.  They do require the use of the stream extraction (>>) and insertion (<<) operators.  Example with cin and cout: // program to find average of two numbers #include<iostream.h> void main() { float n1,n2,avg; cout<<”Enter two valuesn”; cin>>n1>>n2; avg = (n1+n2)/2; cout<<”nAverage is “<<avg; }
  • 27. Sathi Durga Devi, Department of IT,SNIST • A sample C++ program -cout is a predefined object that represents the standard output stream in C++. Here the standard output stream represents the screen. -The operator << is called the insertion or put to operator. It inserts the content on its right to the object on its left. -we have used #include<iostream.h>. It contains the declarations for the cout and the operator <<. -The header file iostream should be included at the beginning of all programs that use input/output statements. #include<iostream.h> void main() { cout<<” Hello World”; }
  • 28. Sathi Durga Devi, Department of IT,SNIST • A sample C++ program // program to find average of two numbers #include<iostream.h> void main() { float n1,n2,avg; cout<<”Enter two valuesn”; cin>>n1>>n2; avg=(n1+n2)/2; cout<<”nAverage is “<<avg; } • cin is a predefined object that represents the standard input stream in C++. Here the standard input stream represents the keyboard. • The operator >> is known as extraction or get from operator. It extracts the values from the keyboard and assigns it to the variables on its right. • At a time, more than one variable can be read using cin. • The multiple use of << (along with cout) or >> (along with cin) in one statement is called cascading
  • 29. Implementing classes and objects • Class:- the class is basis for the oops. Class is a expanded concept of data structure, where it holds both data and functions. The class is used to define the nature of an object, and also it is basic unit for the encapsulation. -> the class combines the data and its associated functions together. It allows the data to be hidden. -> the keyword class is used to create a class. The class declaration defines the new data type used to create the objects of that type. Class has two parts: 1. Data members declaration 2. Prototype of member function declarations Note: Data members can’t be initialized with in the class. They can be initialized using member functions.Sathi Durga Devi, Department of IT,SNIST
  • 30. Sathi Durga Devi, Department of IT,SNIST Syntax of declaring a class: class class-name { access-specifier: data and functions; access-specifier: data and functions; // ... access-specifier: data and functions; }object-list;  -When defining a class, we are creating a new abstract data type that can be treated like any other built-in data type.  Class should enclose both data declaration and function declaration part between curly parenthesis and class definition should be ended with semicolon.  Members (data members and member functions) are grouped under access specifiers, namely private, public and protected, which define the visibility of members.  Data which is declared in a class is by default treated as private which can be accessed only to the functions which are declared inside of the same class.  The object-list is optional. If present, it declares objects of the class
  • 31. class: item Data number cost Functions getdata() putdata() (a) getdata() putdata() item (b) number cost Representation of class Data members are number and cost member functions are getdata(), putdata() data members + member functions- members of the class. Sathi Durga Devi, Department of IT,SNIST
  • 32. Sathi Durga Devi, Department of IT,SNIST Creating objects  The process of creating objects of a class is called class instantiation.  Object is instance of the class.  Once the class is created we can create any number of objects. class class-name { ------; ------; }object-list; class student { ------; ------; }s1,s2,s3; class_name object-name1,object-name2,object-name3; student s1, s2, s3; Syntax1: Example1: Syntax2: Example2:
  • 33. Sathi Durga Devi, Department of IT,SNIST Accessing class members:  Once an object of a class has been created, then we can access the members of the class. This is achieved by using the member access operator, dot(.). Syntax: Object-Name.DataMember; Object-Name.Memberfunction(arguments); Example: x.getdata(10,20); x.number; Here x.number accessing is illegal, if number is private data member of the class. Private data members are accessed only through the member functions not directly by objects.
  • 34. Structure of C++ program: Sathi Durga Devi, Department of IT,SNIST Include files Class declaration Member functions definitions Main function program
  • 35. Sathi Durga Devi, Department of IT,SNIST Access control specifiers The following are the access control specifiers. 1. Private 2. public 3. protected. 1. Private members:  Private members of a class have strict access control.  Only the member functions of the same class can access these members.  They prevents the accidental modifications from the outside world. Example: class person { private: int age; int getage(); }; Access- control specifiers- determines the accessibility of the members of the class. person p1; int a=p1.age; //error p1.getage(); // error p1.age=5; // error A private member functions is only called by the member function of the same class . Even an object cannot invoke a private function using the dot operator. Note- by default are members in a class are private – using keyword private is optional.
  • 36. Sathi Durga Devi, Department of IT,SNIST 2. Public members  All members declared with public can have access to outside of the class without any restrictions  Ex- class person { public: int age; int getage(); }; person p1; a=p1.age;//correct p1.getage();// correct
  • 37. 3. Protected:  Similar to the private members and used in inheritance.  The members which are under protected, can have access to the members of its derived class. Example: class A { private: //members of A protected: //members of A public: //members of A }; class B: public A //Here class B can have access on { protected data of its parent class as //members of B well as public data. }; Sathi Durga Devi, Department of IT,SNIST
  • 38. Visibility of the class members Sathi Durga Devi, Department of IT,SNIST Access specifiers own class members objects of class Private yes No Public yes yes Protected yes No
  • 39. #include <iostream.h> #include <string.h> class student { public: string name; int rollno; }; int main() { student a, b; a.name = "Calvin"; b.name = "Hobbes"; a.rollno = 4 01; b.rollno= 402; cout << a.name << ": " << a.rollno << endl; cout << b.name << ": " << b.rollno << endl; return 0; } Sathi Durga Devi, Department of IT,SNIST endl in c++ is similar to the n in c language.
  • 40. Defining the member functionsFunctions are defined in two ways 1. outside the class definition 2. inside the class definition 1. outside the class definition if a member function is declared within the class, it may also defined out side of the class. General form is Sathi Durga Devi, Department of IT,SNIST Return_type classname:: functionname(argmlist) { ---- ---- } - scope resolution operator tells to the compiler that which function belongs to hich class in the program. It uses the scope resolution operator :: to define a function out side of the class. 2. inside the class definition- functions are directly defined inside of the class definition.
  • 41. #include<iostream.h> #include<string.h> class student { private: int rollno; char name[30]; public: void setdata(int rn, char *n) void putdata() }; void student :: setdata(int rn, char *n) { rollno=rn; strcpy(name, n); } void student :: putdata() { cout<<“roll o=“<<rollno<<“n”; cout<<“name=“<<name<<“n”;} Example on functions defined outside the class Void main() { student s1,s2; s1.setdata(001,”rajesh”); s2.setdata(002,”shanker”); s1.putdata(); s2.putdata(); } Sathi Durga Devi, Department of IT,SNIST
  • 42. Example on Member functions defined inside the class #include<iostream.h> • #include<string.h> class student { private: int rollno; char name[30]; public: void setdata(int rn, char *n) { rollno=rn; strcpy(name, n); { void putdata() { cout<<“roll no=“<<rollno<<“n”; cout<<“name=“<<name<<“n”; }; Void main() { student s1,s2; s1.setdata(001,”rajesh”); s2.setdata(002,”shanker”); s1.putdata(); s2.putdata(); } Sathi Durga Devi, Department of IT,SNIST roll no=001 name= rajesh roll no= 002 name= shanker
  • 43. Sathi Durga Devi, Department of IT,SNIST Class Scope:  It tells in which parts of the program (or in which functions), the class declaration can be used.  Class scope may be local or global. Local:  If class is declared inside the function, then objects can be created inside that function only. Global:  If class is declared outside the functions, then object can be created in any function.
  • 44. Sathi Durga Devi, Department of IT,SNIST #include<iostream.h> #include<conio.h> void print() { class point { int a; public: void getdata() { cout<<"Enter an integer number: "; cin>>a; } void display() { cout<<"Entered number is: "<<a; } }; point p; p.getdata(); p.display(); } void main() { print(); } //Example program for class inside a member function
  • 45. Sathi Durga Devi, Department of IT,SNIST #include<iostream.h> #include<conio.h> class point { int a; public: void getdata() { cout<<"nEnter value of a :"; cin>>a; } void display( ) { cout<<"nValue of a is: "<<a; } }; void print() { point p; p.getdata(); p.display(); } void main() { clrscr(); print(); point m; m.getdata(); m.display(); getch(); } //Example program for class outside a member function
  • 46. Sathi Durga Devi, Department of IT,SNIST Characteristics of member functions 1. several classes in the same program may use the same member function. The ambiguity of the compiler in deciding which function belongs to which class can be resolved by the scope resolution operator. 2. Private member of a class can be accessed by all the members of the class. Whereas non member functions are not allowed to access. 3. Member functions of the same class can access all the members of their own class without the dot operator. 4. Private member function cannot invoke even with the object. ex- class test { int x; void read(); public: void display(); }t1 t1.read();// illegal However, the function read() can be called by the function display void test :: display() { read(); }//display()
  • 47. Sathi Durga Devi, Department of IT,SNIST Memory allocation for objects• The separate space is allocated for the objects when they are declared. • Memory is allocated for the functions when they are defined and no separate space is allocated when the objects are created. That space is common for all the objects. • Separate space is allocated for the data members of the each object. Member funciton1 Member function 2 Common for all the objects Member variable1 Member variable 2 Member variable1 Member variable 2 Member variable1 Member variable 2 object1 object2 object3
  • 48. class test { int a,b; public: void display(int x,int y) { a=x; b=y; cout<<“a=“<<a’; cout<<“b=“<<b; } }; void main() { test t; t.display(10,20); } When object t created, it is not initializing the data members of class. It is performed by a call to the function display Display function cannot initialize its members when the object created. Sathi Durga Devi, Department of IT,SNIST
  • 49. Sathi Durga Devi, Department of IT,SNIST constructors  A constructor is a special member function whose task is to initialize the objects of its class when they are created. This is also known as automatic initialization of objects.  It is special because its name is the same as the class name  The constructor is executed automatically whenever an object of its associated class is created.  It is called constructor because it constructs the values of data members of the class.  The constructor is executed every time an object of that class is created. Syntax class classname{ //private members public: classname(); //constructor declaration ---------- ---------- }; classname :: classname (void) //constructor definition { } The constructor is invoked automatically when the objects of that class are created . No need to write the special statement.
  • 50. Sathi Durga Devi, Department of IT,SNIST Characteristics of constructors  Constructor name is same as class name.  They should be declared in the public section  They are invoked automatically when the objects are created  They do not have return types, not even void and therefore, they cannot return values.  Constructor can access any data members but cannot be invoked explicitly.  They cannot be inherited, through a derived class can call the base class constructor  Like other , they can have default arguments  They cannot refer to their address  They make ‘implicit calls’ to the operators new and delete when memory allocated or de allocation is required  Note: when a constructor is declared for a class, initialization of the class objects become mandatory
  • 51. Example of constructor Sathi Durga Devi, Department of IT,SNIST void main() { test t(10,20); test s(40,50); } output a=10 b=20 a=40 b=50 Class test { int a,b; public: test(int x,int y); }; test::test(int x,int y) { a=x; b=y; cout<<“a=“<<a’; cout<<“b=“<<b; }
  • 52. Sathi Durga Devi, Department of IT,SNIST Types of Constructors: 1) Default Constructor 2) Parameterized Constructor 3) Copy Constructor 1. Default constructor:  Constructor without parameters is called default constructor. #include<iostream.h> class Test{ int a; public: Test( ) { //Default constructor a=1000; } void display( ){ cout<<”a value is “<<a; } }; void main( ) { Test t; //constructor is invoked after creation of object t t.display(); }
  • 53. Sathi Durga Devi, Department of IT,SNIST 2. Parameterized Constructor:  Constructor which takes parameters is called Parameterized Constructor. Example: #include<iostream.h> class Test { public: Test(int x, int y)//// parameterized constructor { cout<<“x=“<<x<<“ y=“<<y<<endl; }; void main() { Test t1(10,20); or Test(10,20); }
  • 54. Sathi Durga Devi, Department of IT,SNIST  Constructor can also accepts the address of its own class as an argument. In such case the constructor is called copy constructor.  Copy constructor is a member function which is used to initialize an object from another object.  Copy Constructor is used to create an object that is a copy of an existing object.  By default, the compiler generates a copy constructor for each class. 3. Copy constructor Syntax: class-name (class-name &variable) { -----; -----; }; You can call or invoke copy constructor in the following way: class obj2(obj1); or class obj2 = obj1;
  • 55. Sathi Durga Devi, Department of IT,SNIST #include<iostream.h> class point{ int a; public: point( ) //Default constructor { a=1000; } point(int x) //Parameterized constructor { a = x; } point(point &p) //Copy constructor { //p is an alternative name (alias) of object p1 a = p.a; } void display( ) { cout<<endl<<”a value is “<<a; } }; void main( ) { point p1; point p2(500); point p3(p1); p1.display(); p2.display(); p3.display(); }
  • 56. Sathi Durga Devi, Department of IT,SNIST • We must pass some initial values as arguments to the constructor when an object is created. • This can be done in two ways. 1. explicitly. 2. implicitly. 1. test t1= test(10,20);// explicitly 2. test t1(20,30);// implicit call.
  • 57. Sathi Durga Devi, Department of IT,SNIST #include<iostream.h> Class integer { int m,n; public: integer(int,int); void display( ) { cout<<“m=“<<m<<“n”; cout<<“n=“<<n<<“n”; }//display() };//class Integer:: integer(int x,int y) { m=x; n=y; } main(){ integer I1(0,100); // constructor called implicitly integer I2= integer(10,20);// constructor called explicitly cout<<“n object1”<<“n”; I1.display(); Cout<<“nobject2”<<“n”; I2.display(); return 0; }//main
  • 58. Sathi Durga Devi, Department of IT,SNIST  Destructor is a member function which is used to destroy an object when an object is no longer needed.  Destructor name is same as class name preceded by tilde mark (~).  Destructor does not include return-type, not even void.  Destructor does not return any value.  Destructor cannot be overloaded.  Single destructor is used in a class without arguments.  Destructor is invoked when the object goes out of the scope.  If no user-defined destructor exists for a class, the compiler implicitly declares a destructor.  Ex: class X { public: X(); // Constructor for class X ~~X(); // Destructor for class X }; Destructor
  • 59. Sathi Durga Devi, Department of IT,SNIST include<iostream.h> class test { public: test( ); //Default constructor ~ test(); }; test:: test() { cout<<“n constructor of a class”; } test :: ~test() { cout<<“n destructor of a class”; } void main( ) { test T; //constructor is invoked after creation of object T cout<<“n main(); }// object T goes out of the scope, destructor is called.

Editor's Notes

  1. Instructor notes: Because cin and cout are objects in C++ they have some built in “intelligence”. Effectively they can see the “signature” of the value or variable that is being input or output and based on this signature cin and cout can process the information without the use of the usual format strings and conversion specifiers that are needed in C. cin and cout are able to look at the signature of the data and automatically know the data’s type. Often times one of the operators that is most easily missed in C is the address operator, &amp;, which if frequently used with the scanf function. Fortunately in C++ the address operator is not required. cout and cin do require the use of the extraction and insertion operators.