Unit III CPP
Unit III CPP
C uses scanf() and printf() function C++ uses cin>> and cout<< for
for standard input and output. standard input and output.
Variables must be defined at the
beginning in the function. Modern C
compilers such as gcc support the
C99 and C11 standards, which allow Variables can be defined anywhere
you to declare a variable anywhere. in the function.
In C++, namespace feature is
In C, namespace feature is absent. present.
C is a middle level language. C++ is a high level language.
Programs are divided into modules Programs are divided into classes
and functions. and functions.
C doesn’t support exception C++ supports exception
handling directly. Can be done handling. Done by using try
by using some other functions. and catch block.
Features like function C++ supports function
overloading and operator overloading and operator
overloading is not present. overloading.
C uses functions for C++ uses objects for input
input/output. output.
For example scanf and printf. For example cin and cout.
C has no support for virtual C++ supports virtual and
and friend functions. friend functions.
Software Evaluation
Machine Language
Assembly Language
Procedure- Oriented
Function-4
Function-5
DATA DATA
Communication
FUNCTION FU N C T IO N
Object c
DATA
FU N C T IO N
Basic Concepts of Object Oriented Programming
•Objects
•Classes
•Data abstraction
•Encapsulation
•Inheritance
•Polymorphism
•Dynamic binding
•Message passing
Objects
Objects are the basic run time entities in an object- oriented
system. They may represent a person, a place, a bank account, a
table of data or any item that the program has to handle. They
may also represent user-defined data such as vectors, time and
lists.
DATA
Name
Date-of-birth
Marks
FUNCTIONS
Total
Average
Display
………
The entire set of data and code of an object can be made a user -defined
data type with the help of class. In fact, objects are variables of the type
class. Each object is associated with the data of type class with which they
are created.
Once a class has been defined, we can create any number of objects
belonging to that class.
Fruit Mango;
BRD
Attributes
Features
Lay Eggs
Attributes Attributes
………… ………..
………... ………..
Draw
Object
Information
Message
Application of OOP
•Real-time system
•Simulation and modeling
•Object-oriented data bases
•Hypertext, Hypermedia, and expertext
•AI and expert systems
•Neural networks and parallel programming
•Decision support and office automation systems
•CIM/CAM/CAD systems
//PRINT NUMBER ENTERED BY USER
#include<iostream>
using namespace std;
int main()
{
int number;
cout<<“Enter an integer: ”;
cin>> number;
cout<<“You entered: ” << number;
return 0;
}
OUTPUT
Enter an integer: 23
You entered: 23
//PROGRAM TO FIND QUOTIENT AND REMAINDER
#include<iostream>
using namespace std;
int main()
{
int divisor, dividend, quotient,remainder;
cout<< “Enter dividend: ”;
cin>> dividend;
cout<< “Enter divisor: ”;
cin>> divisor;
quotient = dividend / divisor;
remainder = dividend % divisor;
cout<< “Quotient= “ << quotient << endl;
cout<< “Remainder= “<<remainder;
return 0;
}
OUTPUT
Enter dividend: 13
Enter divisor: 4
Quotient = 3
Remainder = 1
//Program to check palindrome number
#include<iostream>
using namespace std;
int main()
{
int n, num, digit, rev=0;
cin>> num;
n=num;
while(n>0)
{
digit = num%10;
rev=(rev*10)+digit;
num = num/10;
}
if(n==rev)
cout<<“The number is a palindrome.”;
else
cout<<“The number is not a palindrome.”;
return 0
}
Output
Enter the positive number: 12321
The reverse of the number is: 12321
The number is a palindrome
//PROGRAM TO CHECK PRIME NUMBER
#include<iostream>
using namespace std;
int main()
{
int num, i;
cin>>num;
for (i=2;i<=num-1;i++)
{
if (num%i==0)
{
cout<<"The number is not a prime number";
break;
}
}
if (i== num)
cout<<"The number is a prime number";
return 0;
}
Output
5
The number is a prime number
6
The number is not a prime numbe
//PROGRAM TO DISPLAY ALL FACTORS OF A NUMBER
#include<iostream>
using namespace std;
int main()
{
int n, i;
cin>>n;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
cout<<i<<“ “;
}
}
return 0;
}
Output
60
1 2 3 4 5 6 10 12 15 20 30 60
//PROGRAM TO CHECK VOWEL OR A CONSONANT MANUALLY
#include<iostream>
using namespace std;
int main()
{
char c;
bool islower, isupper;
cin>>c;
islower=(c==‘a’ || c==‘e’ || c==‘I’ || c==‘o’ || c==‘u’);
isupper=(c==‘A’ || c==‘E’ || c==‘I’ || c==‘O’ ||c==‘U’);
if(!isalpha(c))
cout<<“Not a alphabet”;
else
if(islower || isupper)
cout<< c<<“is a vowel”;
else
cout<<c<<“is a consonant.”;
return 0;
}
Output
Enter an alphabet: u
u is a vowel
DEFINING A CLASS
2.The body of the class is defined inside the curly brackets and
terminated by the semicolon at the end.
EXAMPLE
class Car
{
Public:
string brand;
string model;
int year;
};
An Object is an instance of a class.
SYNTAX
ClassName ObjectName;
EXAMPLE
#include<iostream.h>
class Car
{
Public:
string brand;
string model;
int year;
};
int main()
{
Car obj1; // Creating an object of class car
obj1.brand = “BMW”;
obj1.model = “X5”;
obj1.year = 1999;
cout << obj1.brand << ” “ << obj1.model << “ “ << obj1.year;
}
O/P
BMW X5 1999
Data Members and Member Functions
Data members are the data variables and member functions are the
functions used to manipulate these variables and together defines the
properties and behavior of the objects in the class.
For example
Car is the class, the speed limit, mileage are the data members and apply
brakes, increase speed are the member functions.
Example
#include<iostream.h>
class Car
{
public:
int speed_limit, mileage; //Data member
void apply_break() // Member function
{
cout<< “Applybreak” ;
}
void increase_speed() // Member function
{
cout<< “Increase speed” ;
}
}
int main()
{
Car obj1; // Creating object for the class
Obj1.apply_break(); // Accessing member function
Obj1.increase_speed(); // Accessing member function
}
Output
Apply break
Increase speed
Accessing Data Member and Member Functions
O/P
Car model name is BMW X5
Defining Member Functions in Classes
Output
I am BMW
ii) Inside The Class Definition
Another method of defining a member function is to replace the function
declaration by the actual function definition inside the class.
Example
#include<iostream.h>
class Cars
{
public:
void printname()
cout << “I am BMW”;
};
int main()
{
Cars obj1;
obj1.printname();
}
OUTPUT
I am BMW
Nesting of Member Function
EXAMPLE
#include<iostream.h>
class set
{
int m, n;
public:
void input(void):
void display(void);
int largest(void);
};
int set :: largest(void)
{
if(m>=n)
return (m);
else
return(n);
}
void set :: input(void)
{
cout << “Input values of m and n” << “\n”;
cin >> m >> n;
}
void set :: display(void)
{
cout<< “Largest value =” << largest() << “\n”;
}
int main()
{
set A;
A.input();
A.display();
return 0;
}
Output
Input values of m and n
23 13
Largest value = 23
Private Member Function
Example
For example, there is a class named “student” which has the
following
private data members and public member functions:
#include <iostream>
using namespace std;
class Student
{
private:
int rNo;
float percentage;
void TakeNumbersBegin(void) //private member functions
{
cout<<"Input start..."<<endl;
}
void TakeNumbersBeginFinish(void)
{
cout<<"Input end..."<<endl;
}
public:
void read(void) //public member functions
{
TakeNumbersBegin(); //calling first member function
cout<<“Enter roll number”;
cin>>rNo;
cout<<“Enter percentage”;
cin>>percentage;
TakeNumbersBeginFinish(); //calling second member function
}
void print(void)
{
cout<<endl;
cout<<"Roll Number: "<<rNo<<endl;
cout<<"Percentage: "<<percentage<<"%"<<endl;
}
};
int main()
{
Student object1;
object1.read();
object1.print();
return 0;
}
Private Data Members
rNo is used to store the roll number of the student.
perc is used to store the percentage of the student.
1.Static data members are class members that are declared using the static
keyword.
2.There is only one copy of the static data member in the class, even if there
are many class objects.
3.This is because all the objects share the static data member.
4.The static data member is always initialized to zero when the first class
object is created.
Syntax:
In the above syntax, static keyword is used. The data_type is the C++
data type such as int, float etc.
#include <iostream>
#include<string.h>
using namespace std;
class Student
{
private:
int rollNo;
char name[10];
int marks;
public:
static int objectCount;
Student()
{
objectCount++;
}
void getdata()
{
cout << "Enter roll number: "<<endl;
cin >> rollNo;
cout << "Enter name: "<<endl;
cin >> name;
cout << "Enter marks: "<<endl;
cin >> marks;
}
void putdata()
{
cout<<"Roll Number = "<< rollNo
<<endl;
cout<<"Name = "<< name <<endl;
cout<<"Marks = "<< marks <<endl;
cout<<endl;
}
};
int Student::objectCount = 0;
int main(void)
{
Student s1;
s1.getdata();
s1.putdata();
Student s2;
s2.getdata();
s2.putdata();
Student s3;
s3.getdata();
s3.putdata();
cout << "Total objects created = “ << Student::objectCount;
return 0;
}
OUTPUT:
Enter roll number: 1
Enter name: Mark
Enter marks: 78
Roll Number = 1
Name = Mark
Marks = 78
Enter roll number: 2
Enter name: Nancy
Enter marks: 55
Roll Number = 2
Name = Nancy
Marks = 55
Enter roll number: 3
Enter name: Susan
Enter marks: 90
Roll Number = 3
Name = Susan
Marks = 90
Total objects created = 3
Static Member Function
The static member functions are special functions used to access the static
data members or other static member functions.
We can access the static member function using the class name or class
objects.
If the static member function accesses any non-static data member or non-
static member function, it throws an error.
SYNTAX:
class_name::function_name(parameter);
EXAMPLE:
//create program to access the static member function using the class name
#include <iostream>
using namespace std;
Class Note
{
static int num; //Declare a static data member
public:
static int fun() // Create static member function
{
return num;
}
};
int Note :: num =5; /*Initialize the static data member using the class name and the scope resolution operator*/
int main()
{
cout<<“The value of the num is: “<<Note :: func() <<endl; /*Access static member
function using the class name and scope resolution operator*/
return 0;
}
Output:
The value of the num is: 5
Arrays of Objects
class employee
{
char name[30];
int id;
public:
void getdata(void);
void putdata(void);
};
employee manager[3];
employee foreman[15];
employee worker[75];
The above statement will display the data of the ith element of the array
manager. That is, this statement requests the object manager[i] to invoke
the member function putdata().
An array of objects is stored inside the memory in the same way as a
multi-dimensional array.
Member functions are stored separately and will be used by all the
objects.
Example:
#include<iostream>
using namespace std;
class employee
{
char name[30];
float age;
public:
void getdata(void);
void putdata(void);
};
void employee :: getdata(void)
{
cout<< “Enter name: ”;
cin>> name;
cout<< “Enter age: ”;
cin>>age;
}
void employee :: putdata(void)
{
cout<< “Name: ”<< name << “\n”;
cout<< “Age: ”<< age << “\n”;
}
const int size = 3;
int main()
{
employee manager[size];
for(int i=0; i<size; i++)
{
cout << “\nDetails of manager” << i+1 << “\n”;
manager[i].getdata();
}
for(i=0; i<size; i++)
{
cout<< “\nManager” << i+1 << “\n”;
manager[i].putdata();
}
return 0;
}
Output:
Details of manager1
Enter name: Geetha
Enter age: 45
Details of manager2
Enter name: Arun
Enter age: 37
Details of manager3
Enter name: Sam
Enter age: 50
Manager1
Name: Geetha
Age: 45
Manager2
Name: Arun
Age: 37
Manager3
Name: Sam
Age: 50
Object as Function Argument
However, the members of the objects passed as arguments (w1 and w2)
can be accessed within function using the object name and dot operator.
Note that, the objects w1 and w2 are passed by value, however, they
can re passed by reference also.
Point1
x=5
y=3
Point2
x=12
y=6
1.A friend function of a class is defined outside that class scope but it has
the right to access all private and protected members of the class.
2.Even though the prototypes for friend functions appear in the class
definition, friends are not member functions.
3.A friend can be a function, function template, or member function, or a
class or class template, in which case the entire class and all of its members
are friends.
4.To declare a function as a friend of a class, precede the function
prototype in the class definition with keyword friend.
Example:
class Box
{
double width;
public:
double length;
friend void printWidth(Box box);
void setWidth(double wid);
};
Output
Width of box: 10
Const Member Function
The const member functions are the functions which are declared as
constant in the program. The object called by these functions cannot be
modified.
#include<iostream>
using namespace std;
class Demo
{
int val;
public:
Demo(int x =0)
{
val = x;
}
int getvalue() const
{
return val;
}
};
int main()
{
const Demo d(28);
Demo d1(8);
cout<< “The value using object d: ” << d.getvalue();
cout<< “The value using object d1: ”<< d1.getvalue();
return 0;
}
Output
The value using object d: 28
The value using object d1: 8
CONSTRUCTOR
•It is a special method that is invoked automatically at the time of object
creation.
•It is used to initialize the data members of new objects.
•The constructor has the same name as the class or structure.
•Constructor is invoked at the time of object creation.
•Constructor does not have a return value, hence they do not have a return
type.
int main()
{
student s;
s.display();
return 0;
}
Output:
Enter the RollNo: 101
Enter the Name: Guru
Enter the Fee: 190000
101 Guru 190000
Syntax for defining the constructor outside the class
<classname> :: <classname> (list of parameter)
{
//constructor definition
}
Example
#include<iostream>
using namespace std;
class student
{
int rno;
char name[10];
double fee;
public:
student();
void display();
};
student :: student()
{
cout << “Enter the RollNo: ”;
cin>>rno;
cout << “Enter the Name: “;
cin>>name;
cout << “Enter the fee: ”;
cin<<fee;
}
void student::display()
{
cout<< endl << rno << “\t” <<name << “\t” << fee;
}
int main()
{
student s;
s.display();
return 0;
}
Output:
SYNTAX
ClassName(const ClassName &old_obj);
Example:
#include<iostream.h>
#include<string.h>
using namespace std;
class student
{
int rno;
string name;
double fee;
public:
student(int,string,double);
student(student &t)
{
rno = t.rno;
name = t.name;
fee = t.fee;
}
void display();
};
student ::student(int no,string n, double f)
{
rno = no;
name = n;
fee = f;
}
void student :: display()
{
cout<<endl<<rno<< “\t”<<name<< “\t”<<fee;
}
int main()
{
student s(1001, “sam”, 10000);
s.display();
student sam(s);
sam.display();
Output
return 0;
} 1001 Sam 10000
1001 Sam 10000
Destructor
•A destructor will have exact same name as the class prefixed with a
tilde(~) and it can neither return a value nor can it take any parameters.
•Destructor can be very useful for releasing resources before coming out of
the program like closing files, releasing memories.
Example
#include<iostream>
Using namespace std;
class Line
{
public:
void setLength(double len);
double getLength(void);
Line(); //This is the constructor decleration
~Line(); // This is the destrutor decleration
private:
double length;
};
Line :: Line(void)
{
cout<<“Object is being created”<<endl;
}
Line :: ~Line(void)
{
cout<<“Object is being deleted”<<endl;
}
void Line :: setLength(double len)
{
length = len;
}
double Line :: getLength(void)
{
return length;
}
int main()
{
Line line;
line.setLength(6.0);
cout<<“Length of Line: “<<line.getLength()<<endl;
return 0;
}
Output
Object is being created
Length of line: 6
Object is being deleted
THANK YOU