0% found this document useful (0 votes)
54 views

CS-307 - OOPS THROUGH C++ Lab (1-18)

This document contains the lab manual for the Object Oriented Programming through C++ lab course for the Computer Science and Engineering department. It includes details about the course code, credits, prerequisites, outcomes, content, and reference materials. It also lists 18 experiments covering topics like input/output operators, decision making statements, loops, arrays, classes, objects, functions, inheritance, templates, and more. The goal of the lab course is for students to apply concepts of OOP through C++ programming.

Uploaded by

Naga Kalyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

CS-307 - OOPS THROUGH C++ Lab (1-18)

This document contains the lab manual for the Object Oriented Programming through C++ lab course for the Computer Science and Engineering department. It includes details about the course code, credits, prerequisites, outcomes, content, and reference materials. It also lists 18 experiments covering topics like input/output operators, decision making statements, loops, arrays, classes, objects, functions, inheritance, templates, and more. The goal of the lab course is for students to apply concepts of OOP through C++ programming.

Uploaded by

Naga Kalyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 46

OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE & ENGINEERING

LAB MANUAL

FOR

OOPS THROUGH C++

LAB

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES


(Approved by AICTE,New Delhi, Affiliated to JNTUH)

Ponnekal village,Khammam-507170

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 1


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE & ENGINEERING

CS-307-C++ Lab

Course Title C++ Lab Course Code CS-307


Semester III Course Group Core
Teaching Scheme
1:0:2 Credits 1.5
in Periods(L:T:P)
Methodology Lecture + Practical Total Contact Hours 45
CIE 60 Marks SEE 40 Marks

Pre requisites

Knowledge of Computer Operation.


Course Outcome

Course
Outcome
CO1 Use of I/O operators, loops, Classes, objects and functions

CO2 Use of Constructors, Destructors and Operator overloading

CO3 Implement Derived classes and types of inheritance

CO4 Implement Templates

Course Content

Unit Hours/
Unit Name
No Periods
1 I/O operators, loops, Classes, objects and functions 13
2 Constructors, Destructors and Operator overloading 13
3 Derived classes and types of inheritance 13
4 Templates 6
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 2
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE & ENGINEERING

Total 45

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 3


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE & ENGINEERING

Course outcomes
Course Teaching
CL Linked PO
Outcome Hours
Write programs using classes, objects and
CO1 R, U, A 1,2,3,4,7 15
functions
Construct programs using Constructors,
CO2 R, U, A 1,2,3,4,7 15
Destructors and Operator overloading
Demonstrate Derived classes and types of
CO3 R,U, A 1,2,3,4,7 15
Inheritance
CO4 Develop programs using Templates U, A 1,2,3,4,7 10
Total
45
Sessions

Reference Books:

1. Teach yourself C++-- Helbertschildt Osborne McG


2. Object-oriented Programming with C++--- PoornachandraSarang PHI
3. Programming with C++-- E. Balaguruswamy – TMH
4. Computer Science: A Structured Approach using C++--Forouzan/Gillberg -
Thomson
5. C++ & OOPS Paradigm-- DebasishJana PHI

E-References:

1. https://www.tutorialspoint.com/cplusplus/index.htm
2. http://www.cplusplus.com/doc/tutorial/
3. https://www.programiz.com/cpp-programming
4. https://beginnersbook.com/2017/08/c-plus-plus-tutorial-for-beginners/
5. http://www.cplusplus.com/files/tutorial.pdf

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 4


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

List of Experiments

1 Write programs using input and output operators and comments.


2 Write programs using if/ if – else/ nested if statement.
3 Write programs using loop statements – while/ do-while / for.
4 Write programs using arrays.
5 Write programs using classes & object.
6 Write programs using constructor and destructor.
7 Write programs working with two/more classes using Friend function.
8 Write programs using inline function.
9 Write a program to pass an object as a functions argument – pass
object by value, pass object by reference.
10 Write a program to demonstrate the use of operator overloading
on unary operator & binary operators like ++ operator and <<
operator.
11 Write a program to demonstrate the use of function overloading.
12 Write a simple program on array of objects and pointers to objects.
13 Write programs using new, delete with classes.
14 Write simple programs illustrating use of all types of inheritances.
15 Write a program to illustrate virtual base class.
16 Write a Program to illustrate virtual functions.
17 Write a Program to illustrate class templates.
18 Write a Program to illustrate function templates.

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 5


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

1. Write programs using input and output operators and comments.


i) C++ Input operators

#include <iostream.h>
using namespace std;

int main() {
int num;
cout << "Enter an integer: ";
cin >> num; // Taking input
cout << "The number is: " << num;
return 0;
}

OUTPUT:
Enter an integer: 70
The number is: 70

ii) Numbers and Characters c++ Output operators


#include <iostream.h>
using namespace std;

int main() {
int num1 = 70;
double num2 = 256.783;
char ch = 'A';

cout << num1 << endl; // print integer


KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 6
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

cout << num2 << endl; // print double


cout << "character: " << ch << endl; // print char
return 0;
}
OUTPUT:

70
256.783
character: A
2. Write programs using if/ if – else/ nested if statement.
i) C++ if Statement

// Program to print positive number entered by the user

// If the user enters a negative number, it is skipped

#include <iostream.h>
using namespace std;

int main() {
int number;

cout << "Enter an integer: ";


cin >> number;

// checks if the number is positive


if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 7


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

return 0;
}
OUTPUT:

Enter an integer: 5
You entered a positive number: 5
This statement is always executed.

ii) C++ if...else Statement

// Program to check whether an integer is positive or negative

// This program considers 0 as a positive number

#include <iostream.h>
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 {
cout << "You entered a negative integer: " << number << endl;
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 8
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

}
cout << "This line is always printed.";
return 0;
}

OUTPUT:

Enter an integer: 4
You entered a positive integer: 4.
This line is always printed.

iii) C++ Nested if

// C++ program to find if an integer is positive, negative or zero


// using nested if statements

#include <iostream.h>
using namespace std;

int main() {

int num;

cout << "Enter an integer: ";


cin >> num;

// outer if condition
if (num != 0) {
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 9
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// inner if condition
if (num > 0) {
cout << "The number is positive." << endl;
}
// inner else condition
else {
cout << "The number is negative." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither positive nor negative." << endl;
}

cout << "This line is always printed." << endl;

return 0;
}

OUTPUT:

Enter an integer: 35
The number is positive.
This line is always printed.

3. Write programs using loop statements – while/ do-while / for.


i) Sum of Positive Numbers using while loop.

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 10


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// program to find the sum of positive numbers


// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream.h>
using namespace std;

int main() {
int number;
int sum = 0;

// take input from the user


cout << "Enter a number: ";
cin >> number;

while (number >= 0) {


// add all positive numbers
sum += number;

// take input again if the number is positive


cout << "Enter a number: ";
cin >> number;
}

// display the sum


cout << "\nThe sum is " << sum << endl;

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 11


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

return 0;
}
OUTPUT:

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25
ii) Sum of Positive Numbers using Do-while loop.

// program to find the sum of positive numbers


// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream.h>
using namespace std;

int main() {
int number = 0;
int sum = 0;

do {
sum += number;

// take input from the user


cout << "Enter a number: ";
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 12
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

cin >> number;


}
while (number >= 0);

// display the sum


cout << "\nThe sum is " << sum << endl;

return 0;
}
OUTPUT:
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25
iii) Find the sum of first n Natural Numbers using for loop

// C++ program to find the sum of first n natural numbers


// positive integers such as 1,2,3,...n are known as natural numbers

#include <iostream.h>

using namespace std;

int main() {
int num, sum;
sum = 0;

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 13


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

cout << "Enter a positive integer: ";


cin >> num;

for (int i = 1; i <= num; ++i) {


sum += i;
}

cout << "Sum = " << sum << endl;

return 0;
}
OUTPUT:
Enter a positive integer: 10
Sum = 55

4. Write programs using arrays.

i) Displaying Array Elements


#include <iostream.h>
using namespace std;

int main() {

int numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 14


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// Printing array elements


// using range based for loop
for (const int &n : numbers) {
cout << n << " ";
}

cout << "\nThe numbers are: ";

// Printing array elements


// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}

return 0;
}
OUTPUT:

The numbers are: 7 5 6 12 35


The numbers are: 7 5 6 12 35

ii) Take Inputs from User and Store Them in an Array

#include <iostream.h>
using namespace std;

int main() {

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 15


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

int numbers[5];

cout << "Enter 5 numbers: " << endl;

// store input from user to array


for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}

cout << "The numbers are: ";

// print array elements


for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}

return 0;
}
OUTPUT:

Enter 5 numbers:
11
12
13
14
15
The numbers are: 11 12 13 14 15

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 16


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

5. Write programs using classes & object


// Program to illustrate the working of
// objects and class in C++ Programming

#include <iostream.h>;
using namespace std;

// create a class
class Room {

public:
double length;
double breadth;
double height;

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 17


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// assign values to data members


room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

OUTPUT:
Area of Room = 1309
Volume of Room = 25132.8

6. Write programs using constructor and destructor.


#include <iostream.h>

class code
{ int id;
int count;
public:
code()
{
cout<<"Default constructor called\n";
id=0;
cout<<"id="<<id<<<"Parameterized constructor called\n";

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 18


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

id=a;
cout<<"id="<<id<<<"copy constructor called\n";
id=x.id;
cout<<"id="<<id<<<"id="<<id<<<"Object Destroyed"<<<"\n For object d id=";
d.display();
cout<<"\n For object a id="; a.display();
cout<<"\n For object b id="; d.display();
cout<<"\n For object c id="; d.display(); return 0;
}
OUTPUT:

Parameterized constructor called id=100


copy constructor called id=100
copy constructor called id=100
Default constructor called id=0
For object d id=id=0
For object a id=id=100
For object b id=id=0
For object c id=id=0
Object Destroyed
Object Destroyed
Object Destroyed
Object Destroyed
7. Write programs working with two/more classes using Friend function.
// Add members of two different classes using friend functions

#include <iostream.h>
using namespace std;

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 19


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// forward declaration
class ClassB;

class ClassA {

public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}

private:
int numA;

// friend function declaration


friend int add(ClassA, ClassB);
};

class ClassB {

public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}

private:
int numB;

// friend function declaration


friend int add(ClassA, ClassB);
};

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 20


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// access members of both classes


int add(ClassA objectA, ClassB objectB) {
return (objectA.numA + objectB.numB);
}

int main() {
ClassA objectA;
ClassB objectB;
cout << "Sum: " << add(objectA, objectB);
return 0;
}

OUTPUT:
Sum: 13

8. Write programs using inline function.


#include <iostream.h>
using namespace std;

inline void displayNum(int num) {


cout << num << endl;
}

int main() {
// first function call
displayNum(5);

// second function call

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 21


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

displayNum(8);

// third function call


displayNum(666);

return 0;
}
OUTPUT:

5
8
666

9. Write a program to pass an object as a functions argument – pass object by value, pass
object by reference
i) C++ Pass Objects to Function

// C++ program to calculate the average marks of two students

#include <iostream.h>
using namespace std;

class Student {

public:
double marks;

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 22


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// constructor to initialize marks


Student(double m) {
marks = m;
}
};

// function that has objects as parameters


void calculateAverage(Student s1, Student s2) {

// calculate the average of marks of s1 and s2


double average = (s1.marks + s2.marks) / 2;

cout << "Average Marks = " << average << endl;

int main() {
Student student1(88.0), student2(56.0);

// pass the objects as arguments


calculateAverage(student1, student2);

return 0;
}
OUTPUT:
Average Marks = 72
ii) C++ Return Object from a Function

#include <iostream.h>
using namespace std;
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 23
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

class Student {
public:
double marks1, marks2;
};

// function that returns object of Student


Student createStudent() {
Student student;

// Initialize member variables of Student


student.marks1 = 96.5;
student.marks2 = 75.0;

// print member variables of Student


cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;

return student;
}

int main() {
Student student1;

// Call function
student1 = createStudent();

return 0;
}

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 24


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

OUTPUT:
Marks1 = 96.5
Marks2 = 75

10. Write a program to demonstrate the use of operator overloading on unary operator &
binary operators like ++ operator and << operator.

i) ++ Operator (Unary Operator) Overloading

// Overload ++ when used as prefix and postfix

#include <iostream>
using namespace std;

class Count {
private:
int value;

public:

// Constructor to initialize count to 5


Count() : value(5) {}

// Overload ++ when used as prefix


void operator ++ () {
++value;
}

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 25


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// Overload ++ when used as postfix


void operator ++ (int) {
value++;
}

void display() {
cout << "Count: " << value << endl;
}
};

int main() {
Count count1;

// Call the "void operator ++ (int)" function


count1++;
count1.display();

// Call the "void operator ++ ()" function


++count1;

count1.display();
return 0;
}
OUTPUT:
Count: 6
Count: 7
ii) C++ Binary Operator Overloading
// C++ program to overload the binary operator +
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 26
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// This program adds two complex numbers

#include <iostream>
using namespace std;

class Complex {
private:
float real;
float imag;

public:
// Constructor to initialize real and imag to 0
Complex() : real(0), imag(0) {}

void input() {
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}

// Overload the + operator


Complex operator + (const Complex& obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}

void output() {

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 27


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

if (imag < 0)
cout << "Output Complex number: " << real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};

int main() {
Complex complex1, complex2, result;

cout << "Enter first complex number:\n";


complex1.input();

cout << "Enter second complex number:\n";


complex2.input();

// complex1 calls the operator function


// complex2 is passed as an argument to the function
result = complex1 + complex2;
result.output();

return 0;
}
OUTPUT:
Enter first complex number:
Enter real and imaginary parts respectively: 9 5
Enter second complex number:
Enter real and imaginary parts respectively: 7 6
Output Complex number: 16+11i

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 28


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

11. Write a program to demonstrate the use of function overloading.


i) function overloading example1

#include<iostream.h>
usingnamespacestd;
classprintData
{
public:
voidprint(int i)
{
cout<<"Printing int: "<< i <<endl;
}
voidprint(double f)
{
cout<<"Printing float: "<< f <<endl;
}
voidprint(char*c)
{
cout<<"Printing string: "<< c
<<endl;
}
};
int main(void)
{
printDatapd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return0;
}
Output:
Printingint:5
Printingfloat:500.263
Printing string:Hello C++

ii) function overloading example2


#include <iostream.h>
using namespace std;
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 29
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// function with 2 parameters


void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}

// function with double type single parameter


void display(double var) {
cout << "Double number: " << var << endl;
}

// function with int type single parameter


void display(int var) {
cout << "Integer number: " << var << endl;
}

int main() {

int a = 5;
double b = 5.5;

// call function with int type parameter


display(a);

// call function with double type parameter


display(b);

// call function with 2 parameters

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 30


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

display(a, b);

return 0;
}
OUTPUT:
Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5

12. Write a simple program on array of objects and pointers to objects.


i) Array of Objects in C++
// C++ program to implement
// the above approach
#include<iostream.h>
using namespace std;

class Employee
{
int id;
char name[30];
public:

// Declaration of function
void getdata();

// Declaration of function
void putdata();
};

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 31


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// Defining the function outside


// the class
void Employee::getdata()
{
cout << "Enter Id : ";
cin >> id;
cout << "Enter Name : ";
cin >> name;
}

// Defining the function outside


// the class
void Employee::putdata()
{
cout << id << " ";
cout << name << " ";
cout << endl;
}

// Driver code
int main()
{
// This is an array of objects having
// maximum limit of 30 Employees
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 32


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

// Accessing the function


for(i = 0; i < n; i++)
emp[i].getdata();

cout << "Employee Data - " << endl;

// Accessing the function


for(i = 0; i < n; i++)
emp[i].putdata();
}
OUTPUT:

ii)Array of Objects Using Pointers in C++


#include<iostream.h>
using namespace std;

class ShopItem
{
int id;
float price;

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 33


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

public:
void setData(int a, float b){
id = a;
price = b;
}
void getData(void){
cout<<"Code of this item is "<< id<<endl;
cout<<"Price of this item is "<<price<<endl;
}
};

int main()
{
int size = 3;
ShopItem *ptr = new ShopItem [size];
ShopItem *ptrTemp = ptr;
int p, i;
float q;
for (i = 0; i < size; i++)
{
cout<<"Enter Id and price of item "<< i+1<<endl;
cin>>p>>q;
// (*ptr).setData(p, q);
ptr->setData(p, q);
ptr++;
}

for (i = 0; i < size; i++)


{

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 34


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

cout<<"Item number: "<<i+1<<endl;


ptrTemp->getData();
ptrTemp++;
}

return 0;
}

OUTPUT:

13. Write programs using new, delete with classes.


#include <iostream.h>
using namespace std;

class Student {
private:
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 35
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

int age;
public:
// constructor initializes age to 12
Student() : age(12) {}
void getAge() {
cout << "Age = " << age << endl;
}
};
int main() {
// dynamically declare Student object
Student* ptr = new Student();

// call getAge() function


ptr->getAge();
// ptr memory is released
delete ptr;

return 0;
}

OUTPUT:
Age = 12

14. Write simple programs illustrating use of all types of inheritances.


a)Write a C++ Program that illustrate single inheritance.
The mechanism of deriving a new class from an old one is called inheritance or derivation
class derived-class-name : visibility-mode base-class-name
{

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 36


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

………
………
}
Program:
#include<iostream.h>
using namespace std;
class A
{
protected:
inta,b; public:
void get()
{
cout<<"Enter any two integer values"; cin>>a>>b;
}
};
class B:public A
{
int c; public:
void add()
{
c=a+b; cout<<a<<"+"<<b<<"="<<c;
}
};

int main()
{
B b; b.get();
b.add();

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 37


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

}
Output:
Enter any two integer values1 2
1+2=3
b)Write a C++ Program that illustrate multipe inheritance.
Program:
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rno,m1,m2; public:
void get()
{
cout<<"Enter the Roll no :"; cin>>rno;
cout<<"Enter the two marks :"; cin>>m1>>m2;
}
};
class sports
{
protected:
intsm; // sm = Sports mark public:
voidgetsm()
{
cout<<"\nEnter the sports mark :"; cin>>sm;
}
};
classstatement:publicstudent,public sports
{

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 38


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

inttot,avg; public:
void display()
{
tot=(m1+m2+sm); avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr(); statementobj; obj.get();
obj.getsm(); obj.display(); getch();
}
Output:
Enter the Roll no: 100 Enter two marks
90
80
Enter the Sports Mark: 90 Roll No: 100
Total : 260
Average: 86.66
c) Write a C++ Program that illustrate multi level inheritance.

Program:

#include<iostream.h>

#include<conio.h>

class top //base class

public :

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 39


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

int a;

voidgetdata()

cout<<"\n\nEnter first Number :::\t";

cin>>a;

voidputdata()

cout<<"\nFirst Number Is :::\t"<<a;

};

//First level inheritance

class middle :public top // class middle is derived_1

public:

int b;

void square()

getdata();

b=a*a;

cout<<"\n\nSquare Is :::"<<b;

};

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 40


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

//Second level inheritance

class bottom :public middle // class bottom is derived_2

public:

int c;

void cube()

square();

c=b*a;

cout<<"\n\nCube :::\t"<<c;

};

int main()
{
clrscr(); bottom b1; b1.cube();
getch();
}
Input:
Enter first number ::: 4
Output:
Square Is ::: 16 Cube ::: 64
d)Write a C++ Program that illustrate Hierarchical inheritance.
Program:
#include<iostream.h>
#include<conio.h>
class A //Base Class

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 41


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

{
public:
inta,b; voidgetnumber()
{
cout<<"\n\nEnter Number :::\t"; cin>>a;
}
};
class B : public A //Derived Class 1
{
public:
void square()
{
getnumber(); //Call Base class property cout<<"\n\n\tSquare of the number :::\t"<<(a*a); cout<<"\
n\n\t -------------------------------------------------- ";
}
};
class C :public A //Derived Class 2
{
public:
void cube()
{
getnumber(); //Call Base class property cout<<"\n\n\tCube of the number :::\t"<<(a*a*a);
cout<<"\n\n\t -------------------------------------------------- ";
}
};
int main()
{
clrscr();
B b1; //b1 is object of Derived class 1 b1.square(); //call member function of class B C c1; //c1 is

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 42


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

object of Derived class 2 c1.cube(); //call member function of class C getch();


}
Input:
Enter number ::: 2
Output:
Square of the number ::: 4
Input:
Enter number ::: 2
Output:
Cube of the number ::: 8

15. Write a program to illustrate virtual base class.


#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello from A \n";
}
};

class B : public virtual A {


};

class C : public virtual A {


};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 43


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

OUTPUT:
Hello from A

16. Write a Program to illustrate virtual functions.


#include <iostream>
using namespace std;

class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;

// pointer of Base type that points to derived1


Base* base1 = &derived1;

// calls member function of Derived class


base1->print();

return 0;
}
OUTPUT:

Derived Function

17. Write a Program to illustrate class templates.

// Simple Calculator Using Class Templates

#include <iostream>
using namespace std;

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 44


OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

template <class T>


class Calculator {
private:
T num1, num2;

public:
Calculator(T n1, T n2) {
num1 = n1;
num2 = n2;
}

void displayResult() {
cout << "Numbers: " << num1 << " and " << num2 << "." << endl;
cout << num1 << " + " << num2 << " = " << add() << endl;
cout << num1 << " - " << num2 << " = " << subtract() << endl;
cout << num1 << " * " << num2 << " = " << multiply() << endl;
cout << num1 << " / " << num2 << " = " << divide() << endl;
}

T add() { return num1 + num2; }


T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() { return num1 / num2; }
};

int main() {
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);

cout << "Int results:" << endl;


intCalc.displayResult();

cout << endl


<< "Float results:" << endl;
floatCalc.displayResult();

return 0;
}

OUTPUT:

Int results:
Numbers: 2 and 1.
2 + 1 = 3
2 - 1 = 1
2 * 1 = 2
2 / 1 = 2

Float results:
Numbers: 2.4 and 1.2.
2.4 + 1.2 = 3.6
2.4 - 1.2 = 1.2
KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 45
OBJECT ORIENTED PROGRAMMING THROUGH C++ LAB COMPUTER SCIENCE &
ENGINEERING

2.4 * 1.2 = 2.88


2.4 / 1.2 = 2

18. Write a Program to illustrate function templates.


// Adding Two Numbers Using Function Templates

#include <iostream>
using namespace std;

template <typename T>


T add(T num1, T num2) {
return (num1 + num2);
}

int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << endl;

// calling with double parameters


result2 = add<double>(2.2, 3.3);
cout << "2.2 + 3.3 = " << result2 << endl;

return 0;
}
OUTPUT:
2 + 3 = 5
2.2 + 3.3 = 5.5

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 46

You might also like