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

Unit - 1: 1) What Is Object Oriented Programming? What Are The Benefits and Applications of Oop?

OOP concepts like classes, objects, inheritance and polymorphism are explained. Key benefits are abstraction, encapsulation and reusability. Common OOP concepts like class vs object relationship, inheritance and composition are illustrated with examples. Common operators in C++ like arithmetic, logical, relational, increment/decrement are also explained with examples.

Uploaded by

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

Unit - 1: 1) What Is Object Oriented Programming? What Are The Benefits and Applications of Oop?

OOP concepts like classes, objects, inheritance and polymorphism are explained. Key benefits are abstraction, encapsulation and reusability. Common OOP concepts like class vs object relationship, inheritance and composition are illustrated with examples. Common operators in C++ like arithmetic, logical, relational, increment/decrement are also explained with examples.

Uploaded by

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

OOP

Unit – 1 :

1) What is Object Oriented Programming? What are the benefits and applications of
OOP?

=>

2)Explain structure of a C++ program.


=>
3) Illustrate the relationship between class and object
=>
In object-oriented programming (OOP), classes and objects are fundamental concepts
that form the basis of the paradigm. Here's an illustration of the relationship between
them:

1. Class:
- A class is a blueprint or template for creating objects. It defines the attributes (data)
and methods (functions) that objects of the class will have.
- Think of a class as a blueprint for a house. It specifies what the house will look like,
how many rooms it has, what materials it's made of, etc., but it's not the actual house
itself.

2. Object:
- An object is an instance of a class. It is a concrete realization of the blueprint defined
by the class.
- Going back to the analogy, if a class is the blueprint for a house, then an object is an
actual, physical house built based on that blueprint. Each house (object) constructed
from the same blueprint (class) may have different attributes (such as color, size,
location) but will share the same fundamental structure defined by the blueprint.

Relationship:
- Classes and objects have a hierarchical relationship where a class serves as a
template for creating objects, and objects are instances of classes.
- Multiple objects can be created from a single class, each with its own unique set of
attributes and behaviors, but all sharing the same structure and functionality defined by
the class.
- Changes made to a class can affect all objects created from it, but changes made to
individual objects do not affect other objects or the class itself.

/* In short>>>

In object-oriented programming:

- **Class**: Blueprint or template defining attributes and methods.

- **Object**: Instance of a class, embodying its attributes and behaviors.

- **Relationship**: Classes create objects; objects belong to classes.

In essence, classes define the structure, while objects represent the actual instances
with specific characteristics and functionalities.

4) Write a short note on Abstraction and Encapsulation


=>

Abstraction:
Abstraction simplifies complex systems by focusing on essential properties and
behaviors , ignoring unnecessary details.

Ex..,
Encapsulation:
5) Explain in brief about reusability in OOP with suitable example.
=>

Reusability in object-oriented programming (OOP) allows developers to use existing


code components in new contexts without modification, promoting efficiency and
reducing redundancy.

Common way to achieve reusability in OOP is through inheritance and composition:

1. Inheritance: Subclasses can inherit properties and behaviors from a superclass,


avoiding the need to redefine common features.
2. Composition: Objects can be composed of other objects as components,
enabling flexible and modular design without relying on inheritance.

Ex..,
#include <iostream>

using namespace std;

// Inheritance Example

class Animal {

public:

virtual void speak() {

cout << "Animal speaks" << endl;

};

class Dog : public Animal {

public:

void speak() override {

cout << "Woof!" << endl;

};

// Composition Example

class Engine {

public:

void start() {

cout << "Engine started" << endl;

};

class Car {

private:
Engine engine;

public:

void startEngine() {

engine.start();

};

int main() {

// Inheritance example

Animal* animal = new Dog();

animal->speak(); // Output: Woof!

// Composition example

Car car;

car.startEngine();

return 0;

Output:

Woof!

Engine started

6) What is Polymorphism? Give suitable example for the same.


=>

Polymorphism allows objects of different classes to be treated as instances of a


common superclass, with different behaviors based on the specific class being
referenced.
Ex..,

#include <iostream>

using namespace std;

class Shape {

public:

virtual void draw() {

cout << "Drawing a shape" << endl;

};

class Circle : public Shape {

public:

void draw() override {

cout << "Drawing a circle" << endl;

};

int main() {

Shape* shapePtr = new Circle();

shapePtr->draw();

return 0;

Output:

Drawing a circle
7) Explain the Arithmetic and Bitwise operators C++ with suitable example
=>

Arithmetic Operators: Arithmetic operators are used to perform mathematical


operations on numerical operands. Common arithmetic operators include addition,
subtraction, multiplication, division, and modulus.

Ex..,

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 5;

cout << "Addition: " << a + b << endl;


cout << "Subtraction: " << a - b << endl;
cout << "Multiplication: " << a * b << endl;
cout << "Division: " << a / b << endl;
cout << "Modulus: " << a % b << endl;

return 0;
}
Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0

Bitwise Operators: Bitwise operators perform operations at the bit level. They are
used to manipulate individual bits of integer operands.

Bitwise Operators: Bitwise operators perform operations at the bit level. They are
used to manipulate individual bits of integer operands.

Ex..,
#include <iostream>

using namespace std;

int main() {

int a = 5;

int b = 3;

cout << "Bitwise AND: " << (a & b) << endl;

cout << "Bitwise OR: " << (a | b) << endl;

cout << "Bitwise XOR: " << (a ^ b) << endl;

cout << "Bitwise NOT: " << (~a) << endl;

cout << "Left Shift: " << (a << 1) << endl;

cout << "Right Shift: " << (a >> 1) << endl;

return 0;

Output:

Bitwise AND: 1

Bitwise OR: 7

Bitwise XOR: 6

Bitwise NOT: -6

Left Shift: 10

Right Shift: 2

8) Explain the Relational and Logical Operators C++ with suitable example
=>
Relational operators: Relational operators are used to establish relationships
between operands and determine the equality, inequality, or ordering of values.

Common relational operators include:


== (equality)
!= (inequality)
< (less than)
> (greater than)
<= (less than or equal to)
>= (greater than or equal to)

Ex..,

#include <iostream>

using namespace std;

int main() {

int a = 5, b = 10;

cout << (a == b) << endl;

cout << (a != b) << endl;

cout << (a < b) << endl;

cout << (a > b) << endl;

cout << (a <= b) << endl;

cout << (a >= b) << endl;

return 0;

Output:
0

1
0

Logical Operators: Logical operators are used to perform logical operations on


boolean values or expressions.

Common logical operators include:


&& (logical AND)
|| (logical OR)
! (logical NOT)

Ex..,

#include <iostream>

using namespace std;

int main() {

bool x = true, y = false;

cout << (x && y) << endl;

cout << (x || y) << endl;

cout << (!x) << endl;

return 0;

Output:

0
9) Explain the Increment/Decrement and Assignment Operator and Operators C++ with
suitable example
=>

1. Increment/Decrement Operators:

Increment (`++`) and decrement (`--`) operators are used to increase or decrease the
value of a variable by one, respectively. They can be used in prefix form (`++i`, `--i`) or
postfix form (`i++`, `i--`).

Example:

#include <iostream>

using namespace std;

int main() {

int i = 5;

// Increment operator

cout << "Before increment: " << i << endl; // Output: 5

cout << "After increment: " << ++i << endl; // Output: 6

// Decrement operator

cout << "Before decrement: " << i << endl; // Output: 6

cout << "After decrement: " << --i << endl; // Output: 5

return 0;

Output:

Before increment: 5

After increment: 6
Before decrement: 6

After decrement: 5

2. Assignment Operator:

Assignment operator (`=`) is used to assign a value to a variable. It assigns the value on
the right-hand side of the operator to the variable on the left-hand side.

Example:

#include <iostream>

using namespace std;

int main() {

int a = 5;

int b;

// Assignment operator

b = a;

cout << "Value of b: " << b << endl; // Output: 5

return 0;

Output:

Value of b: 5

10) Differentiate between OOP and POP


=>
11) Explain the scope resolution operator C++ with suitable example
=>
12)
a) Write a C++ program to find the area of a rectangle.
=>

#include <iostream>
using namespace std;

int main() {
double length, width;
cout << "Enter length of the rectangle: ";
cin >> length;
cout << "Enter width of the rectangle: ";
cin >> width;
double area = length * width;
cout << "Area of the rectangle: " << area << endl;
return 0;
}

b) Write a C++ program to find the factorial of a number using recursive function.
=>

#include <iostream>
using namespace std;

int factorial(int n) {

if (n == 0 || n == 1) {

return 1;

} else {

return n * factorial(n - 1);

}
}

int main() {
int num;

cout << "Enter a positive integer: ";

cin >> num;

if (num < 0) {

cout << "Factorial is not defined for negative numbers.";

} else {

int result = factorial(num);

cout << "Factorial of " << num << " = " << result;
}
return 0;

c) Write a C++ program to find volume of cube.


=>

#include <iostream>

using namespace std;

int main() {

double side, volume;

cout << "Enter the side length of the cube: ";

cin >> side;

volume = side * side * side;

cout << "Volume of the cube: " << volume << endl;

return 0;

13)

a) Write a C++ program to find sum of first n number of even and sum of first n
number of odd numbers

=>

#include <iostream>

using namespace std;

int main() {

int n;

cout << "Enter the value of n: ";


cin >> n;
int sumEven = 0, sumOdd = 0;

for (int i = 1; i <= 2 * n; i++) {

if (i % 2 == 0) {

sumEven += i;
} else {

sumOdd += i;

cout << "Sum of first " << n << " even numbers: " << sumEven << endl;

cout << "Sum of first " << n << " odd numbers: " << sumOdd << endl;

return 0;

14)

a) Write a C++ program to check a number is even or odd.


=>

#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

if (num % 2 == 0) {
cout << num << " is even." << endl;
} else {
cout << num << " is odd." << endl;
}

return 0;
}
b) Write a C++ to generate all the prime numbers between 1 and n, where the value of
n to be taken from the user
=>
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

cout << "Prime numbers between 1 and " << n << " are: ";

for (int i = 2; i <= n; i++) {


bool isPrime = true;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
cout << i << " ";
}
}

return 0;
}

15)
a) Write a C++ program to find the greatest of three numbers
=>

#include <iostream>
using namespace std;

int findMax(int a, int b, int c) {


int maxNum = a;
if (b > maxNum) {
maxNum = b;
}
if (c > maxNum) {
maxNum = c;
}
return maxNum;
}

int main() {
int num1, num2, num3;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;

int greatest = findMax(num1, num2, num3);

cout << "The greatest number is: " << greatest << endl;

return 0;
}

b) Write a C++ program to find a number is prime or not


=>
#include <iostream>

using namespace std;

bool isPrime(int n) {

if (n <= 1) {

return false;

for (int i = 2; i * i <= n; i++) {

if (n % i == 0) {

return false;

return true;

int main() {

int num;

cout << "Enter a number: ";


cin >> num;

if (isPrime(num)) {

cout << num << " is a prime number." << endl;

} else {

cout << num << " is not a prime number." << endl;

return 0;

16)

a) Write a C++ program to create a simple calculator.


=>

#include <iostream>
using namespace std;

int main() {
char op;
double num1, num2;

cout << "Enter operator (+, -, *, /): ";


cin >> op;

cout << "Enter two numbers: ";


cin >> num1 >> num2;

switch (op) {
case '+':
cout << "Result: " << num1 + num2;
break;
case '-':
cout << "Result: " << num1 - num2;
break;
case '*':
cout << "Result: " << num1 * num2;
break;
case '/':
if (num2 != 0) {
cout << "Result: " << num1 / num2;
} else {
cout << "Error! Division by zero.";
}
break;
default:
cout << "Error! Invalid operator.";
break;
}

return 0;
}

b) Write a C++ program to find the reverse of a number. Hence find it is palindrome
or not?
=>

#include <iostream>

using namespace std;

int reverseNumber(int num) {

int reversedNum = 0;

while (num > 0) {

int digit = num % 10;

reversedNum = reversedNum * 10 + digit;

num /= 10;

return reversedNum;

bool isPalindrome(int num) {

return num == reverseNumber(num);


}

int main() {

int num;

cout << "Enter a number: ";

cin >> num;

int reversedNum = reverseNumber(num);

cout << "Reverse of " << num << " is: " << reversedNum << endl;

if (isPalindrome(num)) {

cout << num << " is a palindrome." << endl;

} else {

cout << num << " is not a palindrome." << endl;

return 0;

17)

a) Write a C++ program to find the area and volume of a cone.


=>

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

double coneArea(double radius, double height) {


return M_PI * radius * (radius + sqrt(height * height + radius * radius));
}

double coneVolume(double radius, double height) {


return (1.0 / 3.0) * M_PI * radius * radius * height;
}

int main() {
double radius, height;
cout << "Enter radius of the cone: ";
cin >> radius;
cout << "Enter height of the cone: ";
cin >> height;

double area = coneArea(radius, height);


double volume = coneVolume(radius, height);

cout << "Area of the cone: " << area << endl;
cout << "Volume of the cone: " << volume << endl;

return 0;
}

b) Write a C++ program to add two numbers using a method that takes two numbers
as parameters and returns the result.
=>
#include <iostream>
using namespace std;

double add(double a, double b) {


return a + b;
}

int main() {
double num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

double sum = add(num1, num2);


cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << endl;

return 0;
}

18)

a) Write a C++ program to convert seconds into hours, minutes and seconds.
=>
#include <iostream>
using namespace std;

void convertTime(int seconds, int &hours, int &minutes, int &remainingSeconds) {


hours = seconds / 3600;
seconds %= 3600;
minutes = seconds / 60;
remainingSeconds = seconds % 60;
}

int main() {
int seconds, hours, minutes, remainingSeconds;
cout << "Enter the number of seconds: ";
cin >> seconds;

convertTime(seconds, hours, minutes, remainingSeconds);

cout << "Hours: " << hours << ", Minutes: " << minutes << ", Seconds: " <<
remainingSeconds << endl;

return 0;
}

b) Write a C++ program to swap two numbers using call by reference.


=>

#include <iostream>
using namespace std;

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
}

int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << endl;

swap(num1, num2);

cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << endl;

return 0;
}

19) Write a C++ program to create one dimensional array. Get the array size from the
user. Initialize the array with dynamic elements. Find the maximum and minimum of
those array elements by using a method.
=>
#include <iostream>
using namespace std;

int findMax(int arr[], int size) {


int maxElement = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
return maxElement;
}

int findMin(int arr[], int size) {


int minElement = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < minElement) {
minElement = arr[i];
}
}
return minElement;
}

int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;

int* arr = new int[size];

cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
int maxElement = findMax(arr, size);
int minElement = findMin(arr, size);

cout << "Maximum element: " << maxElement << endl;


cout << "Minimum element: " << minElement << endl;

delete[] arr;

return 0;
}

Unit – 2 :

1) What is a class? How a class can be defined in C++?


=>
Ex..,

class Rectangle {
// Data members
int length;
int width;

public:
// Member functions
void setLength(int l) {
length = l;
}

void setWidth(int w) {
width = w;
}

int calculateArea() {
return length * width;
}
};

2) What are the different ways of defining member functions in C++


=>

1. Inside the class definition: Member functions are defined directly within the class
declaration. This approach is suitable for small, simple functions.

class MyClass {
public:
void memberFunction() {
// Function definition
}
};

2.Outside the class definition using the scope resolution operator (::): Member
functions are declared inside the class but defined outside using the scope resolution
operator. This approach is suitable for larger functions or when separating interface
from implementation.

Eg..,

class MyClass {
public:
void memberFunction(); // Declaration
};

void MyClass::memberFunction() {
// Function definition
}

3. Inline member functions: Member functions are defined inline within the class
declaration itself. This approach is suitable for small, frequently used functions.

Eg..,

class MyClass {
public:
void memberFunction() {
// Function definition
}
};

4. Defining a member function as a friend function : Member functions can be


defined as friend functions outside the class, allowing them to access private and
protected members of the class. This approach is useful for granting special access to
external functions.

Eg..,

class MyClass {
private:
int data;
public:
friend void friendFunction(MyClass obj);
};

void friendFunction(MyClass obj) {


// Access obj.data directly
}

3) Define object. How they can be declared? Also explain memory allocation of objects
in C++ Programming
=>

An object is an instance of a class. It is a concrete entity that represents a specific


instance of the class, with its own unique set of data members and member functions.
1.Define a class: First, you need to define a class. A class serves as a blueprint or
template for creating objects. It specifies the data members and member functions that
each object will have.

2. Declare an object: Once the class is defined, you can declare objects of that class
by specifying the class name followed by the object name.

Eg..,

class MyClass {
// Class definition
};

int main() {
// Declare an object of MyClass
MyClass obj1;
// Declare another object of MyClass
MyClass obj2;
// ...
return 0;
}

Memory allocation of objects in C++ Programming

• Static memory allocation: If an object is declared globally (outside any function) or


as a static variable inside a function, memory for that object is allocated at compile
time and persists throughout the program's execution. The memory size is
determined based on the class's data members.

Eg..,

class MyClass {
// Class definition
};

// Global object (static memory allocation)


MyClass globalObj;

int main() {
// Static variable (static memory allocation)
static MyClass staticObj;
// ...
return 0;
}

• Dynamic memory allocation: If an object is declared using dynamic memory


allocation (using the `new` keyword), memory for that object is allocated on the
heap at runtime. The object's lifetime is managed manually, and it is the
programmer's responsibility to deallocate the memory when it is no longer needed
using the `delete` keyword.

Eg..,

class MyClass {
// Class definition
};

int main() {
// Dynamic memory allocation
MyClass* dynamicObj = new MyClass();

// Delete dynamically allocated object to prevent memory leaks


delete dynamicObj;
// ...
return 0;
}

4 ) What is constructor? State the rules for constructor.


=>
• A constructor in C++ is a special member function of a class that is
automatically called when an object of that class is created. It is used to
initialize the object's data members.
• Rules for constructors:
• The constructor name must be the same as the class name.
• Constructors have no return type, not even void.
• Constructors can be overloaded, meaning a class can have multiple
constructors with different parameters.
• Constructors can have default arguments.
• Constructors can be explicitly declared as public, protected, or private.
• Constructors are called automatically when objects are created and
cannot be called explicitly.

5 ) Explain parameterized constructor with suitable example.


=>
• A parameterized constructor is a constructor with parameters used to initialize
the object's data members with values passed during object creation.
• Example:
class MyClass {
private:
int x, y;
public:
// Parameterized constructor
MyClass(int a, int b) {
x = a;
y = b;
}
void display() {
cout << "x = " << x << ", y = " << y << endl;
}
};

int main() {
MyClass obj(5, 10); // Creating object with parameterized constructor
obj.display(); // Output: x = 5, y = 10
return 0;
}

6 ) Explain the concept of Destructor with suitable example.


=>
• A destructor in C++ is a special member function of a class that is
automatically called when an object goes out of scope or is explicitly deleted.
It is used to release resources held by the object, such as dynamically
allocated memory.
• Example:
class MyClass {
private:
int *ptr;
public:
// Constructor
MyClass() {
ptr = new int; // Dynamically allocate memory
}
// Destructor
~MyClass() {
delete ptr; // Free dynamically allocated memory
}
};

int main() {
MyClass obj; // Creating object
// Object goes out of scope, destructor is called automatically
return 0;
}

7 ) Write a short note on static members in C++ class


=>
• Static members in C++ classes are shared among all objects of the class. They
are declared using the static keyword.
• Static data members are shared across all objects of the class and are
initialized only once, regardless of the number of objects created.
• Static member functions can access only static data members and other static
member functions.
• They can be accessed using the class name followed by the scope resolution
operator ::.
• Example:
class MyClass {
private:
int x;
static int count; // Static data member
public:
MyClass() {
count++; // Increment count whenever an object is created
}
static void displayCount() { // Static member function
cout << "Total objects created: " << count << endl;
}
};
int MyClass::count = 0; // Initializing static data member

int main() {
MyClass obj1, obj2, obj3;
MyClass::displayCount(); // Output: Total objects created: 3
return 0;
}

8 ) Explain with an example how objects are passed as parameter to a member


function in C+
=>
• Objects can be passed as parameters to member functions just like any other
data type.
• They can be passed by value, by reference, or by pointer.
• Example:
class Rectangle {
private:
int length, width;
public:
Rectangle(int l, int w) {
length = l;
width = w;
}
void display() {
cout << "Length: " << length << ", Width: " << width << endl;
}
void compare(Rectangle &obj) { // Passing object by reference
if (length == obj.length && width == obj.width)
cout << "Rectangles are equal." << endl;
else
cout << "Rectangles are not equal." << endl;
}
};

int main() {
Rectangle obj1(5, 10);
Rectangle obj2(5, 10);
obj1.compare(obj2); // Passing object as parameter
return 0;
}

9 ) What is a friend function? How it can be declared? What are its characteristics?

=>
10 ) Explain the concept of method overloading with suitable example.
=>

Method overloading in C++ allows multiple functions with the same name but
different parameter lists to be defined within the same scope. The compiler selects
the appropriate function to call based on the number and types of arguments passed
to it.

Example:

#include <iostream>

using namespace std;

class Math {
public:

// Method to add two integers

int add(int a, int b) {

return a + b;

// Overloaded method to add three integers

int add(int a, int b, int c) {

return a + b + c;

// Overloaded method to add two doubles

double add(double a, double b) {

return a + b;

};

int main() {

Math math;

cout << "Sum of 5 and 10: " << math.add(5, 10) << endl; // Output: 15

cout << "Sum of 5, 10, and 15: " << math.add(5, 10, 15) << endl; // Output: 30

cout << "Sum of 2.5 and 3.5: " << math.add(2.5, 3.5) << endl; // Output: 6.0

return 0;
}

11 ) Define operator overloading. List the operators that cannot be overloaded.


Explain the rules for overloading the operators.
=>

Operators that cannot be overloaded include:

• . (dot)
• .* (member pointer)
• :: (scope resolution)
• ?: (ternary conditional)
• sizeof (size of)
• typeid (type information)

Eg..,

12 ) Write a C++ program to overload unary ++ operator.


=>
13 ) Write a C++ program to overload unary -- operator.
=>
14) Write a C++ program to design an Employee class for reading and displaying the
employee information (employee ID and employee name), with the getInfo() and
displayInfo() methods respectively. Where getInfo() will be a private method.
=>

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

class Employee {
private:
int employeeID;
string employeeName;

void getInfo() {
cout << "Enter Employee ID: ";
cin >> employeeID;
cout << "Enter Employee Name: ";
cin.ignore();
getline(cin, employeeName);
}

public:
void displayInfo() {
cout << "Employee ID: " << employeeID << endl;
cout << "Employee Name: " << employeeName << endl;
}

void setData() {
getInfo();
}
};

int main() {
Employee emp;
emp.setData();
cout << "\nEmployee Information:" << endl;
emp.displayInfo();
return 0;
}

Output:
Enter Employee ID: 101
Enter Employee Name: John Doe
Employee Information:
Employee ID: 101
Employee Name: John Doe

15 ) Write a C++ program to design the class Student containing data members
Rollno, name and age. Include a method named display() for display the student
information. Include default constructor and parameterized constructor with
default argument to initialize the data members.
Display three students’ details, using array of objects
=>

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

class Student {
private:
int rollNo;
string name;
int age;

public:
// Default constructor
Student() : rollNo(0), name(""), age(0) {}

// Parameterized constructor with default arguments


Student(int r, string n = "", int a = 0) : rollNo(r), name(n), age(a) {}

// Method to display student information


void display() {
cout << "Roll No: " << rollNo << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

int main() {
Student students[3] = {
Student(101, "Alice", 20), // Parameterized constructor with explicit values
Student(102, "Bob"), // Parameterized constructor with default age
Student() // Default constructor
};
cout << "Student Details:" << endl;
for (int i = 0; i < 3; ++i) {
cout << "\nStudent " << (i + 1) << ":\n";
students[i].display();
}

return 0;
}

Output:
Student Details:

Student 1:
Roll No: 101
Name: Alice
Age: 20

Student 2:
Roll No: 102
Name: Bob
Age: 0

Student 3:
Roll No: 0
Name:
Age: 0

16 ) Write a C++ Program to demonstrate function definition outside class and


accessing class members in function definition.
▪Create a class named Rectangle with two data members’ length and breadth.
▪Include a constructor to initialize the data members and a method to find the
area of rectangle.
Define both the constructor and member function outside the class.
=>

#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int breadth;
public:
// Constructor definition outside the class
Rectangle(int l, int b);

// Member function definition outside the class


int area();
};

// Constructor definition
Rectangle::Rectangle(int l, int b) {
length = l;
breadth = b;
}

// Member function definition


int Rectangle::area() {
return length * breadth;
}

int main() {
Rectangle rect(5, 4); // Creating object with constructor
cout << "Area of Rectangle: " << rect.area() << endl; // Accessing member function
return 0;
}

Output:
Area of Rectangle: 20

17)
a)Write a C++ program to design a class Complex for adding two complex numbers;
also show the use of constructor.
=>

#include <iostream>
using namespace std;

class Complex {
private:
float real;
float imag;

public:
Complex(float r = 0.0, float i = 0.0) : real(r), imag(i) {}
Complex add(const Complex& c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}

void display() {
cout << "Complex Number: " << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex num1(2.5, 3.5);
Complex num2(1.5, 2.5);

cout << "First ";


num1.display();
cout << "Second ";
num2.display();

Complex sum = num1.add(num2);

cout << "Sum of complex numbers: ";


sum.display();

return 0;
}

Output:
First Complex Number: 2.5 + 3.5i
Second Complex Number: 1.5 + 2.5i
Sum of complex numbers: Complex Number: 4 + 6i

b)Write a C++ program to access members of a STUDENT class using pointer to


object
=>
#include <iostream>
using namespace std;

class Student {
private:
int rollNo;
string name;
int age;

public:
Student(int r, string n, int a) : rollNo(r), name(n), age(a) {}

void display() {
cout << "Roll No: " << rollNo << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

int main() {
Student *ptr = new Student(101, "Alice", 20);

cout << "Student Details:" << endl;


ptr->display();

delete ptr;

return 0;
}

Output:
Student Details:
Roll No: 101
Name: Alice
Age: 20

18)
a)Write a C++ program to design a class Geometry containing the methods:
▪area() for finding the area of a square
▪volume() for finding the volume of a cuboid
Also overload the area() function for finding the area of a rectangle
=>
#include <iostream>
using namespace std;

class Geometry {
public:
float area(float side) {
return side * side;
}

float area(float length, float breadth) {


return length * breadth;
}

float volume(float length, float breadth, float height) {


return length * breadth * height;
}
};

int main() {
Geometry geo;

float side = 5.0;


float length = 6.0;
float breadth = 4.0;
float height = 3.0;

cout << "Area of square with side " << side << ": " << geo.area(side) << endl;
cout << "Area of rectangle with length " << length << " and breadth " << breadth << ": "
<< geo.area(length, breadth) << endl;
cout << "Volume of cuboid with length " << length << ", breadth " << breadth << " and
height " << height << ": " << geo.volume(length, breadth, height) << endl;

return 0;
}
Output:
Area of square with side 5: 25
Area of rectangle with length 6 and breadth 4: 24
Volume of cuboid with length 6, breadth 4 and height 3: 72

b)Write C++ program to design a class Rectangle to show the implementation of


static variable and static function; that can be used to count the number of
rectangle object created.
=>

#include <iostream>
using namespace std;

class Rectangle {
private:
double length;
double breadth;
static int count; // Static variable to count the number of Rectangle objects

public:
Rectangle(double l, double b) : length(l), breadth(b) {
count++; // Increment count when an object is created
}

// Static function to get the count of Rectangle objects


static int getCount() {
return count;
}
};

// Initializing static variable count


int Rectangle::count = 0;

int main() {
// Creating Rectangle objects
Rectangle rect1(3, 4);
Rectangle rect2(5, 6);

// Displaying the number of Rectangle objects created


cout << "Number of Rectangle objects created: " << Rectangle::getCount() << endl;

return 0;
}

Output:
Number of Rectangle objects created: 2

19)
a) Write a Program to find Maximum out of Two Numbers using friend function.
Note: Here one number is a member of one class and the other number is member
of another class.
=>
#include <iostream>
using namespace std;

class Number2; // Forward declaration

class Number1 {
private:
int num;

public:
Number1(int n) : num(n) {}

friend int max(Number1 n1, Number2 n2);


};

class Number2 {
private:
int num;

public:
Number2(int n) : num(n) {}

friend int max(Number1 n1, Number2 n2);


};

int max(Number1 n1, Number2 n2) {


return (n1.num > n2.num) ? n1.num : n2.num;
}

int main() {
Number1 num1(5);
Number2 num2(10);

cout << "Maximum of " << num1.num << " and " << num2.num << " is: " << max(num1,
num2) << endl;

return 0;
}
Output:
Maximum of 5 and 10 is: 10

20) Write a C++ program to overload unary minus (-) operator to negate a point in
three-dimensional space using a member function.
=>
#include <iostream>
using namespace std;

class Point3D {
private:
double x, y, z;

public:
Point3D(double x_val = 0.0, double y_val = 0.0, double z_val = 0.0)
: x(x_val), y(y_val), z(z_val) {}

// Overloading unary minus operator as a member function


Point3D operator-() {
return Point3D(-x, -y, -z);
}

// Method to display the coordinates of the point


void display() {
cout << "(" << x << ", " << y << ", " << z << ")" << endl;
}
};

int main() {
Point3D point(2.5, -3.7, 4.2);

cout << "Original Point: ";


point.display();

// Using unary minus operator to negate the point


Point3D negated_point = -point;

cout << "Negated Point: ";


negated_point.display();

return 0;
}
Output:
Original Point: (2.5, -3.7, 4.2)
Negated Point: (-2.5, 3.7, -4.2)

21) Write a C++ program to overload the + operator for concatenating two strings
using member function. For e.g “I Love ” + “India” = I Love India.
=>
#include <iostream>
#include <string>
using namespace std;

class Concatenator {
private:
string str;

public:
Concatenator(string s) : str(s) {}

// Overloading + operator as a member function


Concatenator operator+(Concatenator& other) {
return Concatenator(str + other.str);
}

// Method to display the concatenated string


void display() {
cout << str << endl;
}
};

int main() {
Concatenator str1("I Love ");
Concatenator str2("India");

Concatenator result = str1 + str2;

cout << "Concatenated String: ";


result.display();

return 0;
}
Output:
Concatenated String: I Love India.

You might also like