Lab Manual01 A
Lab Manual01 A
Program 1:
To implement Classes, Constructors, Inheritance, Polymorphism, Dynamic Memory
Allocation, Class Templates, Exception Handling.
Aim : C++ Programs to implement: Classes, Constructors, Inheritance, Polymorphism,
Dynamic Memory Allocation, Class Templates, Exception Handling.
Description :
1.A) Classes: A class in C++ is the building block, that leads to Object-Oriented
programming. It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A C++ class
is like a blueprint for an object.
Syntax to Define Class in C++
class className {
// some data
// some functions
};
C++ Objects
When a 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, we need to create
objects.
Syntax to Define Object in C++
classNameobjectVariableName;
Page 1
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
cin>>hours;
cin>>minutes;
cin>>seconds;
}
void Time::displayTime()
{
}
void Time::addTime(Time t1,Time t2)
{
this-> seconds=t1.seconds+t2.seconds;
this->minutes=t1.minutes+t2.minutes+this->seconds/60;
this->hours=t1.hours+t2.hours+this->minutes/60;
this->minutes=this->minutes%60;
this->seconds=this -> seconds%60;
}
int main()
{
Time t1,t2,t3;
t1.getTime();
t2.getTime();
t3.addTime(t1,t2);
t3.displayTime();
return 0;
}
Expected Output:
Enter hours
3
Enter minutes
45
Enter seconds34
Enter hours
4
Enter minutes
56
Enter seconds46
HH:MM:SS8:42:20
class MyClass{
public:
MyClass() {
Page 2
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
int main() {
MyClassmyObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
Types of Constructors
#include<iostream>
using namespace std;
class rectangle
{
int l;
int b;
public:
rectangle() // Default Constructor
{
l=5;
b=6;
}
rectangle(int l1,int b1) //Parameterized Constructor
{
l=l1;
b=b1;
}
rectangle(rectangle &r1) //copy constructor
{
Page 3
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
l=r1.l;
b=r1.b;
}
int area()
{
return(l*b);
}
};
int main()
{
rectangle r; //default constructor is called
rectangle r1(6,3); // parameterized constructor is called
rectangle r2(r1); //copy constructor is called
cout<<"Area of rectangle is"<<r.area();
cout<<"\n Area of rectangle is"<<r1.area();
cout<<"\n Area of rectangle is"<<r2.area();
return 0;
}
Expected Output:
Area of rectangle is30
Area of rectangle is18
Area of rectangle is18
Public mode: If we derive a sub class from a public base class. Thenthe public
member of the base class will become public in thederived class and protected
members of the base class will becomeprotected in derived class.
Protected mode: If we derive a sub class from a Protected baseclass. Then both public
member and protected members of thebase class will become protected in derived
class.
Private mode: If we derive a sub class from a Private base class.Then both public
member and protected members of the base classwill become Private in derived class.
Note : The private members in the base class cannot be directly accessed in thederived class,
while protected members can be directly accessed.
Syntax:
Page 4
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
Types of Inheritance
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
Single inheritance is defined as the inheritance in which a derived class isinherited from the
only one base class.
Syntax:
class base_class
{
};
class base_class :access_modederived_class
{
};
Multilevel Inheritance
If a class is derived from another derived class then it is called multilevel inheritance.
Syntax:
class A
{
};
class B: access_specifier class A
{
};
lass C: access_specifier class B
{
/
};
Multiple InheritanceIf a class is derived from two or more base classes then it is called
multiple inheritance.
Syntax
class A
{
};
Page 5
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
class B
{
};
class C :access_specifier A, access_specifier B
{
};
Hierarchical InheritanceWhen several classes are derived from common base class it is
called hierarchical inheritance.
Syntax:
class A
{
};
class B :access_specifier A
{
};
class C :access_specifier A
{
};
class D :access_specifier A
{
};
Hybrid Inheritance The inheritance in which the derivation of a class involves more than
one form of any inheritance is called hybrid inheritance. Basically C++ hybrid inheritance is
combination of two or more types of inheritance.
Syntax:
class A
{
};
class B :access_specifier A
{
};
class C
{
};
class D :access_specifierB, access_specifier C
{
};
Page 6
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
Aim:Write a Program in c++to create a base class shape and a derived class rectangle to
calculate the area of rectangle.
#include <iostream>
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout<< "Total area: " <<Rect.getArea() << endl;
return 0;
}
Expected Output:
Total area: 35
Page 7
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
And when we use the + operator with strings, it performs string concatenation.
For example,
stringfirstName = "hello ";
stringlastName = "world";
In C++, we can use two functions having the same name if they have different parameters
(either types or number of arguments).
And, depending upon the number/type of arguments, different functions are called. It's
a compile-time polymorphism because the compiler knows which function to execute before
the program is compiled.
#include<iostream>
usingnamespacestd;
intsum(int num1, int num2){
return num1 + num2;
}
doublesum(double num1, double num2){
return num1 + num2;
}
intsum(int num1, int num2, int num3){
return num1 + num2 + num3;
}
intmain(){
// Call function with 2 int parameters
cout<<"Sum 1 = "<<sum(5, 6) <<endl;
// Call function with 2 double parameters
cout<<"Sum 2 = "<<sum(5.5, 6.6) <<endl;
// Call function with 3 int parameters
cout<<"Sum 3 = "<<sum(5, 6, 7) <<endl;
return0;
}
Expected Output:
Sum 1 = 11
Sum 2 = 12.1
Sum 3 = 18
Page 8
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
In C++, we can change the way operators work for user-defined types like objects and
structures. This is known as operator overloading.
For example,
Suppose we have created three objects c1, c2 and result from a class named Complex that
represents complex numbers.
Since operator overloading allows us to change how operators work, we can redefine how
the + operator works and use it to add the complex numbers of c1 and c2 by writing the
following code:
Result = c1+c2;
Instead of:
Result = c1.addnumbers(c2);
Note: We cannot use operator overloading for fundamental data types like int, float, char and
so on.
Syntax for C++ Operator Overloading
Unary operators operate on only one operand. The increment operator ++ and decrement
operator -- are examples of unary operators.
#include<iostream>
usingnamespacestd;
classCount {
private:
int value;
public:
// Constructor to initialize count to 5
Count() : value(5) {}
Page 9
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
Expected Output:
Count: 6
Count: 7
#include<iostream>
usingnamespacestd;
classComplex {
private:
float real;
floatimag;
public:
// Constructor to initialize real and imag to 0
Complex() : real(0), imag(0) {}
voidinput(){
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;
}
Page 10
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
voidoutput(){
if (imag<0)
cout<<"Output Complex number: "<< real <<imag<<"i";
else
cout<<"Output Complex number: "<< real <<"+"<<imag<<"i";
}
};
intmain(){
Complex complex1, complex2, result;
cout<<"Enter first complex number:\n";
complex1.input();
cout<<"Enter second complex number:\n";
complex2.input();
result = complex1 + complex2; // complex1 calls the operator function
// complex2 is passed as an argument to the function
result.output();
return0;
}
Expected Output:
1. Two operators = and & are already overloaded by default in C++. For
example, to copy objects of the same class, we can directly use the = operator. We do not
need to create an operator function.
2. Operator overloading cannot change the precedence and associativity of
operators. However, if we want to change the order of evaluation, parentheses should be used.
3. There are 4 operators that cannot be overloaded in C++. They are:
1. :: (scope resolution)
2. . (member selection)
3. .* (member selection through pointer to function)
4. ?: (ternary operator)
1.G) Templates:Templates are powerful features of C++ which allows us to write generic
programs. In simple terms, we can create a single function or a class to work with different
data types using templates.Templates are often used in larger codebase for the purpose of
code reusability and flexibility of the programs.
The concept of templates can be used in two different ways:
Function Templates
Class Templates
Function Templates
A function template works in a similar to a normal function, with one key difference.
Page 11
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
A single function template can work with different data types at once but, a single normal
function can only work with one set of data types.
Normally, if you need to perform identical operations on two or more types of data, you use
function overloading to create two functions with the required function declaration.
However, a better approach would be to use function templates because you can perform the
same task writing less and maintainable code.
How to declare a function template?
A function template starts with the keyword template followed by template parameter/s
inside <> which is followed by function declaration.
template<class T>
T someFunction(T arg)
{
... .. ...
}
#include<iostream>
usingnamespacestd;
// template function
template<classT>
TLarge(Tn1, Tn2)
{
if (n1 > n2)
return(n1);
else
return(n2);
}
intmain()
{
int i1, i2;
float f1, f2;
char c1, c2;
return0;
}
Page 12
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
Expected Output:
Enter two integers:
5
10
10 is larger.
Class Templates
Like function templates, we can also create class templates for generic class
operations.Sometimes, we need a class implementation that is same for all classes,
only the data types used are different.
Normally, we would need to create a different class for each data type OR create
different member variables and functions within a single class.
This will unnecessarily bloat our code base and will be hard to maintain, as a change is
one class/function should be performed on all classes/functions.
However, class templates make it easy to reuse the same code for all data types.
Aim:Program to add, subtract, multiply and divide two numbers using class template
#include<iostream>
Usingnamespacestd;
Page 13
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
template<classT>
classCalculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
voiddisplayResult()
{
cout<<"Numbers are: "<< num1 <<" and "<< num2 <<"."<<endl;
cout<<"Addition is: "<<add() <<endl;
cout<<"Subtraction is: "<<subtract() <<endl;
cout<<"Product is: "<<multiply() <<endl;
cout<<"Division is: "<<divide() <<endl;
}
T add(){ return num1 + num2; }
T subtract(){ return num1 - num2; }
T multiply(){ return num1 * num2; }
T divide(){ return num1 / num2; }
};
intmain()
{
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();
return0;
}
Expected Output:
Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2
Page 14
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
After delete is called on a memory region, that region should no longer be accessed by the
program.
Aim :Write a program to create an array dynamically , read the elements in an array
and print an array.
include <iostream>
using namespace std;
int main ()
{
int i,n;
int * p;
cout<< "How many numbers would you like to type? ";
cin>>i;
p= new (nothrow) int[i];
if (p == 0)
cout<< "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout<< "Enter number: ";
Page 15
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
cin>> p[n];
}
cout<< "You have entered: ";
for (n=0; n<i; n++)
cout<< p[n] << ", ";
delete[] p;
}
return 0;
}
Expected Output:
How many numbers would you like to type? 5
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
You have entered: 1, 2, 3, 4, 5,
Exceptions are runtime anomalies or unusual conditions that a program may encounter
while executing.
Exception handling mechanism provides a means to detect and report an exception
circumstances.
Find the problem (Hit the exception)
Inform that an error has occurred(Throw the exception)
Receive the error information(Catch the exception)
Take corrective actions(Handle the exception)
The exception handling mechanism is built upon three keywords:
1. Try
Is used to preface a block of statements which may generate exceptions.
2. Throw
When an exception is detected, it is thrown using a throw statement in the try block
3. Catch
A catch block defined by the keyword catch catches the exception thrown by the throw
statement in the try block and handles it appropriately.
#include<iostream>
using namespace std;
int main()
{
int a=10,b=0;
try
{
if (b==0)
{
throw "division by zero not possible";
}
}
catch (const char *ex)
Page 16
SCET DATA STRUCTURES AND ALGORITHMS LAB MANUAL
{
cout<<ex;
}
return 0;
}
Expected Output:
division by zero not possible
Page 17