Uploaded by Siddharth Mittal

2K22-SE-172 Siddharth Mittal (OOPS Assignment 2)

advertisement
SE-203
OBJECT ORIENTED
PROGRAMMING
ASSIGNMENT - 2
Submitted by Siddharth Mittal
2K22/SE/172
Q1)List the different operators in C++ with code snippets demonstrating their functionality
Ans. The different operators new to Ctt are 1)
Input-Output Operators
<< (Insertion or put to) - Used for output, typically to display data on the console or
write it to a file. It is often used with the cout stream.
>> (Extraction or get from) - Used for input to read data from the console or from a
file into a variable. It is commonly used with the cin stream.
2)
Reference Operator
& - Used to create another reference identifier to an existing variable.
3)
Class Member Access Operators
.(dot)
Used to access a class member using object name.
->-Used to access a class member using pointer to object.
4)
Scope Resolution Operator (::)
:: - Ithas multiple uses Accessing Global Variables or Functions
o Accessing Namespaces
o Defining Member Functions Outside the Class
o Accessing Class or Structure Members
o Accessing Classes in Multiple Inheritance
o Accessing Nested Classes
Accessing Static Members of Class
5)
Member Dereferencing Operators
:* - Used in either declaration of apointer to a class member or access member
using class name and pointer tomember.
-* -Used to access a class member using a pointer to an object and pointer to
member.
6)
Dynamic Memory Management Operators
new - Used to dynamically allocate memory.
delete - Used to deallocate dynamically allocaled memory using new.
7)
Miscellaneous Operators
sizeof) - Used to determine the size (in bytes) of a datatype or an object.
Iypecast - Used for typeconversion of an expression.
typeid -
Used to obtain information about the type of an expression or an object
at runtime.
CODES -
/Demonstrating the input and output operators '<< and >
#include <iostream>
using namespace std;
int main)
int n;
cout<<'enter a number:":
cin>>n;
cout<<"'number is "<<n<<endl:
return 0;
I/Demonstrating the '&' reference operator
#include <iostream>
using namespace std;
int main)
int x = 42:
cout<<"x="<<x<<endl;
x
int& y X;I/ yis areference tovalue
of x to 55
the
modifies
y=55; I/ This
cout<<"x="<<x<Kendl:
return 0;
/Demonstrating class member access operators
lland member dereferencing operators
#include <iostream>
using namespace std;
int main(0
class Demo
public:
int x;
Demo obj;
obj.x =42; l/Accessing class member using'"
cout<<"x="<<x<Kendl:
obj_ptr-&obj;
obj_ptr->x-30; //Accessing class member using '->'
cout<<"x="<<x<<endl;
int Demo:* mem ptr-&Demo::x; /Using ':* tocreate a pointer to a class member
obj.*mem ptr-69; lAccessing class member using':
cout<<"x="<<x<<endl;
obj ptr->*mem ptr-11; /Accessing class member using '->**
cout<<"x="<<x<Kendl;
return 0;
I/Demonstrating all functionalities of
l/the scope resolution operator
#include <iostream>
using namespace std;
/ Global variable
int globalVar=10;
|/Outer class
class Outer
public:
static int staticVar; // Static variable inside Outer class
1/ Nested class
class Inner
public:
static int innerVar; // Staticvariable inside Inner class
|/ Member function of lnner class
void displaylnnerVar()
cout<<"nner::innerVar: "<<innerVar<<<endl;
I/ Member function of Outer class
void displayStaticVar)
cout <<"Outer::staticVar: "<<staticVar<<endl;
I| Initialize static variables
int Outer::staticVar = 20;
int Outer::Inner: innerVar = 30;
int main()
int global Var = 5; |/Local variable with the same name as the global one
cout<<"Local globalVar: "<<globalVar <<endl;
cout<<"Global globalVar: "<K:globalVar <<endl;
Outer outerObj:
Outer::Inner innerObj;
outerObj.displayStaticVar();
innerObj.displaylnnerVar();
return 0;
I/Demonstrating use of new and delete operators
#include <iostream>
using namespace std;
int main(0
int *arr:
int size;
cout<<"Enter array size:";
cin>>size;
arr = new int[size ]; //Dynamic memoryallocation
cout<<"nMemory allocated to array dynamically... "<<endl:
cout<<"nEnter array elements:";
for(inti=0;i<size;i++)
cin>>arr[i];
cout<<"\nArray elements are: ";
for(inti=0:;i<size;i++)
cout<<arrlil<<"";
cout<<"\n\nDeleting array...array memory deallocated";
delete arr; /Freeing of dynamically allocated memory
return 0:
I/Demonstrating the sizeof(). typecast
l/and typeid operators
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
I/ Declare variables of different data types
int integerVariable = 42;
double doubleVariable =3.14159;
char charVariable ='A';
bool boolVariable = true;
I/Use sizeof operator to determine the size of variables
cout << "Size of int: " << sizeof(int) <<" bytes" << endl;
cout << "Size of double: " << sizeof(double) <<" bytes" << endl;
cout << "Size of char:"<< sizeof(char) <<" byte" << endl;
cout << "Size of bool: " << sizeof(bool) <<"byte" << endl;
/ Use typecast operator to convert variables to different data types
double intToDouble =double(integerV ariable);
int doubleTolnt int(doubleVariable);
cout << "intToDouble: " << intToDouble << endl:
cout << "doubleTolnt: " << doubleTolnt << endl:
I/Use typeid operator to get the type information of variables
cout << "Type of integerVariable: " << typeid(integerVariable).name() << endl;
cout << "Type of doubleVariable: " << typeid(doubleVariable).name() << endl;
cout << "Type of charVariable: " <<typeid(charVariable). name() << endl;
cout <<"Type of boolVariable: " << typeid(boolVariable).name() << endl;
return 0;
02)Write code snippets implementing cach of the following concepts in C++
a) Overloading with friend functions
b) Abstract classes
c) Inheritance types
d) Virtual base classes
e) Virtual functions
CODE -
a) Overloading with friend functions
#include <iostream>
using namespace std;
class num
{
int val;
public:
num(int Val): val(Val){3
int get value()
return val;
friend int operator -(num);
lOverloading unary operator
friend int operator +(int, num); //Overloading binary operator
friend int operator t(num, int); //Overloading binary operator
int operator -(num num1)
int temp-numl.val*(-1);
return temp;
int operator +(int x, num numl)
int tempFnuml.val+x;
return temp;
int operator +(num num1, int x)
int temp=num 1.val+x;
return temp;
int main()
int nl,n2;
cout<<"Enter a number nl:":
cin>>nl;
cout<<"Enter a number n2:":;
cin>>n2:
num nml(nl);
cout<<"nl="<<numl.get value()<<endl;
cout<<"-n1="<<-numl<<endl;
cout<<"nl+n2="<<num1+n2<<endl;
cout<<"'
return 0;n2+n]="<<n2+num1<<endl:
b) Abstract classes
//Demonstrating abstract class
#include <iostream>
using namespace std;
I| Abstract class with a pure virtual function
class Shape
public:
I/Pure virtual function makes this class abstract
virtual double area()const = 0;
virtual double perimeter) const = 0;
}:
I/Derived class 1: Circle
class Circle :public Shape
private:
double radius;
public:
Circle(double r) :radius(r) {}
I7 Implemnent the pure virtual functions
double area) const override
return 3.14159 * radius * radius;
double perimeter(0 const override
return 2*3.14159 * radius:
I Derived class 2: Rectangle
class Rectangle : public Shape
private:
double length;
double width:
public:
Rectangle(double 1, double w) : length(l), width(w)!
I/Implement the pure virtual functions
double area() const override
return length * width;
double perimeter() const override
return 2 * (length + width):
int main()
I/ Youcannot ereate an instance of the abstract class 'Shape'
I/Shape shape: //This willresult in a compilation eror
I/However, you can create instances of derived classes
Circle circle(3.0):
Rectangle rectangle(4.0, 6.0):
I/Use the abstract class pointer to access derived class objects
Shape* shapel = &circle:
Shape* shape? = &rectangle:
I/ Calculate anddisplav the area and perimeter of shapes
shapel->perimeter) <<end]:
cout << "Circle Area: " << shapel->area() <K", Perimeter:" << <<shape2->perimeter() <<
cout << "Rectangle Area: " << shape2->area()<<", Perimeter: "
endl:
return 0:
c) Inheritance types
Demonstrating the different types of inheritance
lisingle, multiple, multilevel, hierarchical, hybrid inheritance
#include <iostream>
using namespace std;
|/ Base class
class Animal
public:
void eat()
cout << "Animal is eating." << endl:
IDerived class 1 (Single Inheritance)
class Dog:public Animal
public:
void bark)
cout << "Dog is barking." << endl;
I/ Derived class 2 (Multiple Inheritance)
class Bird
public:
void fly()
cout << "Bird is flying." << endl;
}:
class Parrot : public Animal, public Bird
public:
void talk)
Cout << "Parrot is talking." << endl;
Derived class 3 (Multilevel Inheritance)
Class Cat:public Animal
public:
void meow)
cout << "Cat is meowing." << endl;
class PersianCat : public Cat
public:
void purr()
cout << "Persian Cat is purring." << endl;
/ Derived class 4 (Hierarchical Inheritance)
class Lion: public Animal
public:
void roar)
cout << "Lion is roaring." << endl:
};
class Tiger : public Animal
public:
void growl)
cout << "Tiger is growling." << endl:
};
/Derived class 5 (Hybrid Inheritance)
class Liger : public Lion, public Tiger
public:
void specialAbility()
{
cout << "Liger has a special ability." << endl;
int main0
{
/ Single Inheritance Example
Dog dog:
dog.eat();
dog.bark);
cout<<"nn":
IIMultiple Inheritance Example
Parrot parrot;
parrot.eat):
parrot.fly):
parrot.talk0;
cout<<"nn":
/Multilevel Inheritance Example
PersianCat persianCat;
persianCat.eat():
persianCat.meow);
persianCat.purr();
cout<<"nn";
I/Hierarchical Inheritance Example
Lion lion;
lion.eat();
lion.roar():
cout<<"\n":
Tiger tiger;
tiger.eat();
tiger.growl0;
cout<<"nn":
/Hybrid Inheritance Example
Liger liger;
liger.eat():
liger.roar);
liger.growl):
liger.specialAbility();
return 0;
d) Virtual base classes
//Demonstrating virtual base classes
#include <iostream>
using namespace std;
I/Base class
class Animal
string name;
public:
void eat()
cout << "Animal is eating." << endl;
class Lion:virtual publicAnimal /Animal made virtual base class in hierarchy
public:
void roar)
cout << "Lion is roaring." << endl;
class Tiger: virtualpublic Animal /lAnimal made virtual base class in hierarchy
public:
void growl)
cout <<"Tiger is growling." << endl;
class Liger : public Lion, public Tiger
public:
void specialAbility)
cout << "Liger has a special ability." << endl:
int main0
Liger liger;
liger.eat();
liger.roar();
liger.growl);
liger.specialAbility();
return 0;
e) Virtualfunctions
I/Demonstrating virtual functions
#include <iostream>
using namespace std;
I/ Base class
class Shape
public:
I|Virtual function for calculating area
virtual double calculateArea)
return 0.0;
}
I/Derived class 1: Circle
class Circle : public Shape
{
private:
double radius;
public:
Circle(double r) : radius(r) {}
|/ Override the base class virtual function
double calculateArea) override
return 3.14159 * radius * radius:
/Derived class 2: Rectangle
class Rectangle : public Shape
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h)
function
//Override the base class virtual
double calculateArea) override
return width * height;
};
int main()
/Create objects of derived classes
Circle circle(5.0);
Rectangle rectangle(4.0, 6.0):
I/Use the base class pointer tocall the virtual function
Shape* shapel- &circle;
Shape* shape2 &rectangle;
/ Calculate and display areas
cout << "Area of Circle: " << shape1->calculate Area() << endl;
cout <<"Area of Rectangle: " << shape2->calculateArea() << endl;
return 0;
Download