View
230
Download
0
Category
Preview:
Citation preview
Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING
THROUGH C++ Practical: OOPS THROUGH C++
Subject Code: 1618407
PROGRAM NO.1
Programming exercise on executing a Basic C++ Program.
Object oriented programming – As the name suggests uses objects in programming.
Object oriented programming aims to implement real world entities like
inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to
bind together the data and the functions that operates on them so that no other part
of code can access this data except that function.
When we consider a C++ program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what
a class, object, methods, and instant variables mean.
Object − Objects have states and behaviors. Example: A dog has states -
color, name, breed as well as behaviors - wagging, barking, eating. An object
is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
Methods − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.
Instance Variables − Each object has its unique set of instance variables.
An object's state is created by the values assigned to these instance variables.
There are following concepts of OOPS:
1. Class
2. Object
3. Inheritance
4. Data Encapsulation
5. Data Abstractions
6. Polymorphism
1) Class
Class is the template of an object. That logically encapsulates data members and
member functions into a single unit. Classes are data type based on which objects are
created.
2) Object
Object is a basic unit of OOPS. It has unique name. An object represents a particular
instance of a class. We can create more than one objects of a class. The size of class is
size of total number of data members of class.
3) Inheritance
Inheritance is the process of creating new class from existing class or base class. By
using the concept of Inheritance, we can use implemented (existing) features of a class
into another class).
Base class is also known as parent class or super class. The new class that is formed is
called derived class. The derived class is also known as sub class or child class.
Inheritance is basically used for reducing the overall code size of the program.
4) Data Encapsulation
Data encapsulation combines data members and member functions into a single unit
that is called class. The advantage of encapsulation is that data cannot access directly.
It is only accessible through the member functions of the class.
5) Data Abstraction
Data abstraction specifies hiding the implementation detail for simplicity. It increases
the power of programming language by creating user define data types.
6) Polymorphism
Polymorphism is basic and important concept of OOPS. Polymorphism specifies the
ability to assume several forms. It allows routines to use variables of different types at
different times. In C++, an operator or function can be given different meanings or
functions. Polymorphism refers to a single function or multi-functioning operator
performing in different ways.
C++ Program Structure
Let us look at a simple code that would print the words Hello World.
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
Let us look at the various parts of the above program −
The C++ language defines several headers, which contain information that is
either necessary or useful to your program. For this program, the
header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line
comment available in C++. Single-line comments begin with // and stop at the
end of the line.
The line int main() is the main function where program execution begins.
The next line cout << "This is my first C++ program."; causes the message
"This is my first C++ program" to be displayed on the screen.
The next line return 0; terminates main( )function and causes it to return the
value 0 to the calling process.
Program: Sum of two no.
#include <iostream>
using namespace std;
int main()
{
int firstNumber, secondNumber, sumOfTwoNumbers;
cout << "Enter two integers: ";
cin >> firstNumber >> secondNumber;
// sum of two numbers in stored in variable sumOfTwoNumbers
sumOfTwoNumbers = firstNumber + secondNumber;
// Prints sum
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
return 0;
}
Output
Enter two integers: 4
5
4 + 5 = 9
PROGRAM NO.2
Programming Exercise on Control Statement (if-else, else-if
ladder)
IF-ELSE
The if...else statement executes two different codes depending upon whether the
test expression is true or false. Sometimes, a choice has to be made from more than
2 possibilities.
Program: Check Whether Number is Even or odd using if else
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
Output
Enter an integer: 23
23 is odd.
Nested if...else
The nested if...else statement allows you to check for multiple test expressions
and execute different codes for more than two conditions.
Syntax of Nested if...else
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is
true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
Program: C++ Nested if...else
// Program to check whether an integer is positive, negative or zero
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0)
{
cout<<"You entered a negative integer: " << number << endl;
}
else
{
cout << "You entered 0." << endl;
}
cout << "This line is always printed.";
return 0;
}
Output
Enter an integer: 0
You entered 0.
This line is always printed.
PROGRAM NO.3
Programming exercise on loop Control Statement (for, while,
do while)
For Loop: A for loop is a repetition control structure which allows us to write a loop that is
executed a specific number of times. The loop enables us to perform n number of
steps together in oneline. Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Program: Sum of Natural Numbers using For loop
include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
Output
Enter a positive integer: 50
Sum = 1275
This program assumes that user always enters positive number.
If user enters negative number, Sum = 0 is displayed and program is terminated.
Do-while: In do while loops also the loop execution is terminated on the basis of test condition.
The main difference between do while loop and while loop is in do while loop the
condition is tested at the end of loop body, i.e do while loop is exit controlled whereas
the other two loops are entry controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test
condition.
Syntax:
initialization expression; do
{
// statements
update_expression;
} while (test_expression);
C++ Program to compute factorial of a number
#include <iostream>
using namespace std;
int main()
{
int number, i = 1, factorial = 1;
cout << "Enter a positive integer: ";
cin >> number;
while ( i <= number) {
factorial *= i; //factorial = factorial * i;
++i;
}
cout<<"Factorial of "<< number <<" = "<< factorial;
return 0;
}
Output
Enter a positive integer: 4
Factorial of 4 = 24
PROGRAM NO.4
Programming exercise on Function
Depending on whether a function is predefined or created by programmer; there are
two types of function:
Library Function
User-defined Function
Library Function
Library functions are the built-in function in C++ programming.
Programmer can use library function by invoking function directly; they don't need to
write it themselves.
Example: Library Function
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double number, squareRoot;
cout << "Enter a number: ";
cin >> number;
// sqrt() is a library function to calculate square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Output
Enter a number: 26
Square root of 26 = 5.09902
In the example above, sqrt() library function is invoked to calculate the square root of a number.
Notice code #include <cmath> in the above program. Here, cmath is a header file. The function
definition of sqrt()(body of that function) is present in the cmath header file.
You can use all functions defined in cmath when you include the content of file cmath in this
program using #include <cmath>
User-defined Function
C++ allows programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of code
is given a name(identifier).
When the function is invoked from any part of program, it all executes the codes
defined in the body of function.
Example : User Defined Function
C++ program to add two integers. Make a function add() to add integers and
display sum in main() function.
#include <iostream>
using namespace std;
// Function prototype (declaration)
int add(int, int);
int main()
{
int num1, num2, sum;
cout<<"Enters two numbers to add: ";
cin >> num1 >> num2;
// Function call
sum = add(num1, num2);
cout << "Sum = " << sum;
return 0;
}
// Function definition
int add(int a, int b)
{
int add;
add = a + b;
// Return statement
return add;
}
Output
Enters two integers: 8
-4
Sum = 4
Program: Prime Numbers Between two Intervals using function
#include <iostream>
using namespace std;
int checkPrimeNumber(int);
int main()
{
int n1, n2;
bool flag;
cout << "Enter two positive integers: ";
cin >> n1 >> n2;
cout << "Prime numbers between " << n1 << " and " << n2 << " are:
";
for(int i = n1+1; i < n2; ++i)
{
// If i is a prime number, flag will be equal to 1
flag = checkPrimeNumber(i);
if(flag)
cout << i << " ";
}
return 0;
}
// user-defined function to check prime number
int checkPrimeNumber(int n)
{
bool flag = true;
for(int j = 2; j <= n/2; ++j)
{
if (n%j == 0)
{
flag = false;
break;
}
}
return flag;
}
Output
Enter two positive integers: 12
55
Prime numbers between 12 and 55 are: 13 17 19 23 29 31 37 41 43 47 53
To print all prime numbers between two integers, checkPrimeNumber() function is created. This
function checks whether a number is prime or not.
All integers between n1 and n2 are passed to this function.
If a number passed to checkPrimeNumber() is a prime number, this function returns true, if not the
function returns false.
PROGRAM NO.5
Programming exercise on creating classes and their object.
C++ Class
Before you create an object in C++, you need to define a class.
A class is a blueprint for the object.
We can think of class as a sketch (prototype) of a house. It contains all the details
about the floors, doors, windows etc. Based on these descriptions we build the house.
House is the object.
As, many houses can be made from the same description, we can create many objects
from a class.
How to define a class in C++?
A class is defined in C++ using keyword class followed by the name of class.
The body of class is defined inside the curly brackets and terminated by a semicolon
at the end.
class className
{
// some data
// some functions
};
Example: Class in C++
class Test
{
private:
int data1;
float data2;
public:
void function1()
{ data1 = 2; }
float function2()
{
data2 = 3.5;
return data2;
}
};
C++ Objects
When class is defined, only the specification for the object is defined; no memory or
storage is allocated.
To use the data and access functions defined in the class, you need to create objects.
Syntax to Define Object in C++
className objectVariableName;
You can create objects of Test class (defined in above example) as follows:
class Test
{
private:
int data1;
float data2;
public:
void function1()
{ data1 = 2; }
float function2()
{
data2 = 3.5;
return data2;
}
};
int main()
{
Test o1, o2;
}
Here, two objects o1 and o2 of Test class are created.
In the above class Test, data1 and data2 are data members and function1() and function2() are member
functions.
Example: Object and Class in C++ Programming
// Program to illustrate the working of objects and class in C++ Programming #include <iostream>
using namespace std;
class Test
{
private:
int data1;
float data2;
public:
void insertIntegerData(int d)
{
data1 = d;
cout << "Number: " << data1;
}
float insertFloatData()
{
cout << "\nEnter data: ";
cin >> data2;
return data2;
}
};
int main()
{
Test o1, o2;
float secondDataOfObject2;
o1.insertIntegerData(12);
secondDataOfObject2 = o2.insertFloatData();
cout << "You entered " << secondDataOfObject2;
return 0;
}
Output
Number: 12
Enter data: 23.3
You entered 23.3
PROGRAM NO.6
Programming exercise to demonstrated constructor and
destructor.
A constructor is a special type of member function that initialises
an object automatically when it is created.
Compiler identifies a given member function is a constructor by its name and the
return type.
Constructor has the same name as that of the class and it does not have any return
type. Also, the constructor is always public.
Example: Constructor in C++
Calculate the area of a rectangle and display it.
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
// Constructor
Area(): length(5), breadth(2){ }
void GetLength()
{
cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
}
int AreaCalculation() { return (length * breadth); }
void DisplayArea(int temp)
{
cout << "Area: " << temp;
}
};
int main()
{
Area A1, A2;
int temp;
A1.GetLength();
temp = A1.AreaCalculation();
A1.DisplayArea(temp);
cout << endl << "Default Area when value is not taken from user"
<< endl;
temp = A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
Output
Enter length and breadth respectively: 6
7
Area: 42
Default Area when value is not taken from user
Area: 10
\
Destructor
The destructor is a special member function which is called automatically when the
object goes out of scope.
Program
Class class_name {
public:
`class_name() //Destructor
{
}
}
Example // Header Files
#include<iostream>
#include<conio.h>
//Standard Namespace Declaration
using namespace std;
class BaseClass // Class Name
{
public:
//Constructor of the BaseClass
BaseClass() {
cout << "Constructor of the BaseClass : Object Created"<<endl;
}
//Destructor of the BaseClass
~BaseClass() {
cout << "Destructor of the BaseClass : Object Destroyed"<<endl;
}
};
int main ()
{
// Object Declaration for BaseClass
BaseClass des;
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
Sample Output
Constructor of the BaseClass : Object Created
Destructor of the BaseClass : Object Destroyed
PROGRAM NO.7
Programming exercise on operator overloading.
In C++, it's possible to change the way operator works (for user-defined types). This is
done by operator overloading feature.
How to overload operators in C++ programming
To overload an operator, a special operator function is defined inside the class as:
class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};
Here, returnType is the return type of the function.
The returnType of the function is followed by operator keyword.
Symbol is the operator symbol you want to overload. Like: +, <, -, ++
You can pass arguments to the operator function in similar way as functions.
Example: Operator overloading in C++ Programming
#include <iostream>
using namespace std;
class Test
{
private:
int count;
public:
Test(): count(5){}
void operator ++()
{
count = count+1;
}
void Display() { cout<<"Count: "<<count; }
};
int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;}
Output
Count: 6
This function is called when ++ operator operates on the object of Test class (object t in this case).
In the program,void operator ++ () operator function is defined (inside Test class).
This function increments the value of count by 1 for t object.
PROGRAM NO.8
Programming exercise to illustrate concept of Inheritence
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application. This also provides an
opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the
members of an existing class. This existing class is called the baseclass, and the new
class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A
animal, dog IS-A mammal hence dog IS-A animal as well and so on.
Base and Derived Classes
A class can be derived from more than one classes, which means it can inherit data
and functions from multiple base classes. To define a derived class, we use a class
derivation list to specify the base class(es). A class derivation list names one or more
base classes and has the form −
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the
name of a previously defined class. If the access-specifier is not used, then it is
private by default.
Example:
Create game characters using the concept of inheritance.
#include <iostream>
using namespace std;
class Person
{
public:
string profession;
int age;
Person(): profession("unemployed"), age(16) { }
void display()
{
cout << "My profession is: " << profession << endl;
cout << "My age is: " << age << endl;
walk();
talk();
}
void walk() { cout << "I can walk." << endl; }
void talk() { cout << "I can talk." << endl; }
};
// MathsTeacher class is derived from base class Person.
class MathsTeacher : public Person
{
public:
void teachMaths() { cout << "I can teach Maths." << endl; }
};
// Footballer class is derived from base class Person.
class Footballer : public Person
{
public:
void playFootball() { cout << "I can play Football." << endl; }
};
int main()
{
MathsTeacher teacher;
teacher.profession = "Teacher";
teacher.age = 23;
teacher.display();
teacher.teachMaths();
Footballer footballer;
footballer.profession = "Footballer";
footballer.age = 19;
footballer.display();
footballer.playFootball();
return 0;}
Output
My profession is: Teacher
My age is: 23
I can walk.
I can talk.
I can teach Maths.
My profession is: Footballer
My age is: 19
I can walk.
I can talk.
I can play Football.
In this program, Person is a base class, while MathsTeacher and Footballer are derived
from Person.
Person class has two data members - profession and age. It also has two member functions -
walk() and talk().
Both MathsTeacher and Footballer can access all data members and member functions
of Person.
However, MathsTeacher and Footballer have their own member functions as
well: teachMaths() and playFootball() respectively. These functions are only accessed by their
own class.
In the main() function, a new MathsTeacher object teacher is created.
Since, it has access to Person's data members, profession and age of teacher is set. This data is
displayed using the display() function defined in the Person class. Also,
the teachMaths() function is called, defined in the MathsTeacher class.
Likewise, a new Footballer object footballer is also created. It has access to Person's data
members as well, which is displayed by invoking the display() function.
The playFootball()function only accessible by the footballer is called then after.
Types of Inheritance
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is specified
by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is commonly
used. While using different type of inheritance, following rules are applied –
Public Inheritance − When deriving a class from a public base
class, public members of the base class become public members of the derived
class and protected members of the base class become protected members of
the derived class. A base class's privatemembers are never accessible directly
from a derived class, but can be accessed through calls to
the public and protected members of the base class.
Protected Inheritance − When deriving from a protected base class, public
and protected members of the base class become protected members of the
derived class.
Private Inheritance − When deriving from a private base class, public and
protected members of the base class become private members of the derived
class.
Example of public, protected and private inheritance in C++
class base
{
public:
int x;
protected:
int y;
private:
int z;
};
class publicDerived: public base
{
// x is public
// y is protected
// z is not accessible from publicDerived
};
class protectedDerived: protected base
{
// x is protected
// y is protected
// z is not accessible from protectedDerived
};
class privateDerived: private base
{
// x is private
// y is private
// z is not accessible from privateDerived
}
In the above example, we observe the following things:
base has three member variables: x, y and z which are public, protected and private member respectively.
publicDerived inherits variables x and y as public and protected. z is not inherited as it is a private member
variable of base.
protectedDerived inherits variables x and y. Both variables become protected. z is not inherited
If we derive a class derivedFromProtectedDerived from protectedDerived, variables x and y are also inherited
to the derived class.
privateDerived inherits variables x and y. Both variables become private. z is not inherited
If we derive a class derivedFromPrivateDerived from privateDerived, variables x and y are not inherited
because they are private variables of privateDerived.
Recommended