V2V - OOP - Super - 25 - Solutions - by - Akshay - Sir - (24-25)
V2V - OOP - Super - 25 - Solutions - by - Akshay - Sir - (24-25)
1. POP vs OOP
Ans.
2 Programs are divided into multiple Large programs are divided into multiple
objects functions
3 Data is hidden and cannot be accessed Data move openly around the system from
by external functions. function to function
4 Objects communicate with each other Functions transform data from one form to
through function another by calling each other.
Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at
runtime.
Features of OOP: -
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are ties together in the data structure.
5. Data is hidden and cannot be accessed by external function.
6. Objects may communicate with each other through function.
7. New data and functions can be easily added whenever necessary.
8. Follows bottom up approach in program design. Object-oriented programming is the
most recent concept among programming paradigms and still means different things to
different people.
CLASS DECLARATION
- Explicit type casting is performed manually by the programmer using casting operators.
- It is used when there may be a risk of data loss or when you want to enforce a specific type
conversion.
- C++ provides casting operators like `static_cast`, `dynamic_cast`, `const_cast`, and
`reinterpret_cast`.
- For example, using `static_cast` allows you to explicitly convert a `float` to an `int`, but
you must be aware that it may truncate the fractional part of the number.
Example:-
#include <iostream>
using namespace std;
int main() {
// Implicit type casting (int to float)
int num = 10;
float floatValue = num; // Implicitly converts int to float
cout << "Implicit type casting (int to float): " << floatValue << endl;
cout << "Explicit type casting (float to int): " << intNum << endl;
return 0;
}
Type casting is a way to ensure that data of one data type can be used in operations or
assignments involving another data type. Implicit type casting happens automatically when it's
safe, while explicit type casting is done manually when you need control or when data loss
may occur. It's important to use type casting carefully to avoid unexpected results and data loss
in your programs.
Object: It is a basic run time entity that represents a person, place or any item that the program
has to handle.
9. Member Function with Program Example (Internal, External, Inline & Friend Function)
Ans. Static Member Function in C++
Static Member Function in a class is the function that is declared as static because of which
function attains certain properties as defined below:
A static member function is independent of any object of the class.
A static member function can be called even if no objects of the class exist.
A static member function can also be accessed using the class name through the scope
resolution operator.
A static member function can access static data members and static member functions inside
or outside of the class.
// C++ Program to show the working of
// static member functions
#include <iostream>
using namespace std;
class Box
{
private:
static int length;
static int breadth;
static int height;
public:
// Driver Code
int main()
{
Box b;
cout << "Static member function is called through Object name: \n" << endl;
b.print();
cout << "\nStatic member function is called through Class name: \n" << endl;
Box::print();
return 0;
}
Example:
Program to interchange values of two integer numbers using friend function.
#include <iostream.h>
#include <conio.h>
class B;
class A
{
int x;
public:
void accept()
{
cout<<"\n Enter the value for x:";
cin>>x;
}
friend void swap(A,B);
};
class B
{
int y;
public:
void accept()
{
cout<<"\n Enter the value for y:";
cin>>y;
}
friend void swap(A,B);
};
void swap(A a,B b)
{
cout<<"\n Before swapping:";
cout<<"\n Value for x="<<a.x;
cout<<"\n Value for y="<<b.y;
int temp;
temp=a.x;
a.x=b.y;
b.y=temp;
cout<<"\n After swapping:";
cout<<"\n Value for x="<<a.x;
cout<<"\n Value for y="<<b.y;
}
void main()
{
A a;
B b;
clrscr();
a.accept();
b.accept();
swap(a,b);
getch();
}
Before swapping:
Value for x=5
Value for y=10
After swapping:
Value for x=10
Value for y=5
b. Write a C++ program to find smallest number from two numbers using friend function.
(Hint: use two classes).
(Note: Any other correct logic shall be considered)
Ans. #include
#include
class class2;
class class1
{
int no1;
public:
void get1()
{
cout<<"Enter number 1:";
cin>>no1;
}
friend void smallest(class1 no1,class2 no2);
};
class class2
{
int no2;
public:
void get2()
{
cout<<"Enter number 2:";
cin>>no2;
}
friend void smallest(class1 no1,class2 no2);
};
void smallest(class1 c1,class2 c2)
{
if(c1.no1<c2.no2)
cout<<"no1 is smallest";
else
cout<<"no2 is smallest";
}
void main()
{
class1 c1;
class2 c2;
clrscr();
c1.get1();
c2.get2();
smallest(c1,c2);
getch();
}
Enter number 1: 5
Enter number 2: 3
no2 is smallest
c. Write a C++ program to find greatest number among two numbers from two different classes
using friend function.
Ans. #include
#include
class second;
class first
{
int x;
public:
void getx()
{
cout<<"\nEnter the value of x:";
cin>>x;
}
friend void max(first,second);
};
class second
{
int y;
public:
void gety()
{
cout<<"\nEnter the value of y:";
cin>>y;
}
friend void max(first,second);
};
void max(first a,second b)
{
if(a.x>b.y)
{
cout<<"\Greater value is:"<<a.x;
}
else
{
cout<<"\nGreater value is:"<<b.y;
}
}
void main()
{
first a;
second b;
clrscr();
a.getx();
b.gety();
max(a,b);
getch();
}
d. Write a C++ program to declare two classes with data members as ml and m2 respectively.
Use friend function to calculate average of two (m1, m2) marks and display it.
(Hint: class 1 contains ml and class 2 contains m2)
Ans. #include <iostream>
using namespace std;
// Class1 declaration
class Class1 {
private:
int m1;
public:
Class1(int m) : m1(m) {}
// Class2 declaration
class Class2 {
private:
int m2;
public:
Class2(int m) : m2(m) {}
int main() {
Class1 obj1(80); // Create an object of Class1 with m1 = 80
Class2 obj2(90); // Create an object of Class2 with m2 = 90
return 0;
}
This program demonstrates the use of friend functions to access and calculate values involving
data members of two different classes.
Ans. 1. Access to Private Members: A friend function can access and modify the private and
protected members of the class it is a friend of. This provides a way to break the encapsulation
of a class temporarily, allowing external functions to work with the class's private data.
2. Declared Outside the Class: Friend functions are declared outside the class in which they
are defined as friends. They are not members of the class, but they are associated with it. This
means that they can be used to provide external functions that have privileged access to the
class without being part of it.
These characteristics make friend functions useful for scenarios where you need external
functions to interact with a class's private members while still maintaining data integrity and
access control. However, it's important to use friend functions judiciously, as they can
potentially violate the encapsulation principle if overused.
Types of Constructor
• Default Constructor
• Parameterize Constructor
• Copy Constructor
Default Constructor:
Construct without parameter is called default constructor.
Parameterize Constructor:
Constructor with parameter is called parameterize constructor. In parameterize constructor, we
have to pass values to the constructor through object.
Copy Constructor:
Initialization of an object through another object is called copy constructor. In other words,
copying the values of one object into another object is called copy constructor.
c. Constructor vs Destructor.
Ans.
Constructor Destructor
It constructs the values of data members of It does not construct the values for the data
the class. members of the class
It is invoked automatically when the objects It is invoked implicitly by the compiler upon
are created exit of a program/block/function.
Constructors are classified in various types Destructors are not classified in any types.
such as : Default constructor Parameterized
constructor Copy constructor Overloaded
constructor
A class can have more than one constructor. A class can have at most one constructor.
Constructor accepts parameter. Also it can Destructor never accepts any parameter.
have default value for its parameter
Syntax: Syntax:
classname() destructor name is preceded with tilde.
{ ~classname()
… {
… ….
} ….
}
class Rectangle {
private:
double length;
double width;
public:
// Constructor with default arguments
double calculateArea() {
return length * width;
}
};
int main() {
// Creating objects of the Rectangle class with default arguments
Rectangle rect1; // Uses default values (length = 1.0, width = 1.0)
Rectangle rect2(5.0); // Sets length to 5.0, width remains default (1.0)
Rectangle rect3(3.0, 4.0); // Sets both length and width
return 0;
}
Area of rect1: 1
Area of rect2: 5
Area of rect3: 12
e. Write a C++ program to declare a class student with members as roll no, name and
department. Declare a parameterized constructor with default value for department as ‘CO’ to
initialize members of object. Initialize and display data for two students. (Note: Any other
relevant logic should be considered).
Ans. #include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int roll_no;
char name[20],department[40];
public:
Roll No:112
Name: Chitrakshi
Department:CO
Roll No:114
Name:Anjali
Department:CO
f. Develop a c++ program for constructor with default argument and use of destructor.
Ans. #include <iostream>
using namespace std;
class MyClass
{
private:
int value;
public:
// Constructor with default argument
MyClass(int x = 0) {
value = x;
cout << "Constructor called with value: " << value << endl;
}
// Destructor
~MyClass() {
cout << "Destructor called for value: " << value << endl;
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
// Create objects with and without arguments
MyClass obj1; // Default constructor (value = 0)
MyClass obj2(42); // Constructor with argument (value = 42)
// Display values
obj1.display();
obj2.display();
6. It is invoked implicitly by the compiler upon exit from the program (or block or function)
i.e when scope of object is over.
Enter the array size: [You will enter the size of the array]
Enter array elements: [You will enter the elements of the array]
Sorted Array:
[The sorted array elements will be displayed here]
int a[5],smallest,i;
clrscr();
cout<<" Enter array elements:";
for(i=0;i<5;i++)
cin>>a[i];
smallest=a[0];
for(i=1;i<5;i++)
{
if(a[i]<smallest)
{
smallest=a[i];
}
}
cout<<endl<<"Smallest number="<<smallest;
getch();
}
int main()
{
const int numCount = 10; // Number of elements in the array
int numbers[numCount]; // Declare an array to store the numbers
int sum = 0; // Initialize a variable to store the sum
sum += numbers[i];
}
Return
0;
}
Types of inheritance:
1) Single inheritance: In single inheritance, a derived class is derived from only one base
class.
Diagram:
2) Multiple inheritance: In multiple inheritance, derived class is derived from more than
one base classes.
Diagram:
Private members of base class are not inherited directly in any visibility mode.
1. Private visibility mode In this mode,
protected and public members of base class become private members of derived class.
2. Protected visibility mode In this mode,
protected and public members of base class become protected members of derived class.
3. Public visibility mode In this mode,
protected members of base class become protected members of derived class and public
members of base class become public members of derived class
class Employee {
protected:
int emp_id;
string name;
public:
void getEmployeeDetails() {
cout << "Enter Employee ID: ";
cin >> emp_id;
cin.ignore();
cout << "Enter Employee Name: ";
getline(cin, name);
}
public:
void getBasicSalary() {
cout << "Enter Basic Salary: ";
cin >> basic_salary;
}
int main() {
EmpInfo emp;
emp.getEmployeeDetails();
emp.getBasicSalary();
cout << "\nEmployee Information:\n";
emp.displayEmpInfo();
return 0;
}
Accept and display data for one car with all details.
Ans. #include <iostream>
#include <string>
using namespace std;
class Carmanufacturer {
protected:
string name;
public:
void setManufacturerName(const string& manufacturerName) {
name = manufacturerName;
}
void displayManufacturer() {
cout << "Manufacturer Name: " << name << endl;
}
};
string modelName;
int modelNumber;
public:
void setModelDetails(const string& name, int number) {
modelName = name;
modelNumber = number;
}
void displayModel() {
displayManufacturer();
cout << "Model Name: " << modelName << endl;
cout << "Model Number: " << modelNumber << endl;
}
};
public:
void setCarDetails(int number, const string& carColor) {
carNumber = number;
color = carColor;
}
void displayCar() {
displayModel();
cout << "Car Number: " << carNumber << endl;
cout << "Car Color: " << color << endl;
}
};
int main() {
Car car;
car.setManufacturerName("Toyota");
car.setModelDetails("Corolla", 2023);
car.setCarDetails(1001, "Red");
car.displayCar();
return 0;
}
class Subject1 {
protected:
int m1;
public:
void setMarks1(int marks) {
m1 = marks;
}
int getMarks1() {
return m1;
}
};
class Subject2 {
protected:
int m2;
public:
void setMarks2(int marks) {
m2 = marks;
}
int getMarks2() {
return m2;
}
};
public:
void calculateTotal() {
total = m1 + m2;
}
void displayResult() {
cout << "Marks in Subject 1: " << m1 << endl;
cout << "Marks in Subject 2: " << m2 << endl;
cout << "Total Marks: " << total << endl;
}
};
int main() {
Result studentResult;
studentResult.setMarks1(85);
studentResult.setMarks2(90);
studentResult.calculateTotal();
studentResult.displayResult();
return 0;
}
Marks in Subject 1: 85
Marks in Subject 2: 90
Total Marks: 175
class HOD {
protected:
string name;
public:
void setHODName(const string& hodName) {
name = hodName;
}
void displayHOD() {
cout << "HOD Name: " << name << endl;
}
};
public:
void setFacultyName(const string& name) {
facultyName = name;
}
void displayFaculty() {
displayHOD();
cout << "Faculty Name: " << facultyName << endl;
}
};
public:
void setStudentName(const string& name) {
studentName = name;
}
void displayStudent() {
displayHOD();
cout << "Student Name: " << studentName << endl;
}
};
public:
void setLabName(const string& name) {
labName = name;
}
void displayLabIncharge() {
displayHOD();
cout << "Lab Name: " << labName << endl;
}
};
public:
void setTechnicalDetails(const string& specialization) {
technicalSpecialization = specialization;
}
void displayTechnical() {
displayLabIncharge();
cout << "Technical Specialization: " << technicalSpecialization << endl;
}
};
public:
void setNonTechnicalDetails(const string& work) {
nonTechnicalWork = work;
}
void displayNonTechnical() {
displayLabIncharge();
cout << "Non-Technical Work: " << nonTechnicalWork << endl;
}
};
int main() {
Technical tech;
tech.setHODName("Dr. Sharma");
tech.setLabName("Physics Lab");
tech.setTechnicalDetails("Hardware Maintenance");
tech.displayTechnical();
NonTechnical nonTech;
nonTech.setHODName("Dr. Sharma");
nonTech.setLabName("Chemistry Lab");
nonTech.setNonTechnicalDetails("Inventory Management");
nonTech.displayNonTechnical();
return 0;
}
HOD Name: Dr. Sharma
Lab Name: Physics Lab
Technical Specialization: Hardware Maintenance
int main() {
int num1, num2;
int *ptr1, *ptr2;
return 0;
}
b. Write a program to declare a class ‘book’ containing data members as ‘title’, ‘author-name’,
‘publication’, ‘price’. Accept and display the information for one object using pointer to that
object. (Note: Any other correct logic shall be considered)
Ans. #include<iostream.h>
#include<conio.h>
class book
{
char author_name[20];
char title[20];
char publication[20];
float price; public:
void Accept();
void Display();
};
void book::Accept()
{
cout<<"\n Enter book‟s title, author_name, publication and price \n:";
cin>> title >>author_name>> publication >> price;
}
void student::Display()
{
cout<<title <<”\t”<<author_name<<”\t”<<publication <<”\t”<<
price<<”\n”<<;
}
void main()
{
book b, *p;
clrscr();
p=&b;
p->Accept();
cout<<”title \t author_name \t publication \t price\n”;
p-> Display();
getch();
}
Enter book's title, author name, publication, and price: The Catcher in the Rye J.D. Salinger
Little, Brown and Company 12.99
title author_name publication price
The Catcher in the Rye J.D. Salinger Little, Brown and Company 12.99
int main() {
int num = 42;
int* ptr = # // Declare a pointer and assign the address of 'num'
return 0;
}
int main() {
int num = 42;
return 0;
Output:
Memory address of num:
0x7ffe65db36b8 (The address may vary)
`&` operator is used to obtain the memory address of the `num` variable, and that address is
then stored in the `ptr` pointer.
The pointer operator (`*`) is used for dereferencing pointers and accessing the value stored at
a specific memory address. The address operator (`&`) is used to get the memory address of
a variable. These operators are fundamental when working with pointers in C++.
d. Write a C++ program to declare a class train with members as train no and name. Accept
and display data for one object of train. Use pointer to object to call functions of class.
Ans. #include <iostream>
using namespace std;
class Train
{
private:
int trainNo;
string trainName;
public:
// Member function to accept data
void acceptData() {
cout << "Enter Train Number: ";
cin >> trainNo;
cin.ignore(); // Ignore any previous newline character
cout << "Enter Train Name: ";
getline(cin, trainName);
}
int main() {
This program demonstrates how to use a pointer to an object of a class to call its member
functions and access its data members.
class sample {
int a;
public:
void setdata(int x) {
this->a = x;
}
void putdata() {
cout << a;
}
};
int main() {
sample s;
s.setdata(100);
s.putdata();
return 0;
}
100
In the above example, this pointer is used to represent object s when setdata ( ) and putdata (
) functions are called.’
17 . Overloading
(i) Write a C++ program to overload "+" or ‘-‘ operator so that it will perform concatenation
of two strings. (Use class get data function to accept two strings)
Ans.
(ii)Describe Function overloading with suitable program.
Ans. #include <iostream>
using namespace std;
int main() {
int result1 = add(5, 10);
double result2 = add(3.5, 2.5);
string result3 = add("Hello, ", "world!");
cout << "Result 1: " << result1 << endl; // Output: Result 1: 15
cout << "Result 2: " << result2 << endl; // Output: Result 2: 6
cout << "Result 3: " << result3 << endl; // Output: Result 3: Hello, world!
return 0;
}
Result 1: 15
Result 2: 6
Result 3: Hello, world!
5. A virtual function in a base class must be defined, even though it may not be used.
6. The prototypes of the base class version of a virtual function and all the derived class
versions must be identical.
7. We cannot have virtual constructors, but we can have virtual destructors.
8. While a base pointer can point to any type of the derived object, the reverse is not true.
9. When a base pointer points to a derived class, incrementing ordecrementing it will not
make it to point to the next object of the derived class.
10. If a virtual function is defined in the base class, it need not be necessarily redefined in the
derived class
20. Describe the concept of virtual base class with suitable example.
Ans. Virtual Base Class:
An ancestor class is declared as virtual base class which is used to avoid duplication of
inherited members inside child class due to multiple path of inheritance.
Consider a hybrid inheritance as shown in the above diagram. The child class has two direct
base classes, Parent1 and Parent2 which themselves have a common base class as
Grandparent. The child inherits the members of Grandparent via two separate paths. All the
public and protected members of Grandparent are inherited into Child twice, first via Parent1
and again via Parent2. This leads to duplicate sets of the inherited members of Grandparent
inside Child class. The duplication of inherited members can be avoided by making the
common base class as virtual base class while declaring the direct or intermediate base
classes as shown below.
class Grandparent
{
};
class Parent1:virtual public Grandparent
{
};
class Parent2:virtual public Grandparent
{
};
Example:-
#include<iostream.h>
#include<conio.h>
class student
{
int rno;
public:
void getnumber()
{
cout<<"Enter Roll No:";
cin>>rno;
}
void putnumber()
{
cout<<"\n\n\t Roll No:"<<rno<<endl;
}
};
int score;
void getscore()
{
cout<<"Enter Sports Score:";
cin>>score;
}
void putscore()
{
cout<<"\n\t Sports Score is:"<<score;
}
};
void main()
{
result obj;
clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}
Output:-
Roll No:30
Marks Obtained
Part1:45
Part2:48
Sports Score is:40
Total Score:133
21. Write a C++ program to implement following in heritance. Refer Figure No.2:
Accept and display data for one object of class result (Hint: use virtual base class).
Ans. #include <iostream>
using namespace std;
class CollegeStudent {
protected:
int student_id;
string college_code;
public:
void displayCollegeStudentDetails() {
cout << "Student ID: " << student_id << endl;
cout << "College Code: " << college_code << endl;
}
};
public:
void setTestDetails(float perc) {
percentage = perc;
}
void displayTestDetails() {
cout << "Percentage: " << percentage << "%" << endl;
}
};
public:
void setSportsDetails(char grd) {
grade = grd;
}
void displaySportsDetails() {
cout << "Sports Grade: " << grade << endl;
}
};
displayTestDetails();
displaySportsDetails();
}
};
int main() {
Result r;
r.setCollegeStudentDetails(101, "CC123");
r.setTestDetails(85.6);
r.setSportsDetails('A');
r.displayResult();
return 0;
}
void main() {
ifstream file;
char ch;
int n = 0;
clrscr();
file.open("abc.txt");
while (file) {
file.get(ch);
if (ch == '\n') {
n++;
}
}
(iii) Write a C++ program to append data from abc.txt to xyz.txt file.
Ans. Assuming input file as abc.txt with contents "World" and output file
named as xyz.txt with contents "Hello" have been already created.
#include <iostream.h>
#include<fstream.h>
int main()
{
fstream f;
ifstream fin;
fin.open("abc.txt",ios::in);
ofstream fout;
fout.open("xyz.txt", ios::app);
if (!fin)
{
cout<< "file not found";
}
else
{
fout<<fin.rdbuf();
}
char ch;
f.seekg(0);
while (f)
{
f.get(ch);
cout<< ch;
}
f.close();
return 0;
}
Output:
Hello World
(iv) Write a C++ program to copy the contents of a source file student 1.txt to a destination file
student 2.txt using file operations.
Ans. #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Open the source file for reading
ifstream sourceFile("student1.txt");
if (!sourceFile) {
cerr << "Error: Unable to open source file." << endl;
return 1;
}
// Copy the contents from the source file to the destination file
string line;
while (getline(sourceFile, line)) {
destinationFile << line << endl;
}
return 0;
}