0% found this document useful (0 votes)
30 views18 pages

ENDSEMC

The document outlines key concepts of Object-Oriented Programming (OOP) in C++, including features like encapsulation, inheritance, polymorphism, and abstraction. It explains various programming constructs such as constructors, destructors, and operator overloading, along with their definitions and examples. Additionally, it covers memory management, access specifiers, and file handling in C++.

Uploaded by

isnehanagar
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)
30 views18 pages

ENDSEMC

The document outlines key concepts of Object-Oriented Programming (OOP) in C++, including features like encapsulation, inheritance, polymorphism, and abstraction. It explains various programming constructs such as constructors, destructors, and operator overloading, along with their definitions and examples. Additionally, it covers memory management, access specifiers, and file handling in C++.

Uploaded by

isnehanagar
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/ 18

a) List any four features of OOP's. functions.

Encapsulation: Bundling data and functions. Achieved through inheritance and


Inheritance: Deriving new classes from existing pointers/references.
ones. j) Enlist manipulators in C++.
Polymorphism: Functions or methods behave endl, setw, setprecision, fixed, showpoint,
differently based on input. noshowpoint, left, right.
Abstraction: Hiding internal implementation details.
b) Define pure virtual function. a) What is extraction and insertion operator?
A pure virtual function is a function with no >> is the extraction operator (used with cin).
definition in the base class. << is the insertion operator (used with cout).
It is declared using = 0 syntax and forces derived They help with input and output operations.
classes to override it. b) Explain any two manipulators.
It makes the class abstract. endl: Inserts a newline and flushes the output
c) What is cascading of I/O operator? buffer.
Cascading allows chaining of input/output setw(n): Sets field width to n for the next output.
operations using << or >>. c) Define constructor.
It helps perform multiple I/O actions in one A constructor is a special function with the same
statement. name as the class.
For example: cout << "Name: " << name << endl;. It is invoked automatically when an object is
d) List the ways to define a constant. created.
Using #define preprocessor directive. Used to initialize objects.
Using const keyword. d) What is inline function.
Using enum for constant values. An inline function is a function defined with the
Using constexpr (C++11 onwards). inline keyword.
e) What is an abstract class? The compiler replaces the function call with its
An abstract class contains at least one pure virtual code.
function. Reduces function call overhead.
It cannot be instantiated directly. e) What is reference variable? What is its major
It serves as a base class for other classes. use.
f) Define multiple inheritance. A reference variable is an alias for another variable
Multiple inheritance means a class inherits from using &.
more than one base class. It helps in function arguments to modify actual
It allows access to features from multiple classes. variables.
Syntax: class C : public A, public B {}. Used for efficient parameter passing.
g) Define destructor. f) What is Abstraction and Encapsulation.
A destructor is a special member function that is Abstraction: Showing only essential features and
called when an object is destroyed. hiding details.
Its name starts with a tilde ~ followed by class Encapsulation: Binding data and functions into a
name. single unit.
Used to free resources. g) What is compile-time polymorphism.
h) What is 'this' pointer? Also known as static polymorphism.
this pointer holds the address of the current object. It is achieved using function overloading or
It is used to refer to the calling object in member operator overloading.
functions. Resolved during compilation.
Helpful in returning object reference or resolving h) What is default argument.
naming conflicts. Default arguments are values given in function
i) What is Run-Time Polymorphism? declarations.
Run-time polymorphism allows method overriding. They allow function calls with fewer arguments.
Function call is resolved at runtime using virtual e.g., int add(int x, int y = 5).
i) What is the use of scope resolution operator. overloading.
:: is used to access global variables or class Resolved by compiler before execution.
members. j) Explain structure of C++ program.
Used to define a function outside a class. Include header files.
Also used with static members. Declare main function.
j) What are the access specifiers used in C++. Define class and functions.
public: Accessible from anywhere. Use input/output statements and logic inside
private: Accessible only within the class. main().
protected: Accessible in derived classes.
a) What is Encapsulation?
a) Explain tellg() and tellp() with syntax. Encapsulation is the wrapping of data and functions
tellg(): Returns current get position in input stream. into one unit.
Syntax: int pos = fin.tellg(); It restricts direct access to some components.
tellp(): Returns current put position in output Ensures better control and security of data.
stream. Syntax: int pos = fout.tellp(); b) Define the following terms:
b) Explain any two manipulators. i) Early Binding: Function call resolved at compile
setprecision(n): Sets decimal precision for floating- time, e.g., function overloading.
point numbers. ii) Late Binding: Function call resolved at runtime,
fixed: Ensures decimal values are shown in fixed- e.g., virtual functions.
point notation. c) What is Inline function?
c) What is destructor? Inline function replaces the function call with its
Destructor is a special function prefixed with ~. code.
Called automatically when object scope ends. Improves performance for small functions.
Used to release memory or resources. Declared using inline keyword.
d) What are the visibility labels used in C++? d) Explain get() and put() function.
public: Members accessible anywhere. get(): Reads a single character from input stream.
private: Members accessible only inside class. put(): Writes a single character to output stream.
protected: Members accessible in derived class. e) What is stream?
e) What is extraction and insertion operator? A stream is a sequence of bytes for input or output.
Extraction operator >> is used with cin for input. cin and cout are standard I/O streams in C++.
Insertion operator << is used with cout for output. Streams connect programs to devices/files.
They are overloaded for user-defined types too. f) Define Friend function.
f) What is abstraction and encapsulation? A friend function is not a member but has access to
Abstraction hides complexity, showing only private members.
essential details. Declared using friend keyword inside class.
Encapsulation combines data and methods into one Used for operator overloading or accessing
class. internals.
Together they ensure data hiding and modularity. g) Explain the use of new operator, state the
g) What is default argument in function? syntax.
It’s a preset value for a function parameter. new is used to allocate memory dynamically.
If no value is passed, the default is used. Syntax: ptr = new int;
Defined during function declaration. Returns pointer to allocated memory.
h) Write any two uses of scope resolution h) State the need of virtual keyword.
operator. virtual allows function overriding in derived classes.
Accessing global variables hidden by local ones. Used to achieve run-time polymorphism.
Defining class functions outside the class. Ensures correct function call via base class pointer.
i) What is static Polymorphism. i) State user defined data types in C++.
Also called compile-time polymorphism. class, struct, union, enum, typedef.
Implemented using function or operator They allow creation of complex and custom types.
j) Explain the use of Scope Resolution operator. b) Function overriding
Used to define a class function outside the class. Function overriding occurs when a derived class
Access global variables or static members. redefines a base class function.
Syntax: ClassName::FunctionName(). The base function must be virtual.
Used for run-time polymorphism.
a) Array of object c) Exception handling
An array of objects is a collection of multiple C++ handles exceptions using try, throw, and catch.
instances of a class stored in a contiguous memory Used to manage errors like divide by zero, invalid
block. inputs, etc.
Each object in the array can access class members Prevents program termination.
using dot operator.
Syntax: ClassName obj[10]; a) Call-by-value and Call-by-reference
b) Access specifier Call-by-value: Copies the value to function
Access specifiers control access to class members. parameters (original not affected).
C++ has three types: public, private, and protected. Call-by-reference: Passes reference; changes affect
They help implement encapsulation and data original.
hiding. Used for efficiency and modification of original
c) Constructor in derived class data.
Constructors in derived classes initialize derived b) Data abstraction
class members. Abstraction means hiding internal details and
They can also call base class constructors using showing only the essential features.
initializer lists. It simplifies complexity and enhances security.
Syntax: Derived() : Base() { // derived initialization }. Achieved through access specifiers and abstract
classes.
a) Exception Handling c) Default Argument
Exception handling in C++ manages runtime errors Default arguments are specified in function
using try, catch, and throw. declaration.
It ensures the program doesn't crash due to They allow function calls without passing all
unexpected inputs. arguments.
Example: try { ... } catch (exception_type e) { ... }. e.g., int add(int x, int y = 5); calling add(3) returns 8.
b) Operator overloading
Operator overloading allows redefining the a) Explain function overloading with example.
behavior of operators for user-defined types. Function overloading allows multiple functions with
It makes code more intuitive. the same name but different parameter lists within
Syntax: ClassName operator+(ClassName); the same scope.
c) Pointer to object with example It enables the programmer to perform different
A pointer to object stores the address of an object tasks using the same function name by changing
and accesses members using ->. the number or type of arguments.
Example: Example:
Class A { public: void show(); }; int add(int a, int b);
A obj; A* ptr = &obj; ptr->show(); float add(float a, float b);

a) This pointer
this is an implicit pointer available in non-static
member functions.
It points to the current calling object.
Useful for returning object reference or resolving
variable shadowing.
b) What is inheritance? Explain types of a) Explain memory management operators with
inheritance. the help of suitable example.
Inheritance is a mechanism where one class In C++, new and delete are memory management
(derived) acquires properties and behaviors of operators.
another class (base). new dynamically allocates memory during runtime,
It promotes code reusability and establishes while delete frees it.
relationships between classes. Example:
Types include: int *ptr = new int; // allocates memory
Single (one base, one derived) *ptr = 10;
Multiple (more than one base) delete ptr; // deallocates memory
Multilevel (derived from derived) They help manage heap memory safely.
Hierarchical (one base, multiple derived) b) Explain memory allocation for objects with non-
Hybrid (combination of types) static and static data members.
c) Explain static data members and static member Each object of a class has its own copy of non-static
functions with example. data members, stored on the stack or heap.
Static members are shared among all objects of a Static data members are shared among all objects
class. and are stored in static storage.
A static data member is declared using the static They are initialized outside the class definition.
keyword and initialized outside the class. Accessed using the class name rather than an
Static functions can only access static data object.
members. c) When do we make a class virtual base class?
Example: Explain with suitable example.
class Test { static int count; static void show(); }; A virtual base class is used in multiple inheritance
d) What is friend function? Write characteristics of to avoid duplication of base class members.
friend function. It resolves the diamond problem by sharing a single
A friend function is not a member of the class but instance of the base class.
has access to its private and protected data. Syntax:
It is declared using the friend keyword inside the class A {};
class. class B : virtual public A {};
Characteristics: class C : virtual public A {};
Not called using an object class D : public B, public C {};
Doesn't belong to any object d) Explain array of object in C++ with example.
Helps in operator overloading when access to An array of objects is a collection of instances of a
private members is needed class stored in contiguous memory.
Increases coupling but is useful in special cases It allows handling multiple objects using indexing.
e) Explain use of any four file opening modes. Example:
ios::in – Opens a file for reading. class Student { public: void show(); };
ios::out – Opens a file for writing (creates file if not Student s[3]; // array of 3 Student objects
exists). e) Explain any four formatted input/output
ios::app – Opens a file and appends data to the functions.
end. setw(n) – Sets field width for output.
ios::binary – Opens a file in binary mode for setprecision(n) – Sets number of digits after
reading/writing binary data. decimal.
These modes are used with fstream objects during showpoint – Forces decimal point to be displayed.
file operations. fixed – Uses fixed-point notation for floating-point
values.
These manipulators are included in <iomanip> and
enhance output formatting.
a) Explain operator overloading in C++ with an It supports code reuse in related subclasses.
example. Example:
Operator overloading allows custom definitions of class Animal {};
operators for user-defined types. class Dog : public Animal {};
It improves code readability by allowing intuitive
expressions. class Cat : public Animal {};
Example: a) List different types of constructor. Explain any
class Complex { one constructor with example.
int real, imag; Types of constructors:
Complex operator+(Complex c) { return Default constructor
Complex(real + c.real, imag + c.imag); } Parameterized constructor
}; Copy constructor
b) Explain memory allocation for objects with non- Dynamic constructor
static and static data members. Example (Parameterized):
Non-static data members are part of each object’s class A {
memory allocation. int x;
Static members exist only once, regardless of how A(int a) { x = a; }
many objects are created. };
They are stored in static memory and shared across b) What is function overloading? Explain with
all objects. suitable example.
Access to static members is done using the class Function overloading means creating multiple
name. functions with the same name but different
c) What is pure virtual function? Explain with the parameters.
help of example. It helps in code readability and modular design.
A pure virtual function is declared using = 0 and has Example:
no definition in the base class. void display(int);
It forces derived classes to implement the function, void display(double);
making the base class abstract. c) Describe different types of inheritance.
Example: Single – One base and one derived class.
class Shape { virtual void draw() = 0; }; Multilevel – Derived class inherits another derived
class Circle : public Shape { void draw() { /*...*/ } }; class.
d) Explain dynamic constructor with suitable Multiple – One class inherits from more than one
example. base class.
A dynamic constructor allocates memory at Hierarchical – Multiple classes inherit from one
runtime using the new operator. base.
It is useful when the size or content of an object Hybrid – Combination of more than one type.
depends on input. d) Explain virtual base class with suitable diagram.
Example: Used to avoid duplication when multiple derived
class Array { classes inherit from a common base.
int *arr; Declared using virtual keyword.
Array(int n) { arr = new int[n]; } Example:
}; class A {};
e) What is inheritance and explain hierarchical class B : virtual public A {};
inheritance. class C : virtual public A {};
Inheritance allows reuse of code by creating new class D : public B, public C {};
classes from existing ones.
In hierarchical inheritance, multiple derived classes
inherit from a single base class.
e) Describe file manipulators with their syntaxes. private:
File manipulators format file input/output. string designation, department;
Examples: float basicSalary;
ios::in – open file for reading public:
ios::out – open file for writing void accept() {
ios::app – append mode Employee::accept();
ios::binary – binary mode cout << "Enter designation, department, and
Syntax: basic salary: ";
fstream file; cin >> designation >> department >>
file.open("data.txt", ios::out | ios::app); basicSalary;
}
b) C++ Program to Design a Class Hierarchy for void display() {
Person, Employee, and Manager: Employee::display();
#include <iostream> cout << "Designation: " << designation << ",
using namespace std; Department: " << department << ", Basic Salary: "
<< basicSalary << endl;
class Person { }
protected: float getSalary() {
string name, address, phoneNo; return basicSalary;
public: }
void accept() { };
cout << "Enter name, address, phone number:
"; int main() {
cin >> name >> address >> phoneNo; int n;
} cout << "Enter number of managers: ";
void display() { cin >> n;
cout << "Name: " << name << ", Address: " << Manager m[n];
address << ", Phone: " << phoneNo << endl; for (int i = 0; i < n; i++) {
} m[i].accept();
}; }
int highestSalaryIdx = 0;
class Employee : public Person { for (int i = 1; i < n; i++) {
protected: if (m[i].getSalary() >
int eno; m[highestSalaryIdx].getSalary()) {
string ename; highestSalaryIdx = i;
public: }
void accept() { }
Person::accept(); cout << "Manager with highest salary: ";
cout << "Enter employee number and name: "; m[highestSalaryIdx].display();
cin >> eno >> ename; return 0;
} }
void display() {
Person::display();
cout << "Employee number: " << eno << ",
Employee name: " << ename << endl;
}
};

class Manager : public Employee {


c) C++ Program to Overload Functions for #include <iostream>
Calculating Area of Circle, Square, and Rectangle: using namespace std;
#include <iostream>
using namespace std; inline int perimeter(int l, int w) {
return 2 * (l + w);
class Area { }
public:
float area(float radius) { // Circle int main() {
return 3.14 * radius * radius; int length, width;
} cout << "Enter length and width of rectangle: ";
float area(float side, float side2 = 0) { // Square cin >> length >> width;
and Rectangle cout << "Perimeter of rectangle: " <<
if (side2 == 0) { perimeter(length, width) << endl;
return side * side; // Square return 0;
} else { }
return side * side2; // Rectangle
}
}
}; a) C++ Program to Create a Class to Swap Two
Entered Numbers Using Call by Reference:
int main() { #include <iostream>
Area a; using namespace std;
cout << "Area of Circle: " << a.area(5) << endl;
cout << "Area of Square: " << a.area(4) << endl; class SwapNumbers {
cout << "Area of Rectangle: " << a.area(4, 6) << int a, b;
endl; public:
return 0; void accept() {
} cout << "Enter two numbers: ";
d) C++ Program to Print the Following Pattern: cin >> a >> b;
A }
BC void display() {
DEF cout << "a = " << a << ", b = " << b << endl;
GHIJ }
#include <iostream> void swap(SwapNumbers &n) {
using namespace std; int temp = n.a;
n.a = n.b;
int main() { n.b = temp;
char ch = 'A'; }
for (int i = 1; i <= 4; i++) { };
for (int j = 1; j <= i; j++) { int main() {
cout << ch << " "; SwapNumbers sn;
ch++; sn.accept();
} cout << "Before swap: ";
cout << endl; sn.display();
} sn.swap(sn);
return 0; cout << "After swap: ";
} sn.display();
e) C++ Program to Calculate and Display Perimeter return 0;
of Rectangle Using Inline Function }
b) C++ Program to Create a Class Book with Static c) C++ Program to Calculate Square and Cube of an
Count of Books: Integer Number Using Inline Functions
#include <iostream> #include <iostream>
using namespace std; using namespace std;

class Book { inline int square(int x) {


int id; return x * x;
string name, author, publication; }
static int count;
public: inline int cube(int x) {
void accept() { return x * x * x;
cout << "Enter Book ID, Name, Author, }
Publication: ";
cin >> id >> name >> author >> publication; int main() {
count++; int num;
} cout << "Enter a number: ";
void display() { cin >> num;
cout << id << " " << name << " " << author << " cout << "Square: " << square(num) << endl;
" << publication << endl; cout << "Cube: " << cube(num) << endl;
} return 0;
static void showCount() { }
cout << "Total books: " << count << endl;
} d) C++ Program to Count the Number of Times
}; display() is Called Using Static Data Member:
#include <iostream>
int Book::count = 0; using namespace std;

int main() { class DisplayCounter {


Book b1, b2; static int count;
b1.accept(); public:
b2.accept(); void display() {
b1.display(); count++;
b2.display(); cout << "Display function called " << count << "
Book::showCount(); times." << endl;
return 0; }
} };

int DisplayCounter::count = 0;

int main() {
DisplayCounter d1, d2;
d1.display();
d2.display();
d1.display();
return 0;
}
e) C++ Program to Read Contents of a Text File and a) C++ Program to Create a Class with Two Data
Count the Number of Characters, Words, and Members and Swap Two Numbers Using Call by
Lines: Reference:
#include <iostream> #include <iostream>
#include <fstream> using namespace std;
#include <cctype>
using namespace std; class SwapNumbers {
int a, b;
int main() { public:
ifstream fin("input.txt"); void accept() {
if (!fin) { cout << "Enter two numbers: ";
cout << "Error opening file!" << endl; cin >> a >> b;
return 1; }
} void display() {
cout << "a = " << a << ", b = " << b << endl;
char ch; }
int chars = 0, words = 0, lines = 0; void swap(SwapNumbers &n) {
bool inWord = false; int temp = n.a;
n.a = n.b;
while (fin.get(ch)) { n.b = temp;
chars++; }
if (ch == '\n') lines++; };
if (isspace(ch)) {
if (inWord) words++; int main() {
inWord = false; SwapNumbers sn;
} else { sn.accept();
inWord = true; cout << "Before swap: ";
} sn.display();
} sn.swap(sn);
cout << "After swap: ";
if (inWord) words++; // Count last word if file sn.display();
doesn't end with space/newline return 0;
}
fin.close();
cout << "Characters: " << chars << " Words: " <<
words << " Lines: " << lines << endl;
return 0;
}
b) C++ Program to Create a Class Customer with c) C++ Program to Calculate Factorial of an Integer
Information and Display the Customer with Number Using Inline Function:
Maximum Salary: #include <iostream>
#include <iostream> using namespace std;
using namespace std;
inline int factorial(int n) {
class Customer { int fact = 1;
int C_id; for (int i = 1; i <= n; i++)
string C_name; fact *= i;
float C_Salary; return fact;
public: }
void accept() {
cout << "Enter Customer ID, Name, Salary: "; int main() {
cin >> C_id >> C_name >> C_Salary; int num;
} cout << "Enter number: ";
void display() { cin >> num;
cout << "Customer ID: " << C_id << ", Name: " cout << "Factorial: " << factorial(num) << endl;
<< C_name << ", Salary: " << C_Salary << endl; return 0;
} }
float getSalary() { d) C++ Program to Count the Number of Times
return C_Salary; count() is Called Using Static Data Member:
} #include <iostream>
}; using namespace std;

int main() { class Counter {


int n; static int count;
cout << "Enter number of customers: "; public:
cin >> n; void countCalls() {
Customer c[n]; count++;
for(int i=0; i<n; i++) { cout << "Function called " << count << " times."
c[i].accept(); << endl;
} }
int maxIdx = 0; };
for(int i=1; i<n; i++) {
if(c[i].getSalary() > c[maxIdx].getSalary()) int Counter::count = 0;
maxIdx = i;
} int main() {
cout << "Customer with the highest salary: "; Counter c1, c2, c3;
c[maxIdx].display(); c1.countCalls();
return 0; c2.countCalls();
} c3.countCalls();
return 0;
}
e) C++ Program to Copy the Contents of a Text File return 0;
into Another Text File: }
#include <iostream> C++ Program to Declare a Class of Vehicle. Derived
#include <fstream> Classes are Two-Wheeler, Three-Wheeler, and
using namespace std; Four-Wheeler. Display the Properties of Each Type
of Vehicle Using Member Functions:
int main() { #include <iostream>
ifstream fin("source.txt"); using namespace std;
ofstream fout("destination.txt");
class Vehicle {
if (!fin) { public:
cout << "Error opening source file." << endl; void display() {
return 1; cout << "This is a general vehicle." << endl;
} }
};
char ch;
while (fin.get(ch)) { class TwoWheeler : public Vehicle {
fout.put(ch); public:
} void display() {
cout << "This is a Two-Wheeler vehicle." <<
fin.close(); endl;
fout.close(); }
cout << "File copied successfully." << endl; };
return 0;
} class ThreeWheeler : public Vehicle {
C++ Program to Calculate Area and Circumference public:
of a Circle Using Inline Function: void display() {
#include <iostream> cout << "This is a Three-Wheeler vehicle." <<
#define PI 3.14159 endl;
using namespace std; }
};
inline double area(double radius) { class FourWheeler : public Vehicle {
return PI * radius * radius; public:
} void display() {
cout << "This is a Four-Wheeler vehicle." <<
inline double circumference(double radius) { endl;
return 2 * PI * radius; }
} };
int main() {
int main() { TwoWheeler t;
double radius; ThreeWheeler th;
cout << "Enter the radius of the circle: "; FourWheeler f;
cin >> radius;
t.display();
cout << "Area of the circle: " << area(radius) << th.display();
endl; f.display();
cout << "Circumference of the circle: " <<
circumference(radius) << endl; return 0;
}
C++ Program to Use setf() and setiosflags()
Manipulator: return 0;
#include <iostream> }
#include <iomanip> b) Explain Parameterized Constructor with
using namespace std; Example
Definition: A parameterized constructor is a
int main() { constructor that takes arguments to initialize an
double num = 123.456789; object.
Example:
// Using setf manipulator #include <iostream>
cout.setf(ios::fixed); using namespace std;
cout.setf(ios::showpoint);
cout << "Number with fixed and showpoint: " << class Rectangle {
num << endl; int length, width;
public:
// Using setiosflags manipulator Rectangle(int l, int w) {
cout << setiosflags(ios::fixed) << setprecision(2); length = l;
cout << "Number with fixed and 2 decimal width = w;
places: " << num << endl; }
void display() {
return 0; cout << "Area = " << length * width << endl;
} }
C++ Program to Compare Two Strings Using };
Overloaded Operator ==
#include <iostream> int main() {
#include <cstring> Rectangle r(10, 5); // Parameterized constructor
using namespace std; is called
r.display();
class String { return 0;
char str[100]; }
public: Explanation:
void accept() { Rectangle(int l, int w) is the parameterized
cout << "Enter string: "; constructor.
cin >> str; It initializes the length and width with given
} arguments.
bool operator==(String s) {
return strcmp(str, s.str) == 0;
}
};

int main() {
String s1, s2;
s1.accept();
s2.accept();

if (s1 == s2)
cout << "Strings are equal." << endl;
else
cout << "Strings are not equal." << endl;
c) Explain Virtual Base Class with Example }
Definition: When multiple derived classes inherit e) Overload Binary + Operator for String
from the same base class, and another class Concatenation:
inherits from them, it may result in duplication of #include <iostream>
base class. To avoid this, use virtual inheritance. #include <cstring>
Example: using namespace std;
#include <iostream>
using namespace std; class String {
char str[100];
class A { public:
public: void accept() {
int x; cout << "Enter string: ";
}; cin >> str;
}
class B : virtual public A {
}; String operator+(String s) {
String temp;
class C : virtual public A { strcpy(temp.str, str);
}; strcat(temp.str, s.str);
return temp;
class D : public B, public C { }
};
void display() {
int main() { cout << "Concatenated String: " << str << endl;
D obj; }
obj.x = 100; // No ambiguity due to virtual base };
class
cout << "Value of x: " << obj.x << endl; int main() {
return 0; String s1, s2, s3;
} s1.accept();
Explanation: s2.accept();
Class A is virtually inherited by B and C. s3 = s1 + s2;
D inherits B and C, but there's only one copy of A in s3.display();
D. return 0;
d) Program to Find Maximum of Two Integers }
Using Function Template:
#include <iostream>
using namespace std;

template <class T>


T maximum(T a, T b) {
return (a > b) ? a : b;
}

int main() {
int x = 10, y = 20;
cout << "Maximum is: " << maximum(x, y) <<
endl;
return 0;
a) Can we pass class object as function c) What is Class Template? Explain with syntax and
arguments? Explain with the help of an example: example
Yes, class objects can be passed to functions in Definition: A class template allows you to create a
three ways: generic class that can work with different data
By value types.
By reference Syntax:
By address (pointer) template <class T>
Example (pass by reference): class ClassName {
#include <iostream> T data;
using namespace std; public:
void setData(T d) {
class Sample { data = d;
int a, b; }
public: void showData() {
void accept(int x, int y) { cout << "Data = " << data << endl;
a = x; }
b = y; };
} Example:
void display() { #include <iostream>
cout << "a = " << a << ", b = " << b << endl; using namespace std;
}
template <class T>
void add(Sample &s2) { class Number {
a += s2.a; T num;
b += s2.b; public:
} void set(T n) {
}; num = n;
}
int main() { void show() {
Sample s1, s2; cout << "Number = " << num << endl;
s1.accept(5, 10); }
s2.accept(3, 6); };
s1.add(s2); // Passing object s2 to s1
s1.display(); int main() {
return 0; Number<int> n1;
} n1.set(10);
b) Explain various stream classes used to perform n1.show();
console I/O operations
In C++, iostream is the main header file for console Number<float> n2;
I/O. It includes these stream classes: n2.set(15.5);
Class Description n2.show();
istream Input stream class (e.g. cin)
return 0;
ostream Output stream class (e.g. cout) }
iostream Supports both input and output
ifstream Input file stream (used for file input)
ofstream Output file stream (used for file output)
fstream Supports both file input/output
d) Program to perform addition of two matrices Example (Pass by Reference):
using operator overloading: #include <iostream>
#include <iostream> using namespace std;
using namespace std; class Number {
int a;
class Matrix { public:
int a[2][2]; void set(int x) {
public: a = x;
void accept() { }
cout << "Enter 4 elements of 2x2 matrix:\n"; void add(Number &n) { // object passed by
for(int i=0; i<2; i++) reference
for(int j=0; j<2; j++) a = a + n.a;
cin >> a[i][j]; }
} void show() {
cout << "Value: " << a << endl;
Matrix operator+(Matrix m) { }
Matrix temp; };
for(int i=0; i<2; i++) int main() {
for(int j=0; j<2; j++) Number n1, n2;
temp.a[i][j] = a[i][j] + m.a[i][j]; n1.set(10);
return temp; n2.set(20);
} n1.add(n2); // n2 is passed as object
n1.show(); // Output: 30
void display() { return 0;
cout << "Matrix:\n"; }
for(int i=0; i<2; i++) { b) Explain different characteristics of friend
for(int j=0; j<2; j++) function.
cout << a[i][j] << " "; A friend function is a non-member function that
cout << endl; can access private and protected members of a
} class.
} Characteristics:
}; Not a member: It’s not a class member but has
access rights.
int main() { Declared using friend keyword inside the class.
Matrix m1, m2, m3; Can be defined anywhere (inside or outside class).
m1.accept(); Used for operator overloading and two-class
m2.accept(); operations.
m3 = m1 + m2; Cannot be called using object.
m3.display(); Example:
return 0; class A {
} int a;
a) Explain object as function arguments. Explain public:
with the help of an example program. A() { a = 10; }
In C++, objects can be passed to functions to access friend void show(A);
their data members or perform operations. There };
are three ways to pass an object:
Pass by Value void show(A obj) {
Pass by Reference cout << "Value of a is: " << obj.a << endl;
Pass by Address (Pointer) }
c) What is class Template? Explain syntax of class void getData(string s) {
template with suitable example. str = s;
A class template is used to create a class that can }
work with any data type.
Syntax: StringAdder operator+(StringAdder s2) {
template <class T> StringAdder temp;
class ClassName { temp.str = str + s2.str;
T data; return temp;
public: }
void setData(T d) { data = d; }
void showData() { cout << data; } void show() {
}; cout << "Concatenated String: " << str << endl;
Example: }
#include <iostream> };
using namespace std;
int main() {
template <class T> StringAdder s1, s2, s3;
class Box { s1.getData("Hello ");
T value; s2.getData("World");
public: s3 = s1 + s2;
void set(T val) { s3.show();
value = val; return 0;
} }
b) Explain try, catch, and throw in exception
void show() { handling.
cout << "Value = " << value << endl; In C++, exception handling is used to handle
} runtime errors using three keywords:
}; try: Block of code to monitor for errors.
throw: Used to throw an exception when an error
int main() { occurs.
Box<int> intBox; catch: Block of code that handles the exception.
intBox.set(100); Example:
intBox.show(); #include <iostream>
using namespace std;
Box<float> floatBox;
floatBox.set(12.5); int main() {
floatBox.show(); int a = 10, b = 0;
try {
return 0; if (b == 0)
} throw "Division by zero error!";
d) Write a program to overload binary + operator cout << "Result: " << a / b;
to add two strings. } catch (const char* msg) {
#include <iostream> cout << "Exception caught: " << msg << endl;
#include <string> }
using namespace std; return 0;
}
class StringAdder {
string str;
public:
c) Design C++ class which contains function };
display(). Write a program to count number of
times display() function is called (Use static data int main() {
member). Demo d1; // constructor called
#include <iostream> return 0; // destructor called automatically
using namespace std; }
e) What is tokens in C++? Explain in detail.
class Counter { Tokens are the smallest units in a C++ program. A
static int count; // static data member C++ compiler breaks code into meaningful tokens
public: during compilation.
void display() { Types of Tokens:
count++; Keywords – Reserved words (e.g., int, class, return)
cout << "Display called " << count << " times." Identifiers – Names of variables, functions, classes
<< endl; (e.g., sum, main)
} Constants – Fixed values (e.g., 10, 3.14, 'A')
}; Operators – Symbols that perform operations (e.g.,
+, -, =)
int Counter::count = 0; // initialize static member Punctuators/Symbols – Special symbols (e.g., ;, {},
())
int main() { Strings – Text inside double quotes (e.g., "Hello")
Counter c1, c2; Example:
c1.display(); // 1 int a = 10;
c2.display(); // 2 Here:
c1.display(); // 3 int → keyword
return 0; a → identifier
} = → operator
d) What is Destructor? State the importance of 10 → constant
destructor with example. ; → punctuator
A destructor is a special member function that is
automatically invoked when an object goes out of
scope. It cleans up memory and resources used by
the object.
Characteristics:
Same name as class preceded by ~
No return type and no parameters
Automatically called
Example:
#include <iostream>
using namespace std;

class Demo {
public:
Demo() {
cout << "Constructor called" << endl;
}

~Demo() {
cout << "Destructor called" << endl;
}
a) C++ Program to Create a Class Product for Bill
Generation:
#include <iostream>
using namespace std;

class Product {
string pname;
float price;
int quantity;
public:
void accept() {
cout << "Enter product name, price, and
quantity: ";
cin >> pname >> price >> quantity;
}
void display() {
cout << "Product: " << pname << ", Price: " <<
price << ", Quantity: " << quantity << endl;
}
float calculateBill() {
return price * quantity;
}
};

int main() {
int n;
cout << "Enter the number of products: ";
cin >> n;
Product p[n];
float totalBill = 0;
for (int i = 0; i < n; i++) {
p[i].accept();
totalBill += p[i].calculateBill();
}
cout << "Total bill: " << totalBill << endl;
return 0;
}

You might also like