[go: up one dir, main page]

0% found this document useful (0 votes)
514 views35 pages

BEC358C-c++ Lab Manual-Updated

Uploaded by

9ch7sh4mcm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
514 views35 pages

BEC358C-c++ Lab Manual-Updated

Uploaded by

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

DON BOSCO INSTITUTE OF TECHNOLOGY

Kumbalagodu, Mysore Road, Bangalore - 560 074

DEPARTMENT OF ELECTRONICS & COMMUNICATION


(ACADEMIC YEAR 2023-24)

C++ Basics MANUAL


(BEC358C)
SEMESTER: III

Name of the Student: ………………………………………….

USN No. of the Student:

………………………………………..
C++ Basics III SEM

WAYANAMAC EDUCATION TRUST

VISION
Don Bosco group of institutions shines brighter each day with a vision to achieve a world class status in
providing exceptionally excellent higher education in the field of Management, Technology and Applied
Science entrenched with Human Values.

MISSION
With a mission to provide refined high quality technical education and training to aspiring students, we at
Don Bosco, strive to impart exclusively valuable, academic knowledge relating to an array of professional
fields undertaken.
Our persistent efforts will evidently create and develop future technocrats and proficient business leaders
who will confidently attend to improve the quality of life for the current generation.

DON BOSCO INSTITUTE OF TECHNOLOGY


VISION
To become a world-class centre in providing globally relevant higher education in the field of
management, technology and applied science embedded with human values.

MISSION
To foster an intellectual and ethical environment in which both skill and spirit will thrive so as to impart
high quality education, training, and service with an international outlook. To create and develop
technocrats and business leaders who will strive to improve the quality of life.

DEPARTMENT OF ELECTRONICS & COMMUNICATION


VISION
To impart value based technical education and train students through continuous improvement in
effectiveness and efficiency of teaching, learning and associated processes and to collaborate with industry,
foreign universities and institutions for academic exchange program for faculty and students.

MISSION
To provide an excellent learning opportunity for all students and staff to develop knowledge and skills
essential in enlightening the individual’s ability to think vitally and utilize Electronics in detail to meet the
technological challenges of tomorrow and to refine knowledge and understanding through research and
creative activities.

DEPT OF ECE, DBIT Page 1


C++ Basics III SEM

PROGRAMME EDUCATIONAL OBJECTIVES AND PROGRAMME OUTCOMES

PROGRAMME EDUCATIONAL OBJECTIVES:

⮚ Program Educational Objective 1: To prepare students for graduate and postgraduate programmes so
as to make them succeed in careers related to Electronics & Communication Engineering fields.
⮚ Program Educational Objective 2: To provide students with strong foundation in fundamental
concepts required in mathematical, scientific and engineering fields to make them succeed in their
technical profession.
⮚ Program Educational Objective 3: To train students with a broad-based scientific and engineering
knowledge so as to comprehend, analyze, design, and create innovative products and solutions for the
real life problems.
⮚ Program Educational Objective 4: To inculcate in students strong professional ethics along with a
strong character to uphold the spiritual and cultural values, effective communication skills, teamwork
skills, multidisciplinary approach, and ability to relate engineering issues to broader social context.
⮚ Program Educational Objective 5: To provide an academic environment and ambience so as to make
the students aware of advanced technological growth leading to life-long learning needed for a successful
professional career, excellence and leadership

PROGRAMME OUTCOMES:

a) Ability to apply knowledge of mathematics, science, and engineering


b) Ability to design and conduct experiments, as well as to analyze and interpret data
c) Ability to design a system, component, or process to meet desired needs within realistic constraints
such as economic, environmental, social, political, ethical, health and safety, manufacturability, and
sustainability
d) Ability to function with multidisciplinary teams
e) Ability to identify, formulates, and solves (complex) engineering problems
f) Understanding of professional and ethical responsibility
g) Ability to communicate effectively
h) Equipped with broad education necessary to understand the impact of engineering solutions in a
global, economic, environmental, and societal context
i) Recognize the need for and be able to engage in - life-long learning
j) Knowledge of contemporary issues,
k) Ability to use the techniques, skills, and modern engineering tools necessary for engineering
practice and
l) Ability to understand and apply knowledge of advanced mathematics, including probability and
statistics, differential and integral calculus, linear algebra and complex variables.

DEPT OF ECE, DBIT Page 2


C++ Basics III SEM

CONTENT LIST
SL. PAGE
EXPERIMENT NAME
NO. NO.
Write a C++ program to find largest, smallest & second largest of three numbers
1. using inline functions MAX & Min 05
Write a C++ program to calculate the volume of different geometric shapes like
2. 06
cube, cylinder and sphere using function overloading concept.
Define a STUDENT class with USN, Name & Marks in 3 tests of a subject. Declare
an array of 10 STUDENT objects. Using appropriate functions, find the average
3. of the two better marks for each student. Print the USN, Name & the average
07
marks
of all the students.
Write a C++ program to create class called MATRIX using two-dimensional array
of integers, by overloading the operator == which checks the compatibility of
4. two matrices to be added and subtracted. Perform the addition and subtraction 09
by overloading + and – operators respectively. Display the results by
overloading the
operator
Demonstrate simple inheritance concept by creating a base class FATHER with
data members: First Name, Surname, DOB & bank Balance and creating a
5. derived class SON, which inherits: Surname & Bank Balance feature from base 13
class but
provides its own feature: First Name & DOB. Create & initialize F1 & S1
objects with appropriate constructors & display the FATHER & SON details.
Write a C++ program to define class name FATHER & SON that holds the income
6. 15
respectively. Calculate & display total income of a family using Friend function.
Write a C++ program to accept the student detail such as name & 3 different
marks by get_data() method & display the name & average of marks using
7. display() method. Define a friend function for calculating the average marks
18
using the method mark_avg().
Write a C++ program to explain virtual function (Polymorphism) by creating a
base class polygon which has virtual function areas two classes rectangle &
8. 20
triangle derived from polygon & they have area to calculate & return the area of
rectangle & triangle respectively.
Design, develop and execute a program in C++ based on the following
requirements: An EMPLOYEE class containing data members & members
functions: i) Data members: employee number (an integer), Employee_ Name (a
string of characters), Basic_ Salary (in integer), All_ Allowances (an integer),
9. 23
Net_Salary (an integer). (ii) Member functions: To read the data of an
employee, to calculate Net_Salary & to print the values of all the data members.
(All_Allowances = 123% of Basic, Income Tax (IT) =30% of gross salary (=basic_
Salary_All_Allowances_IT).
Write a C++ program with different class related through multiple inheritance &
10. demonstrate the use of different access specified by means of members variables 25
& members functions.
Write a C++ program to create three objects for a class named count object with
data members such as roll_no & Name. Create a members function set_data ( )
11.
for setting the data values & display ( ) member function to display which object
28
has invoked it using „this‟ pointer

DEPT OF ECE, DBIT Page 3


C++ Basics III SEM
Write a C++ program to implement exception handling with minimum 5
12. exceptions classes including two built in exceptions. 50

DEPT OF ECE, DBIT Page 4


C++ Basics III SEM

Program 1

Write a C++ program to find largest, smallest & second largest of three numbers using inline functions MAX & Min

#include<iostream>
using namespace std;
inline int max(int x,int y,int z)
{
if(x>y&&x>z)
return(x);
else if(y>z)
return(y);
else
return(z);
}
inline int min(int x,int y,int z)
{
if(x<y&&x<z)
return(x);
else if(y<z)
return(y);
else
return(z);
}
int main()
{
int a,b,c,seclargest;
cout<<" enter three numbers:"<< endl;
cin >>a>>b>>c;
cout<<max(a,b,c)<<" is larger" << endl;
cout<<min(a, b, c) <<"is smallest"<< endl;
seclargest=(a+b+c)-((max(a,b,c)+min(a,b,c)));
cout<<"second largest is"<<seclargest<<endl;
return(0);
}

DEPT OF ECE, DBIT Page 5


C++ Basics III SEM

Program2:
Write a C++ program to calculate the volume of different geometric shapes like cube, cylinder and sphere
using function overloading concept.

#include<iostream >
using namespace std;
float vol(int,int);
float vol(float);
int vol(int);
int main()
{
int r,h,a;
float r1;
cout<<"enter radius and height of a cylinder:";
cin>>r>>h;
cout<<"enterside of cube:";
cin>>a;
cout<<"enter radius of sphere:";
cin>>r1;
cout<<"volume of cylinder is"<<vol(r,h);
cout<<"\nvolume of cube is "<<vol(a);
cout<<"\n volume of sphere is: "<<vol(r1);
return 0;
}
float vol(int r, int h)
{
return(3.14*r*r*h);
}
float vol(float r1)
{
return((4*3.14*r1*r1*r1)/3);
}
int vol(int a)
{
return(a*a*a);
}

DEPT OF ECE, DBIT Page 6


C++ Basics III SEM

Program3:

Define a STUDENT class with USN, Name & Marks in 3 tests of a subject. Declare an array of 10
STUDENT objects. Using appropriate functions, find the average of the two better marks for each student.
Print the USN, Name & the average marks of all the students.

#include<iostream>
#include<string>
using namespace std;
class STUDENT
{
public:
string name,USN;
int s1,s2,s3;
void read()

{
std::cout<<"enter the name";
std::cin>>name;
std::cout<<"enter the sub1 marks";
std::cin>>s1;
std::cout<<"enter the sub2 marks";
std::cin>>s2;
std::cout<<"enter the sub3 marks";
std::cin>>s3;

}
void disp()
{
std::cout<<"\nName"<<name;
std::cout<<"\nUSN"<<USN;
std::cout<<"\n sub1
mks"<<s1; std::cout<<"\n
sub2 mks"<<s2; std::cout<<"\
n sub3 mks"<<s3;
}
void average()
{
int
m1,m2;
float avg;
if(s1>s2 && s1>s3)
{
m1=s1;
if(s2>s3)
m2=s2;
else m2=s3;
}
else if(s2>s3 && s2>s1)

DEPT OF ECE, DBIT Page 7


C++ Basics III SEM
{
m1=s2;

DEPT OF ECE, DBIT Page 8


C++ Basics III SEM

if(s3>s1)
m2=s3;
else
m2=s1;
}
else
{
m1=s3;
if(s1>s2)
m2=s1;
else
m2=s2;
}
avg=(m1+m2)/2.0;
std::cout<<"\n the average marks"<<avg;
}
};
int main()
{
STUDENT A[10];
for(int i=0;i<3;i++)
{
std::cout <<"\n enter the details of "<<i+1<<"student\n";

A[i].read();
}
for(int i=0;i<3;i++)
{
std::cout <<"\nenter the details of "<<i+1<<"student\
n"; cout<<"-----";
A[i].disp();
}
for(int i=0;i<3;i++)
{
std:cout <<"\n average of "<<i+1<<"student\n";

A[i].average();

return 0;
}

DEPT OF ECE, DBIT Page 9


C++ Basics III SEM

Program 4 :

Write a C++ program to create class called MATRIX using two-dimensional array of integers, by
overloading the operator == which checks the compatibility of two matrices to be added and subtracted.
Perform the addition and subtraction by overloading + and – operators respectively. Display the results by
overloading the operator

#include <iostream>
using namespace std;
class matrix
{
int a[3][3];
public:
void accept();
void display();
void operator+(matrix x);
void operator-(matrix x);
};
void matrix::accept()
{
cout<<"\n enter matrix element (3*3):\n";
for(int i=0; i<3;i++)
{
for(int j=0; j<3;j++)
{
cout<<" ";
cin>>a[i][j];
}
}
}
void matrix::display()
{
for(int i=0; i<3;i++)
{
for(int j=0; j<3;j++)
{
cout<<a[i][j]<<"\t" ;
}
cout<<"\n";
}
}
void matrix::operator+(matrix x)
{
int mat[3][3];
for(int i=0; i<3;i++)
{
for(int j=0; j<3;j++)
{

DEPT OF ECE, DBIT Page


10
C++ Basics III SEM
mat[i][j]=a[i][j]+x.a[i][j];
}
}
cout<<"\n addition of matrix:\n\n";
for(int i=0; i<3;i++)
{
cout<<" ";
for(int j=0; j<3;j++)
{
cout<<mat[i][j]<<"\t";
}
cout<<"\n";
}
}
void matrix::operator-(matrix x)
{
int mat[3][3];
for(int i=0; i<3;i++)
{
for(int j=0; j<3;j++)
{
mat[i][j]=a[i][j]-x.a[i][j];
}
}
cout<<"\n subtraction of matrix:\n\n";
for(int i=0; i<3;i++)
{
cout<<" ";
for(int j=0; j<3;j++)
{
cout<<mat[i][j]<<"\t";
}
cout<<"\n";
}
}
int main()
{
matrix m,n;
m.accept();
n.accept();
cout<<"\n first matrix:\n\n";
m.display();
cout<<"\n second matrix:\n\n";
n.display();
m+n;
m-n;
return 0;
}

DEPT OF ECE, DBIT Page


11
C++ Basics III SEM

Output

Enter matrix elements (3*3)


246
8 10 22
246

Enter matrix elements (3*3)


132
546
547

First matrix
2 4 6
8 10 22
2 4 6

Second matrix
1 3 2
5 4 6
5 4 7

Addition of Matrices is :
3 7 8
13 14 28
7 8 13

Subtraction of Matrices is :

1 1 4
3 6 16
-3 0 -1

DEPT OF ECE, DBIT Page 12


C++ Basics III SEM

Program 5

Demonstrate simple inheritance concept by creating a base class FATHER with data members: First Name,
Surname, DOB & bank Balance and creating a derived class SON, which inherits: Surname & Bank
Balance feature from base class but provides its own feature: First Name & DOB. Create & initialize F1 &
S1 objects with appropriate constructors & display the FATHER & SON details.

#include <iostream>
#include <string>
using namespace std;

class Father
{ protected:
string surname;
double bankBalance;

public:
Father (string surname, double bankBalance)
: surname(surname), bankBalance(Balance) {}

void displayFatherDetails() {

cout << "fATHER’S Details: “<< endl;


cout << "Surname: " << surname << endl;
cout << "Bank Balance: " << bankBalance << endl;
}
};

class Son: public Father {


private:
string firstName;
string dob;

public:
Son(string firstName, string dob, string surname, double bankBalance)
: firstName(firstName), dob(dob), Father (surname, balance) {}

void displaySonDetails() {
cout << "\nSon’s Details:" << endl;
cout << "firstName:" << firstName<<endl;
cout << "Date of Birth: " << dob << endl;
cout << "Surname:" << Surname<<endl;

DEPT OF ECE, DBIT Page 13


C++ Basics III SEM

cout << "Balance:" << bankBalance<<endl;

} };

int main ()

{
Son S1("John", "2000-05-10", "Smith", 2000.00);
Father F1("Smith", 50000.00);
S1. displaySonDetails();
F1. displayFatherDetails();
return 0;
}

Output:

Father's Details:
Surname: Smith
Bank Balance: $50000

Son's Details:
Surname: Smith
Bank Balance:
$2000 First Name:
John
Date of Birth: 2000-05-10

DEPT OF ECE, DBIT Page 14


C++ Basics III SEM

Program 6:
Write a C++ program to define class name FATHER & SON that holds the income respectively.
Calculate & display total income of a family using Friend function.

A friend function can access the private and protected data of a class. We declare a friend function
using the friend keyword inside the body of the class.

#include <iostream>
#include<conio.h>
using namespace std;
class father;
class son
{
private:
char name[15];
float income;
public:
void read();
void show();
friend void cal(father f,son s);
};
class father
{
private:
char name[15];
float salary;
public:
void read();
void show();
friend void cal(father f,son s);
};

DEPT OF ECE, DBIT Page 15


C++ Basics III SEM

void father::read()
{
cout<<"Enter name and salary ";
cin>>name>>salary;
}
void father::show()
{
cout<<name<<" "<<salary<<endl;
}
void son::read()
{
cout<<"Enter name and income ";
cin>>name>>income;
}
void son::show()
{
cout<<name<<" "<<income<<endl;
}
void cal(father f,son s)
{
float t;
t=f.salary+s.income;
cout<<"Total family income "<<t<<endl;
cout<<"Avg family income
"<<t/2<<endl;
}
int main()
{
father f1;
son s1;
f1.read();
s1.read();
f1.show();

DEPT OF ECE, DBIT Page 16


C++ Basics III SEM

s1.show();
cal(f1,s1);
return(0);
}

Output
Enter name and salary Amit
45000
Enter name and income Sunita
54000
Amit 45000
Sunita 54000
Total family income
99000 Avg family income
49500

DEPT OF ECE, DBIT Page 17


C++ Basics III SEM

Program 7:
Write a C++ program to accept the student detail such as name & 3 different marks by get_data() method &
display the name & average of marks using display() method. Define a friend function for calculating the
average marks using the method mark_avg().

#include<iostream>
#include<string>
using namespace std;
class Student{
string name;
int mark1, mark2, mark3;

public:
void get_data(){
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Marks in Subject 1: ";
cin >> mark1;
cout << "Enter Marks in Subject 2: ";
cin >> mark2;
cout << "Enter Marks in Subject 3: ";
cin >> mark3;
}

friend float mark_avg(Student


s); void display()
{
cout << "Name: " << name << endl;
cout << "Average Marks: " << mark_avg(*this) << endl;
}};

float mark_avg(Student s)
{
return (s.mark1 + s.mark2 + s.mark3)/3.0;
}

int main()
{ Student s;
s.get_data();
s.display();
return 0; }

DEPT OF ECE, DBIT Page 18


C++ Basics III SEM

Output:

Enter Name: Harish


Enter Marks in Subject 1: 98
Enter Marks in Subject 2: 86
Enter Marks in Subject 3: 78
Name: Harish
Average Marks: 87.3333

In the above program, we have defined a class `Student` with member variables `name`, `mark1`,
`mark2`, and `mark3`. The member functions `get_data()` and `display()` are used to accept and display
the student details respectively.
The `mark_avg()` function is declared as a friend of the `Student` class. It takes a `Student` object as
input and calculates the average marks of the student by summing up the marks in three different subjects
and dividing by 3.
In the `main()` function, we create an object `s` of the `Student` class, call the `get_data()` function to
accept the student details, and then call the `display()` function to display the student name and average
marks calculated using the `mark_avg()` function.

DEPT OF ECE, DBIT Page 19


C++ Basics III SEM

Program 8

Write a C++ program to explain virtual function (Polymorphism) by creating a base class polygon which
has virtual function areas two classes rectangle & triangle derived from polygon & they have area to
calculate & return the area of rectangle & triangle respectively.

#include <iostream>
using namespace
std;

class Polygon
{ protected:
double width, height;

public:
Polygon(double w, double h)
{ width = w;
height = h;
}

virtual double area() {


cout << "Parent class area():
"; return 0;
}
};

class Rectangle : public Polygon {


public:
Rectangle(double w, double h) : Polygon(w, h) {}

double area() {
cout << "Rectangle class area(): ";
return (width * height);
}
};

class Triangle : public Polygon {


public:
Triangle(double w, double h) : Polygon(w, h) {}

double area() {
cout << "Triangle class area(): ";
return (width * height / 2);
}};
DEPT OF ECE, DBIT Page 20
C++ Basics III SEM

int main() {
int RectLength, RectWidth, TriBase, TriHeight;
Polygon *poly1, *poly2;
cout<<"Enter the Length of RECT";
cin>>RectLength;
cout<<"Enter the width of RECT";
cin>>RectWidth;
cout<<"Enter the Base of TRI";
cin>>TriBase;
cout<<"Enter the Height of TRI";
cin>>TriHeight;
Rectangle rect(RectLength, RectWidth);
Triangle tri(TriBase, TriHeight);

poly1 = &rect;
poly2 = &tri;

cout << poly1->area() <<


endl; cout << poly2->area()
<< endl;

return 0;
}

Output:
Enter the Length of RECT 5
Enter the width of RECT 5
Enter the Base of TRI 3
Enter the Height of TRI 3
Rectangle class area(): 25
Triangle class area(): 10.5

C++ program to explain virtual functions (polymorphism) by creating a base class Polygon which has a
virtual function area(), and two derived classes Rectangle and Triangle that inherit from the Polygon
class and implement the area() function to calculate and return the area of rectangle and triangle
respectively.
In this program, we define a base class Polygon with two protected data members width and height and a
virtual function area(). The Rectangle and Triangle classes are derived from the Polygon class.

The area() function is defined as virtual in the Polygon class. This means that when a pointer of type
Polygon points to an object of the Rectangle or Triangle class, the correct version of the area() function is
called based on the type of the object being pointed to.

DEPT OF ECE, DBIT Page 21


C++ Basics III SEM
In the main() function, we create objects of Rectangle and Triangle classes, and then create two pointers
of type Polygon to point to these objects.

DEPT OF ECE, DBIT Page 22


C++ Basics III SEM

We then call the area() function using these pointers. The virtual function area() is called based on the
type of object being pointed to, so the correct version of area() is called for Rectangle and Triangle
objects respectively.
This is an example of polymorphism, where the same function name area() is used for both Rectangle and
Triangle classes, but they have different implementations, based on their individual needs.

DEPT OF ECE, DBIT Page 23


C++ Basics III SEM

Program 9

Design, develop and execute a program in C++ based on the following requirements: An EMPLOYEE
class containing data members & members functions: i) Data members: employee number (an integer),
Employee_ Name (a string of characters), Basic_ Salary (in integer), All_ Allowances (an integer),
Net_Salary (an integer). (ii) Member functions: To read the data of an employee, to calculate Net_Salary &
to print the values of all the data members. (All_Allowances = 123% of Basic, Income Tax (IT) =30% of
gross salary (=basic_ Salary_All_Allowances_IT).

#include <iostream>
#include <string>
using namespace std;

class Employee {
int empNumber, basicSalary, allowances, netSalary;

string empName;
public:
void readData() {
cout << "Enter Employee Number: ";
cin >> empNumber;
cout << "Enter Employee Name: ";
cin.ignore();
getline(cin, empName);
cout << "Enter Basic Salary:
"; cin >> basicSalary;
}

void calculateNetSalary()
{ allowances = 1.23 * basicSalary;
int grossSalary = basicSalary + allowances;
int incomeTax = 0.3 * grossSalary;
netSalary = grossSalary - incomeTax;
}

void printData() {
cout << "Employee Number: " << empNumber <<
endl; cout << "Employee Name: " << empName <<
endl; cout << "Basic Salary: " << basicSalary << endl;
cout << "Allowances: " << allowances <<
endl; cout << "Net Salary: " << netSalary <<
endl;
}};

DEPT OF ECE, DBIT Page 24


C++ Basics III SEM

int main()
{ Employee e;
e.readData();
e.calculateNetSalary();
e.printData();
return 0;
}

Output:

Enter Employee Number:


123 Enter Employee Name:
harish Enter Basic Salary:
47400 Employee Number:
123 Employee Name: harish
Basic Salary: 47400
Allowances: 58302
Net Salary: 73992

In the above program, we have defined an Employee class with data members empNumber,
empName, basicSalary, allowances, and netSalary. The member functions readData(),
calculateNetSalary(), and printData() are used to read the data of an employee, calculate the net
salary, and print the values of the data members respectively.
In the readData() function, we accept the employee number, employee name, and basic salary from
the user using cin and getline() functions.
In the calculateNetSalary() function, we calculate the allowances as 123% of the basic salary, and then
calculate the gross salary by adding the basic salary and allowances. We then calculate the income tax
as 30% of the gross salary and subtract it from the gross salary to get the net salary.
In the printData() function, we display all the data members of the Employee class using cout statements.
In the main() function, we create an object e of the Employee class, call the readData() function to accept
the employee details, then call the calculateNetSalary() function to calculate the net salary and finally call
the printData() function to display all the details.

DEPT OF ECE, DBIT Page 25


C++ Basics III SEM

Program 10

Write a C++ program with different class related through multiple inheritance & demonstrate the use of
different access specified by means of member’s variables & members functions.

Multiple Inheritance is the concept of the Inheritance in C++ that allows a child class to inherit properties
or behaviour from multiple base classes. Therefore, we can say it is the process that enables a derived class
to acquire member functions, properties, characteristics from more than one base class.

Syntax of the Multiple Inheritance


class A
{
// code of class A
}
class B
{
// code of class B
}
class C: public A, public B (access modifier class_name)
{
// code of the derived class
}

#include <iostream>

using namespace

std;

// Base class

class Shape

{ public:

void displayShape() {

cout << "This is a shape." << endl;

};

DEPT OF ECE, DBIT Page 26


C++ Basics III SEM

// First derived class

class Rectangle : public Shape {

public:

void displayRectangle() {

cout << "This is a rectangle." << endl;

};

// Second derived class

class Circle : public Shape

{ public:

void displayCircle() {

cout << "This is a circle." << endl;

};

// Derived class inheriting from Rectangle and Circle

class RoundedRectangle : public Rectangle, public Circle {

public:

void displayRoundedRectangle() {

cout << "This is a rounded rectangle." << endl;

// Resolve ambiguity for displayShape()

void displayShape() {

Rectangle::displayShape();

}};

DEPT OF ECE, DBIT Page 27


C++ Basics III SEM

int main() {

RoundedRectangle rr;

// Accessing member functions

rr.displayShape(); // Accessible through RoundedRectangle

rr.displayRectangle(); // Accessible through Rectangle

rr.displayCircle(); // Accessible through Circle

rr.displayRoundedRectangle(); // Accessible through

RoundedRectangle

// Accessing member variables

rr.Rectangle::displayShape(); // Accessible through

Rectangle rr.Circle::displayShape(); // Accessible through

Circle return 0;

DEPT OF ECE, DBIT Page 28


C++ Basics III SEM

Program 11

Write a C++ program to create three objects for a class named count object with data member such as
roll_no & Name. Create a members function set_data ( ) for setting the data values & display ( ) member
function to display which object has invoked it using „this‟ pointer

#include <iostream>
using namespace std;
class CountObject {
private:
int roll_no;
string name;

public:
void set_data(int roll, const string& studentName)
{ roll_no = roll;
name = studentName;
}
void display(string obj) {

cout << "Roll No: " << roll_no << endl;


cout << "Name: " << name << endl;
cout << "Object Name: " << obj << endl;
cout << "Object Address: " << this << endl;
cout << endl;
}
};
int main() {
CountObject obj1, obj2,
obj3; obj1.set_data(1,
"Rama"); obj2.set_data(2,
"Krishna"); obj3.set_data(3,
"Shiva");
DEPT OF ECE, DBIT Page 29
C++ Basics III SEM
cout << "Object 1:" << endl;
obj1.display("obj1");
cout << "Object 2:" << endl;
obj2.display("obj2");
cout << "Object 3:" << endl;
obj3.display("obj3");
return 0;
}

DEPT OF ECE, DBIT Page 30


C++ Basics III SEM

Program 12

Write a C++ program to implement exception handling with minimum 5 exceptions classes including two
built in exceptions.

C++ try and catch:

Exception handling in C++ consists of three keywords: try, throw and catch:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The throw keyword throws an exception when a problem is detected, which lets us create a custom error.

The catch statement allows you to define a block of code to be executed if an error occurs in the try block.

#include<iostream>

using namespace std;

nt main()

int numerator,denominator,result;

cout<<"enter numerator and denominator:"<<endl;

cin>>numerator>>denominator;

try

if (denominator==0)

throw denominator;

result=numerator|denominator;

catch(int ex)

cout<<"exception:divide by zero not allowed"<<endl;

DEPT OF ECE, DBIT Page 31


C++ Basics III SEM
}

cout<<"division is:"<<result;

return 0;

Output:
Enter numerator and denominator
12
10
Division is : 1

DEPT OF ECE, DBIT Page 32


C++ Basics III SEM

C++ Basics VIVA Questions


1. Who invented C++?
a) Dennis Ritchie
b) Ken Thompson
c) Brian Kernighan
d) Bjarne Stroustrup
2. What is C++?
a) C++ is an object oriented programming language
b) C++ is a procedural programming language
c) C++ supports both procedural and object oriented programming language
d) C++ is a functional programming language
3. Which of the following user-defined header file extension used in c++?
a) hg
b) cpp
c) h
d) hf
4. . Which of the following is used for comments in C++?
a) /* comment */
b) // comment */
c) // comment
d) both // comment or /* comment */
5. Which of the following approach is used by C++?
a) Left-right
b) Right-left
c) Bottom-up
d) Top-down
6. What will be the output of the following C++ code?

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
char s1[6] = "Hello";
char s2[6] = "World";
char s3[12] = s1 + " " + s2;
cout<<s3;
return 0;
}

7. What is the value of p in the following C++ code snippet?


#include <iostream>
using namespace std;
int main()
{
int p;
bool a = true;
bool b = false;
int x = 10;

DEPT OF ECE, DBIT Page 33


C++ Basics III SEM
int y = 5;
p = ((x | y) + (a +
b)); cout << p;
return 0;
}

DEPT OF ECE, DBIT Page 34

You might also like