OBJECT ORIENTED PROGRAMMING IN C++ �[UNIT-I]
U4.1
Learning Objectives
U4.2
PROGRAMMING PARADIGMS
OBJECT-ORIENTED PROGRAMMING
OBJECT-BASED PROGRAMMING
PROCEDURAL PROGRAMMING
ASSEMBLY LANGUAGE
MACHINE LANGUAGE
U4.3
PROGRAMMING PARADIGMS
U4.4
Procedural Programming��
U4.5
Procedural Programming�
Advantages:
U4.6
Procedural Programming�
U4.7
Languages that support programming with objects are said to be object based programming languages.
They do not support inheritance and dynamic binding.
Ex-89’Ada, Modula-2
Object Oriented Programming
Objects based features+ inheritance+ dynamic binding
Object Based Programming
U4.8
Object Oriented Programming��
U4.9
Object Oriented Programming�
U4.10
STRUCTURED VS. OBJECT-ORIENTED
U4.11
Object-Based versus Object-Oriented
OR�Object-Oriented = Classes and Objects + Inheritance + Communication with messages�The main difference between object oriented and object based languages is object based languages doesn't support Inheritance where as object oriented supports.
U4.12
FEATURES OF OOP
U4.13
HISTORY OF C++
U4.14
C versus C++
U4.15
Structure of C++ Program
Using C++ hello.cpp
//hello.cpp: printing Hello World message
#include <iostream.h>
void main(){
cout<< “Hello world”;
}
U4.16
Structure of C++ Program
/* greeting.cpp greets its user. * * Input: The name of the user * Output:
A personalized greeting */
#include <iostream> //preprocessor directive for iostream header file
#include <string> //preprocessor directives
int main()//main function declaration
{ //block scope
cout << "Please enter your first name: ";
string firstName;
cin >> firstName;
cout << "\nWelcome to the world of C++, "
<< firstName << "!\n"; return 0;}
U4.17
All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library, and in fact it will be included in most of the source codes
U4.18
ANSI/ISO Standard C++
U4.19
Comments
In C++, there are two different comment delimiters:
The comment pair is identical to the one used in C:
U4.20
Variables
a variable is a named location in memory that is used to hold a value that may be modified by the program. All variables must be declared before they can be used. The general form of a declaration is
type variable_list;
Here, type must be a valid data type plus any modifiers, and variable_list may consist of
one or more identifier names separated by commas. Here are some declarations:
int i,j,l;
short int si;
unsigned int ui;
double balance, profit, loss;
U4.21
Operating with Variables
// initialization of variables
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b=2; // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}
o/p=6
U4.22
const
U4.23
Stream Based I/O
C++’s feature for handling I/O operations are called streams
Streams are abstractions that refer to data flow.
Stream in C++ are classified into
cout<< “Age = “<< age;
U4.24
Input Streams
U4.25
Enumerated types
enum NewTypeName {value1, value2, … , valueN};
U4.26
Specifying different values in enumerations
enum RomanNum { I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000};
U4.27
Example 2 (enum)
enum MonthType {JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
U4.28
Using enumerated types
MonthType thisMonth = APR;
MonthType nextMonth = MAY;
MonthType birthMonth = nextMonth;
U4.29
Operations on enumerations
U4.30
MonthType thisMonth;
…
switch ( thisMonth ) // using enum type switch expression
{
case JAN :
case FEB :
case MAR : cout << “Winter quarter” ;
break ;
case APR :
case MAY :
case JUN : cout << “Spring quarter” ;
break ;
case JUL :
case AUG :
case SEP : cout << “Summer quarter” ;
break ;
case OCT :
case NOV :
case DEC : cout << “Fall quarter” ;
}
U4.31
Incrementing enum variables using type cast mechanism
U4.32
Using enum type Control Variable with for Loop
MonthType month ;
for (month = JAN ; month <= DEC ; month = MonthType (month + 1 ) )
{ // uses type cast to increment
.
.
.
}
U4.33
Simple arithmetic with enumeration constants
U4.34
Example
#include <iostream.h>
#include <stdlib.h>
enum RomanNum {I=1, V=5, X=10, L=50, C=100, M=1000};
int main()
{
cout << "Welcome to the world of Roman numerals!" << endl;
int num = (int)(M + C + L + X + V + I);
cout << "MCLXVI=" << num << endl;
num = (int)((L-X) + (V-I));
cout << "XLIV=" << num << endl;
system("PAUSE");
return 0;
}
U4.35
Arrays Hold Multiple values
U4.36
//This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element int array to store the
// values.
#include <iostream.h>
void main(void)
{
short hours[6];
cout << "Enter the hours worked by six employees: ";
cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];
U4.37
Program continues
cin >> hours[4];
cin >> hours[5];
cout << "The hours you entered are:";
cout << " " << hours[0];
cout << " " << hours[1];
cout << " " << hours[2];
cout << " " << hours[3];
cout << " " << hours[4];
cout << " " << hours[5] << endl;
}
U4.38
Array Initialization
U4.39
Initializing Allocated Memory�
U4.40
Allocating Arrays�
You can allocate arrays using new by using this general form:
p_var = new array_type [size];
Here, size specifies the number of elements in the array.To free an array, use this form of delete:
delete [ ] p_var;
Here, the [ ] informs delete that an array is being released.
For example, the next program allocates a 10-element integer array.
U4.41
No Bounds Checking
There are no checks in C++ that an array subscript is in range
An invalid array subscript can cause program to overwrite other memory
Example:
const int ISIZE = 3;
int i = 4;
int num[ISIZE];
num[i] = 25;
U4.42
// This program uses an array of ten characters to store the
// first ten letters of the alphabet. The ASCII codes of the
// characters are displayed.
#include <iostream.h>
void main()
{
char letters[10] = {'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J'};
cout << "Character" << "\t" << "ASCII Code\n";
cout << "--------" << "\t" << "----------\n";
for (int count = 0; count < 10; count++)
{
cout << letters[count] << "\t\t";
cout << int(letters[count]) << endl;
}
}
U4.43
// Precondition: n is a positive integer
// Postcondition: computes and prints out the first n
// elements of the Fibonacci sequence
void fibonacci(int n){
int *x = new int [n]; // creation of a dynamic array
x[0]=1; x[1]=1;
for (int i=2;i<n;i++)
x[i]=x[i-1]+x[i-2];
cout<<"The Fibonacci sequence of "<<n<<" values are:\n";
for (int i=0;i<n;i++)
cout<<"x["<<i<<"]="<<x[i]<<endl; }
U4.44
//read values and print them in reverse
#include <iomanip.h>
void main()
{
int x[5], index;
cout << “Please enter five integer values: “;
for( index=0; index<5; index++) cin >> x[index];
cout << “The values in reverse order are: “;
for (index=4; index>=0; index--)
cout << setw(3) << x[index];
cout << endl;
}
U4.45
Creating Multidimensional Arrays �
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;
for (int i=0; i<matrix.length; i++)
for (int j=0; j<matrix[i].length; j++)
{
matrix[i][j] = (int)(Math.random()*1000);
}
U4.46
Arrays Example
#include <iostream> #include <new>
using namespace std;
int main()
{ int *p, i;
try {
p = new int [10]; // allocate 10 integer array
} catch (bad_alloc xa) {
cout << "Allocation Failure\n";
return 1; }
for(i=0; i<10; i++ )
p[i] = i;
for(i=0; i<10; i++)
cout << p[i] << " ";
delete [] p; // release the array
return 0;}
U4.47
Introduction to Pointers
U4.48
Pointers and Arrays
U4.49
Character Pointers, Arrays and Strings
U4.50
Character Pointers, Arrays and Strings
U4.51
Examples
U4.52
Remember
U4.53
Void Pointers
int *ip;
U4.54
Constant Pointers
U4.55
Name and Address of an Array
U4.56
CLASSES IN C++
U4.57
STRUCTURE OF C++ PROGRAM
INCLUDE FILES |
CLASS DECLARATION |
MEMBER FUNCTION DEFINITIONS [to separate abstract specifications of the interface (class definition) from the implementation details (member function definition)] |
MAIN FUNCTION PROGRAM |
U4.58
CLASS
U4.59
// myclass1.cpp
#include <iostream.h>
class myclass1// class starts the declaration of a new class
{
private: //Data members are usually private
int num;
public: // Member functions are public in nature.
void getdata() // to enter the value
{
cout<<“Enter an integer:”;// cout keyword to display information
cin>>num; // cin is the keyword to enter data
}
MYCLASS1.CPP
U4.60
void dispdata() // to display the value
{
cout<<“Num=“ <<num<<endl;
}
}; // indicates the end of class command.
void main()
{
myclass1 a1, b1; / /a1 & b1 are objects of class myclass1.
a1.getdata();
b1.getdata();
a1.dispdata();
b1.dispdata();
}
MYCLASS1.CPP
U4.61
A constructor is a special function that is a member of a class and has the same name as that class. For example,
// This creates the class stack.
class stack {
int stck[SIZE]; int tos;
public:
stack(); // constructor
void push(int i);int pop();};
Notice that the constructor stack( ) has no return type specified. In C++, constructors cannot return values and, thus, have no return type.
The stack( ) constructor is coded like this:
// stack's constructor
stack::stack()
{tos = 0;cout << "Stack Initialized\n";
}
Constructors
U4.62
Some important points about constructors:
Constructors
U4.63
The complement of the constructor is the destructor.
There are many reasons why a destructor may be needed. For example, an object may need to deallocate memory that it had previously allocated or it may need to close a file that it had opened.
In C++, it is the destructor that handles deactivation events.
The destructor has the same name as the constructor, but it is preceded by a ~
For example, here is the stack class and its constructor
and destructor.
Destructors
U4.64
Some important points about destructors:�Destructors take the same name as the class name.
Destructors
U4.65
This creates the class stack.
class stack {
int stck[SIZE];
int tos;
public:
stack(); // constructor
~stack(); // destructor
void push(int i);
int pop();
};
// stack's constructor
stack::stack()
{
tos = 0;
cout << "Stack Initialized\n";
}
// stack's destructor
stack::~stack()
{
cout << "Stack Destroyed\n";
}
Notice that, like constructors, destructors do not have return values.
U4.66
CRectangle rectb; // right
CRectangle rectb(); // wrong!
Overloaded Constructors
U4.67
void myfunc(double d = 0.0)
{// ...
}
Now, myfunc( ) can be called one of two ways, as the following examples show:
myfunc(198.234); // pass an explicit value
myfunc(); // let function use default
Default Function Arguments
U4.68
Class Example
// example: class constructor
#include <iostream>
using namespace std;
class CRectangle
{
int width, height;
public:
CRectangle (int,int);
int area ()
{
return (width*height);
}
};
CRectangle::CRectangle (int a, int b)
{
width = a;
height = b;
}
int main ()
{
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
U4.69
Try Out Yourself?
1.Write a program to define a class student. Write function to take the information from user and display the information to user.
2.Write program for a library database using class and with the following data items:
Title of Book
Acc Number
Author
Publisher
Price
Write the class with both a constructor and a member function to initialize the data members.
U4.70
Try out Yourself?
Create a class employee which have name, age and address of the employee. Include functions getdata() and showdata(). Showdata takes the input from the user and display on the monitor in a tabular format and use inline with getdata().
Name:
Age:
Address:.
U4.71
Class Diagram of Employee class
Class: employee |
Data: Name Dept Desig Basic |
Functions: Setbp( ) Totsal( ) Deductions( ) |
U4.72
ABSTRACTION
U4.73
ENCAPSULATION
U4.74
MODULARITY
Example: A Music system comprises of speaker, cassette player, CD player, tuner etc. Though these are different entities in themselves, they work in unity towards achieving one goal i.e. music.
U4.75
Contd.
Advantages:
U4.76
INHERITANCE
U4.77
U4.78
U4.79
Public, Protected, Private Inheritance
class A {
public:
int i;
protected:
int j;
private:
int k;
};
Class B : public A { // ...
};
Class C : protected A {// ...
};
Class D : private A {// ...
};
U4.80
POLYMORPHISM / OVERLOADING
Example: Draw a shape (Box, Triangle, Circle etc.), Move ( Chess, Traffic, Army).
U4.81
Need???
U4.82
U4.83
Compile time polymorphism
U4.84
Function overloading
#include <iostream>�using namespace std;�class arith {�public: void calc(int num1)�{cout<<"Square of a given number: " <<num1*num1 <<endl;}� void calc(int num1, int num2 )�{cout<<"Product of two whole numbers: " <<num1*num2 <<endl;�}};
int main() //begin of main function�{� arith a;� a.calc(5);� a.calc(6,7);}
�
U4.85
Runtime Polymorphism�
U4.86
Virtual Member Function?
For this it uses concepts of dynamic binding.
U4.87
Dynamic binding
class A
{ public:� virtual void f() { cout << "Class A" << endl;} };
class B: public A {
public:� void f(int) { cout << "Class B" << endl; }};
U4.88
Contd…
U4.89
Class, Objects and Memory Resources�
U4.90
Constructors that Allocate Memory Dynamically�[Dynamic Constructors]
U4.91
Dynamic Allocation Operators
U4.92
p_var = new type;
delete p_var;
Here, p_var is a pointer variable that receives a pointer to memory that is large enough to hold an item of type type. Since the heap is finite, it can become exhausted. If there is insufficient available
memory to fill an allocation request, then new will fail and a bad_alloc exception will be generated. This exception is defined in the header <new>. Your program should handle this exception and take appropriate action if a failure occurs. If this exception is not handled by your program, then your program will be terminated.
Dynamic Allocation Operators
U4.93
The trouble is that not all compilers, especially older ones, will have implemented new in compliance with Standard C++. When C++ was first invented, new returned null on failure. Later, this was changed such that new caused an exception on failure. Finally, it was decided that a new failure will generate an exception by default, but that a null pointer could be returned instead, as an option.
Dynamic Allocation Operators
U4.94
int * b= new int [5];
�The dynamic memory requested by our program is allocated by the system from the memory heap. However, computer memory is a limited resource, and it can be exhausted. Therefore, it is important to have some mechanism to check if our request to allocate memory was successful or not.
Dynamic Allocation Operators
Delete ptr;
Dynamic Allocation Operators
U4.96
This program gives the allocated integer an initial value of 87:
#include <iostream> #include <new>
using namespace std;
int main()
{int *p;
try {p = new int (87); // initialize to 87
} catch (bad_alloc xa) {
cout << "Allocation Failure\n";
return 1;}
cout << "At " << p << " ";
cout << "is the value " << *p << "\n";delete p; return 0;}
U4.97
Compound Assignment Operator
// compound assignment operators
#include <iostream>
using namespace std;
int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
return 0;
}
O/P=5
U4.98
Conditional Operator
Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is:
condition ? result1 : result2
If condition is true the expression will return result1, if it is not it will return result2.
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
a>b ? a : b // returns whichever is greater, a or b.
U4.99
Local and Global Variables
You can tell the compiler to use the global identifier rather than the local identifier by prefixing the identifier with ::, the scope resolution operator.
#include <iostream>
using namespace std;
int amount = 123; // A global variable
int main()
{
int amount = 456; // A local variable
cout << ::amount << endl // Print the global variable
cout<< amount << endl; // Print the local variable }
U4.100
Nesting of member function
Member function can be called by using its name inside another member function of the same class.
#include<iostream.h> #include<conio.h>
class student
{ int age;
char name[30];
public:
void getdata();
void displaydata();
};
void student::getdata()
{ cout<<"\n enter the name:";
cin>>name;
cout<<"\n enter the age:";
cin>>age;
displaydata();}
void student::displaydata()
{
cout<<"\n\n name is:"<<name;
cout<<"\n age is:"<<age;}
void main()
{
student s;
s.getdata();
}
U4.101
Nested class
Class within the class and its calling method.
#include<iostream.h> #include<conio.h>
class report
{ int roll_no;char name[30], branch[30];
class dob
{ int dd, mm,yyyy;
public:
void get()
{cin>>dd>>mm>>yyyy; }
void display()
{ cout<<dd<<"-"<<mm<<"-"<<yyyy; }
}dob;
public:
void getdata();
void displaydata();};
U4.102
void report::getdata()
{cout<<"\nenter the roll no:"; cin>>roll_no;
cout<<"\nenter the name:"; cin>>name;
cout<<"\nenter the branch alloted:"; cin>>branch;
cout<<"\nenter the date of birth:";
dob.get();}
void report::displaydata()
{ cout<<"\n\nrollno\tname\tdate of birth\t branch alloted\n";
cout<<roll_no<<"\t"<<name<<"\t";
dob.display(); cout<<"\t\t"<<branch; }
void main()
{ report r;
r.getdata();
r.displaydata();
}
U4.103
Inline Functions
U4.104
#include <iostream>
using namespace std;
inline int max(int a, int b)
{
return a>b ? a : b;
}
int main()
{
cout << max(10, 20);
cout << " " << max(99, 88);
return 0;
}
As far as the compiler is concerned, the preceding program is equivalent to this one:
#include <iostream>
using namespace std;
int main()
{
return 0; cout << (10>20 ? 10 : 20);
cout << " " << (99>88 ? 99 : 88);
}
U4.105
Inline Functions
Inline functions may be class member functions. For example, this is a perfectly valid C++ program:
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
void init(int i, int j);
void show();
};
// Create an inline function.
inline void myclass::init(int i, int j)
{
a = i;
b = j;
}
// Create another inline function.
inline void myclass::show()
{
cout << a << " " << b << "\n";
}
int main()
{
myclass x;
x.init(10, 20);
x.show();
return 0;
}
U4.106
Defining Inline Functions Within a Class
When a function is defined inside a class declaration, it is automatically made into an inline function. It is not necessary (but not an error) to precede its declaration with the inline keyword.
U4.107
Example To Develop An Employee Class
/* class employee stores employee information. We use calc() function to return average salary. */
#include <iostream> #include <string> // to use strings
class employee
{private:
int emp_no, basic;
char name[20];
public:
void getdata() // to enter the data
{cout<<“Enter Employee No:”; cin>>emp_no;
cout<<“Enter name:”; cin.getline(name,’\n’);
cout<<“Enter Salary: “; cin>>basic;}
U4.108
Example To Develop An Employee Class
void dispdata() // to display the value
{cout<<“Employee no:”<<emp_no;
cout<<“Name:”<< name;
cout << “Salary: “<< basic;}
float calc(employee x) //parameter received
{float temp;
temp=(float(basic)+x.basic)/2;//int basic is casted to float
return temp;}}; // End of class declaration
void main()
{employee a1, b1; a1.getdata(); b1.getdata();
float average = a1.calc(b1);
cout<<endl<<“Average Salary:” <<average;}
U4.109
Defining constants (#define)
You can define your own names for constants that you use very often without having to resort to memory consuming variables, simply by using the #define preprocessor directive. Its format is:
#define identifier value
For example:
#define PI 3.14159
#define NEWLINE '\n'
U4.110
// defined constants: calculate circumference
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}
U4.111
U4.112
Variable Aliases- Reference Variables
Datatype & ReferenceVariable = Value Variable
Ex: char & ch1 = ch;
U4.113
Reference Variables contd..
int &num = 100 //invalid
U4.114
Reference Variables cont..
#include <iostream.h>
void main(){
int a = 2;
int c = 7;
int& x = a;
cout<<a;
x = c;
cout <<a;
a=5;
int* b = &a;
cout<<a;
b = &c;
cout <<*b;}
U4.115
#include <iostream.h>
void swap1(int * a, int*b){
int temp = *a;
*a = *b;
*b = temp;
return;}
void swap2(int & a, int& b){
int temp = a;
a = b;
b = temp;
return;}
void main(){
int i =5;
int j = 10;
cout<< i <<" "<<j<<"\n";
swap1(&i, &j);
cout<< i <<" "<<j<<"\n";
swap2(i, j);
cout<< i <<" "<<j<<"\n";}
U4.116
Return by reference
const int & max(int & x, int & y)
#include <iostream.h>
int & max(int & x, int & y)
{
if (x>y)
return x;
else
return y;
}
void main(){
int a,b,c;
cout<<”enter <a,b>:”;
cin>>a>>b;
max(a,b) = 425;
cout<<”a=”<<a;
Cout<<” b= “<<b;}
U4.117
C++ Structures: Classes
U4.118
Structs in C++
int a;
public: // public member function
int f() { return a = 5; }; };
int f() { return a = 5; };
private: // private data member
int a; };
U4.119
Static Instance Variables
ClassName::StaticFieldName
U4.120
C++ Strings
U4.121
C++ Strings
U4.122
Strings
string s1( "abc" ); string s2( "def" ); s1 += s2; // s1 = "abcdef" now
U4.123
Strings
U4.124
Member Functions:�
- swaps the contents of onestring with the contents of other_string. �string s1( "abc" ); string s2( "def" );s1.swap( s2 );
- removes count characters from this string, starting with the character at the given position. If count is omitted the characters up to the end of the string are removed. If both position and count are omitted the string is cleared.
�- �
U4.125
Pass-by-Value �
U4.126
Call-By-Reference �
U4.127
Call-By-Reference in Functions�
We use & to denote a parameter that is passed by reference:
Example:
U4.128
Pass by Value / Pass by Reference
This program uses two functions, one using pass-by-value method and the other using pass-by-reference method.
This shows how the value of number does not change in the main function, when it is evaluated using pass-by-value method and on the other hand it changes when implemented using pass-by-reference method.
U4.129
Review Questions [Objective Types]
U4.130
Review Questions [Objective Types]
U4.131
Review Questions [Short Answer Types]
U4.132
Review Questions [Short Answer Types]
U4.133
Review Questions [Long Answer Types]
Class.
U4.134
Review Questions [Long Answer Types]
How it is different from MACROS? List its advantages and disadvantages also.
U4.135
Review Questions [Long Answer Types]
U4.136