PCC
UNIT 1
Q.Explain the need for Object Oriented Programming language.
Object-Oriented Programming (OOP) is a programming paradigm that organizes
software design around objects, which represent real-world entities with attributes (data)
and methods (functions) that define their behavior.
The need for OOP arises due to the following reasons:
1. Modularity and Reusability
o OOP allows breaking down complex problems into smaller, manageable
objects (modules), making the code easier to understand and maintain.
o Classes can be reused across different programs, reducing redundancy.
2. Data Encapsulation and Security
o OOP bundles data and methods within a single unit (class), preventing direct
access to data and ensuring better security.
3. Inheritance
o Enables new classes to inherit properties and behaviors from existing
classes, promoting reusability and reducing code duplication.
4. Polymorphism
o Allows the same function or method to work differently for different objects,
improving flexibility in programming.
5. Improved Maintainability
o Since OOP code is modular and well-structured, it is easier to update, debug,
and troubleshoot errors.
6. Scalability
o OOP allows easy modification and expansion of systems since the design is
based on small, self-contained objects.
These features make OOP an essential approach for developing complex and efficient
software systems.
Q.Explain Namespaces with the help of Programming example.
A namespace is a way to group identifiers (such as variables, functions, and
classes) to avoid name conflicts in large programs. It helps organize code and
makes it more manageable.
Example Without Namespace:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Here, we use std::cout because cout belongs to the std (standard) namespace.
Example With Namespace:
#include <iostream>
using namespace std; // Now we don't need to use std::
int main() {
cout << "Hello, World!" << endl;
return 0;
}
By using using namespace std;, we can write cout instead of std::cout.
Conclusion:
Namespaces prevent naming conflicts and help in organizing code efficiently, especially
in large programs.
Q.Explain the concept of class & object in C++ with example.
Class:
A class is a blueprint or template for creating objects. It defines data members
(attributes) and methods (functions) but does not store actual data itself.
Object:
An object is an instance of a class. It holds actual data and interacts with other objects or
functions using methods. Each object has its own attributes (variables) and can perform
actions (functions).
#include <iostream>
#include <string>
using namespace std;
// Define a class named 'Person'
class Person {
public:
string name; // Data member (attribute)
int age;
// Method (function) inside the class
void introduce() {
cout << "Hi, my name is " << name << " and I am " << age << " years old." << endl;
}
};
int main() {
Person person1; // Create an object of the Person class
// Assign values to object attributes
person1.name = "John";
person1.age = 25;
// Call the method to introduce the person
person1.introduce();
return 0;
}
Output: Hi, my name is John and I am 25 years old.
Class Definition (Person)
o The Person class has two data members: name and age.
o It has a method introduce(), which prints a message.
Creating an Object (person1)
o The person1 object is created from the Person class.
o Attributes (name and age) are assigned values.
o The introduce() method is called to display the information.
Conclusion:
A class is like a blueprint, and an object is a real-world entity created from it.
Objects allow us to work with real data using the structure defined in a class.
Q.Explain following OOP features: a) Data Abstraction b) Data
Encapsulation 5. Explain following OOP features: a) Inheritance. d)
Polymorphism
a) Data Abstraction - Example: Student Report
Explanation:
A student sees only the final marks in the report card.The internal calculation (assignments,
exams, weightage) is hidden from the student.This is Abstraction—only important details
(total marks) are shown, while internal processing is hidden.
Example:
#include <iostream>
using namespace std;
class Student {
private:
int marks1 = 85, marks2 = 90, marks3 = 80; // Internal data (hidden)
int calculateTotal() { // Hidden method
return marks1 + marks2 + marks3;
}
public:
void showTotalMarks() { // Only necessary details are shown
cout << "Total Marks: " << calculateTotal() << endl;
}
};
int main() {
Student s1;
s1.showTotalMarks(); // Student can see only total marks
return 0;
}
Output: Total marks- 225
b) Data Encapsulation - Example: Student Marks in a Class
Explanation:
A teacher records marks for each student in a system.
The marks are private and cannot be changed by students.
Students can only see their marks through a public method (e.g., view report).
This is Encapsulation—marks are protected, and only the teacher can modify them.
Example:
#include <iostream>
using namespace std;
class Student {
private:
int marks = 90; // Private data (can't be accessed directly)
public:
void showMarks() { // Public method to access marks
cout << "Your marks: " << marks << endl;
}
void updateMarks(int newMarks) { // Only authorized modification
if (newMarks >= 0 && newMarks <= 100) {
marks = newMarks;
cout << "Marks updated successfully!" << endl;
} else {
cout << "Invalid marks!" << endl;
}
}
};
int main() {
Student s1;
s1.showMarks(); // Viewing marks
s1.updateMarks(95); // Updating marks through a method
s1.showMarks(); // Viewing updated marks
return 0;
}
Output: Your marks: 90
Marks updated successfully!
Your marks: 95
Q.Explain the message passing with the help of example.
Message passing refers to communication between objects in an Object-
Oriented Program.
Objects send messages to each other by calling methods (functions) to interact
and exchange information.
It helps in modular programming and improves code organization.
Example; In a school, a teacher asks a student about their marks. The student
responds with their marks. Here, the teacher is sending a message, and the
student is responding to it.
C++ example:
#include <iostream>
using namespace std;
class Student {
public:
int marks;
void setMarks(int m) { // Receives message to set marks
marks = m;
void showMarks() { // Responds with marks
cout << "Student's Marks: " << marks << endl;
};
int main() {
Student s1; // Object created
s1.setMarks(95); // Message sent to set marks
s1.showMarks(); // Message sent to display marks
return 0;
Output: Student's Marks= 95
Object s1 is created.
The setMarks(95) message is sent to the s1 object to set marks.
The showMarks() message is sent to display marks.
The object responds accordingly to each message.
Q.Define Data Type. List out Built in data type with example.
A data type defines the type of value a variable can store in a program. It determines the
size, range, and operations that can be performed on the data.
Built-in Data Types in C++
1. Integer (int) – Stores whole numbers.
Example: int a = 10;
2. Floating-point (float) – Stores decimal numbers (single precision).
Example: float b = 5.75;
3. Double (double) – Stores larger decimal numbers (double precision).
Example: double c = 10.9876;
4. Character (char) – Stores single characters using single quotes.
Example: char d = 'A';
5. Boolean (bool) – Stores true or false values.
Example: bool isPassed = true;
6. Void (void) – Represents an absence of data, mostly used for functions that do not
return any value.
Example: void display();
Conclusion
Built-in data types in C++ help store different types of values, such as numbers,
characters, and boolean values, which are essential for programming.
Q.Explain derived data types with C++ Example
Derived data types are created using built-in data types. They help in storing and
managing complex data efficiently.
Types of Derived Data Types:
1. Arrays – A collection of elements of the same type stored in contiguous memory
locations.
Example:
int arr[5] = {1, 2, 3, 4, 5};
2. Pointers – Stores the memory address of another variable.
int num = 10;
int* ptr = #
3. References – An alias for another variable.
int x = 20;
int& ref = x;
Conclusion
Derived data types in C++ help organize data in a structured way, improving memory
management and code efficiency.
Q.Explain user defined Data Type with C++ Example
User-defined data types are created by programmers to store and manage complex data
in a s structured way. They are built using primitive and derived data types.
Types of User-Defined Data Types:
1. Structures (struct) – Groups multiple variables of different data types under one
name.
Example:
struct Student {
int rollNo;
string name;
};
2. Classes (class) – Similar to structures but also include methods (functions).
Example:
class Car {
public:
string brand;
int speed;
};
3. Enumerations (enum) – Defines a set of named integer constants.
Example:
enum Color { Red, Green, Blue };
User-defined data types allow programmers to create custom data structures that improve
code organization and reusability.
Q.Explain control structures with the help of Programming example.
Control structures determine the flow of execution in a program. They help in making
decisions, repeating tasks, and controlling program behavior.
Types of Control Structures:
1. Sequential Control Structure – Executes statements one after another in order.
Example:
int a = 5, b = 10;
int sum = a + b;
cout << "Sum: " << sum;
2. Selection (Decision-Making) Control Structure – Executes different code blocks
based on conditions.
if-else Statement
int num = 10;
if (num > 0) {
cout << "Positive";
} else {
cout << "Negative";
}
switch Statement
int day = 2;
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
default: cout << "Invalid";
}
3. Iteration (Looping) Control Structure – Repeats code multiple times.
for Loop
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
while Loop
int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}
Control structures help in making programs efficient by allowing decision-making and
looping mechanisms.
Q.Explain switch statement with the help of Programming example.
The switch statement is a decision-making control structure used to execute one
block of code from multiple options based on a single expression. It is useful
when there are multiple conditions to check.
Syntax of Switch Statement:
switch (expression) {
case value1:
// Code block
break;
case value2:
// Code block
break;
default:
// Code block (if no case matches)
Example:
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
default:
cout << "Invalid day";
return 0;
Output: Wednesday
The variable day is checked in the switch expression. If day matches case 3,
"Wednesday" is printed. The break statement prevents unnecessary execution of other
cases. If no case matches, the default case executes. The switch statement is useful for
handling multiple conditions efficiently. It is better than multiple if-else statements when
checking a single variable with many possible values.
Q.Explain following with the help of Programming example.
a if b) if else c) if else ladder d) Nested if
Conditional Statements in C++
if Statement
The if statement checks a condition. If the condition is true, the code inside the block is
executed.
#include <iostream>
using namespace std;
int main() {
int num = 10;
if (num > 0) {
cout << "The number is positive.";
}
return 0;
}
Output:
The number is positive.
if-else Statement
The if-else statement provides an alternative. If the condition is false, the else block
executes.
#include <iostream>
using namespace std;
int main() {
int num = -5;
if (num > 0) {
cout << "The number is positive.";
} else {
cout << "The number is negative.";
}
return 0;
}
Output:The number is negative.
if-else-if Ladder
The if-else-if ladder checks multiple conditions one by one. Once a condition is true, its block
executes, and the rest are skipped.
#include <iostream>
using namespace std;
int main() {
int num = 0;
if (num > 0) {
cout << "The number is positive.";
} else if (num < 0) {
cout << "The number is negative.";
} else {
cout << "The number is zero.";
}
return 0;
}
Output:
The number is zero.
Nested if Statement
An if statement inside another if is called a nested if. It allows multiple levels of condition
checking.
#include <iostream>
using namespace std;
int main() {
int num = 5;
if (num >= 0) {
if (num == 0) {
cout << "The number is zero.";
} else {
cout << "The number is positive.";
}
} else {
cout << "The number is negative.";
}
return 0;
}
Output: The number is positive.
Conclusion - Conditional statements help in making decisions in a program based on given
conditions. They improve code flexibility and control flow.
Q.Explain following with the help of Programming example.
a) While b) Do while c) for d) Nested for
Looping Statements in C++
Loops in C++ allow executing a block of code multiple times until a condition is met. There
are three main types of loops: while, do-while, and for.
a) while Loop
The while loop executes repeatedly as long as the condition is true.
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << i << " ";
i++; // Increment to avoid infinite loop
}
return 0;
}
Output: 1 2 3 4 5
Explanation:The loop starts with i = 1 and runs until i becomes greater than 5.i++ increments
the value in each iteration.
b) do-while Loop
The do-while loop is similar to while, but it executes at least once before checking the
condition.
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
Output:1 2 3 4 5
Explanation:The code inside do runs at least once, even if the condition is false. After
execution, the condition is checked.
c) for Loop
The for loop is commonly used when the number of iterations is known.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
return 0;
}
Output 1 2 3 4 5
Explanation: The for loop consists of initialization (i = 1), condition (i <= 5), and update (i++).
The loop repeats until the condition becomes false.
d) Nested for Loop
A nested for loop means a for loop inside another for loop.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 2; i++) {
cout << "Outer: " << i << "\n";
for (int j = 1; j <= 3; j++) {
cout << " Inner: " << j << "\n";
}
}
return 0;
}
Output: Outer: 1 Inner: 1 Inner: 2 Inner: 3 Outer: 2 Inner: 1 Inner: 2 Inner: 3
Explanation: The outer loop runs 2 times. The inner loop runs 3 times for each iteration of
the outer loop.
Conclusion
while – Repeats while the condition is true. do-while – Runs at least once before
checking the condition. for – Used when the number of iterations is known. nested for
– A for loop inside another for loop.These loops simplify repetitive tasks and improve
efficiency in programming.
Q.Explain following with the help of Programming example.
a) break b) continue c) Return d) goto
1.break Statement
The break statement is used to exit a loop or switch statement immediately when
a specific condition is met.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exits the loop when i is 3
}
cout << i << " ";
}
return 0;
}
Output: 1 2
2.continue Statement
The continue statement is used to skip the current iteration and move to the next
iteration of the loop.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips iteration when i is 3
}
cout << i << " ";
}
return 0;
}
Output: 1 2 4 5
3.return Statement
The return statement exits a function and optionally returns a value.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b; // Returns the sum
}
int main() {
int sum = add(5, 3);
cout << "Sum: " << sum;
return 0;
}
Output: sum: 8
4.goto Statement
The goto statement jumps to a labeled statement in the program.
#include <iostream>
using namespace std;
int main() {
int i = 1;
start: // Label
cout << i << " ";
i++;
if (i <= 5) {
goto start; // Jumps back to the label
}
return 0;
}
Output: 1 2 3 4 5
Jump statements control the flow of execution in loops and functions, improving
program efficiency.
Q.Explain Public, Private & Protected access specifier. Write a C++ program
for any one.
Access specifiers control the visibility of class members (variables and functions). There are
three types in C++:
Public:
Members declared public can be accessed from anywhere in the program.
Private:
Members declared private can be accessed only within the same class.
They cannot be accessed directly outside the class.
Members declared protected can be accessed within the same class and derived (child)
classes.They are not accessible from outside the class.
#include <iostream>
using namespace std;
class Student {
public:
string name; // Public: Can be accessed anywhere
private:
int rollNo; // Private: Can be accessed only within the class
protected:
int age; // Protected: Accessible in this class and derived classes
public:
void setRollNo(int r) { // Public function to access private data
rollNo = r;
}
void showDetails() {
cout << "Name: " << name << endl;
cout << "Roll No: " << rollNo << endl;
}
};
int main() {
Student s1;
s1.name = "John"; // Allowed (public)
s1.setRollNo(101); // Accessing private data using a public method
s1.showDetails();
return 0;
}
Output: Name: John
Roll No: 101
Public: Accessible from anywhere. Private: Accessible only inside the class. Protected:
Accessible inside the class and inherited classes.
Q.Write a C++ program to implement a class called Circle that has member
variables for radius. Include member functions to calculate the circle's area and
circumference.
C++ Program: Implementing a Circle Class
#include <iostream>
using namespace std;
class Circle {
private:
double radius; // Private member variable
public:
// Constructor to initialize radius
Circle(double r) {
radius = r;
}
// Function to calculate area
double getArea() {
return 3.14159 * radius * radius;
}
// Function to calculate circumference
double getCircumference() {
return 2 * 3.14159 * radius;
}
};
int main() {
double r;
cout << "Enter the radius of the circle: ";
cin >> r;
Circle c(r); // Creating an object with user input radius
cout << "Area: " << c.getArea() << endl;
cout << "Circumference: " << c.getCircumference() << endl;
return 0;
}
Output (Example Run):
Enter the radius of the circle: 5
Area: 78.5397 Circumference: 31.4159
Explanation:
1. The class Circle contains a private variable radius.
2. It has two member functions:
o getArea() to calculate area.
o getCircumference() to calculate circumference.
In main(), the user inputs the radius, and the Circle object calculates and displays the
results. This program demonstrates encapsulation by keeping radius private and accessing it
through public methods.
Q.Write a C++ program to create a class called Person that has member
variables for name, age and country. Implement member functions to set and get
the values of these variables.
C++ Program: Implementing a Person Class
#include <iostream>
using namespace std;
class Person {
private:
string name;
int age;
string country;
public:
// Function to set values
void setDetails(string n, int a, string c) {
name = n;
age = a;
country = c;
}
// Function to display values
void getDetails() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Country: " << country << endl;
}
};
int main() {
Person p1; // Creating an object of the Person class
string name, country;
int age;
// Taking user input
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Age: ";
cin >> age;
cin.ignore(); // To clear the newline character from input buffer
cout << "Enter Country: ";
getline(cin, country);
p1.setDetails(name, age, country); // Setting values
cout << "\nPerson Details:\n";
p1.getDetails(); // Displaying values
return 0;
}
Example Output:
Enter Name: John Doe
Enter Age: 25
Enter Country: USA
Person Details:
Name: John Doe
Age: 25
Country: USA
Explanation:
1. The class Person has private variables: name, age, country.
2. The setDetails() function assigns values to these variables.
3. The getDetails() function prints the values.
The user inputs values in main(), and the Person object stores and displays them.
This program demonstrates encapsulation by keeping data private and using public methods
for access.
Q. Write a C++ program to implement a Book class with attributes title, author,
and isbn. Provide methods to set and display these attributes.
C++ Program: Implementing a Book Class
#include <iostream>
using namespace std;
class Book {
private:
string title;
string author;
string isbn;
public:
// Function to set book details
void setDetails(string t, string a, string i) {
title = t;
author = a;
isbn = i;
}
// Function to display book details
void getDetails() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "ISBN: " << isbn << endl;
}
};
int main() {
Book b1; // Creating an object of the Book class
// Setting book details
b1.setDetails("C++ Basics", "Alice", "12345");
// Displaying book details
cout << "\nBook Details:\n";
b1.getDetails();
return 0;
}
Output:
Book Details:
Title: C++ Basics
Author: Alice
ISBN: 12345
Explanation:
1. The Book class has private variables: title, author, isbn.
2. The setDetails() function assigns values to these variables.
3. The getDetails() function prints the values.
4. In main(), the program sets book details directly without user input and displays
them.
This version removes user input and uses easy names and numbers for simplicity.
b) Write a C++ program to implement a Student class with attributes name,
rollNumber, and grade. Provide a method to display the student details.
C++ Program: Implementing a Student Class
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNumber;
char grade;
public:
// Function to set student details
void setDetails(string n, int r, char g) {
name = n;
rollNumber = r;
grade = g;
}
// Function to display student details
void getDetails() {
cout << "Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Grade: " << grade << endl;
}
};
int main() {
Student s1; // Creating an object of the Student class
// Setting student details
s1.setDetails("Rahul", 101, 'A');
// Displaying student details
cout << "\nStudent Details:\n";
s1.getDetails();
return 0;
}
Output:
Student Details:
Name: Rahul
Roll Number: 101
Grade: A
Explanation:
1. The Student class has private attributes: name, rollNumber, grade.
2. The setDetails() function assigns values to these attributes.
3. The getDetails() function prints the details.
4. In main(), we directly set and display student details using simple names and
numbers for clarity.
UNIT 2
1. What is function prototyping? Write a C++ program to implement function
prototyping.
Function prototyping is the declaration of a function before its actual definition in a program.
It tells the compiler about the function name, return type, and parameters before the function
is used. This allows a function to be called before it is defined, improving code organization
and readability.
C++ example:
#include <iostream>
using namespace std;
// Function prototype
int add(int, int);
int main() {
int result = add(5, 3); // Function call before definition
cout << "Sum: " << result;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Output- Sum:8
In this program, int add(int, int); is the function prototype, which declares the function before
its definition. The function is called in main() before its actual definition, demonstrating how
prototyping helps in organizing code and ensuring function calls are recognized before they
are defined.
2. Describe call by reference with suitable example.
Call by reference is a method of passing arguments to a function where the actual memory
address of the variables is passed instead of their values. This allows the function to modify
the original variables directly.
C++ example:
#include <iostream>
using namespace std;
void swap(int &a, int &b) { // Call by reference using '&'
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
cout << "Before swapping: x = " << x << ", y = " << y << endl;
swap(x, y); // Function call by reference
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;
}
Output- Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10
In this program, the swap() function takes two arguments by reference using &. Since the
function operates on actual memory locations, swapping x and y inside the function also
changes their values in main(). This is an advantage over call by value, where changes
inside the function do not affect the original variables.
3. Explain return by reference with the help of C++ program.
Return by reference allows a function to return a reference to a variable instead of a copy of
its value. This means any changes made to the returned reference affect the original
variable. It is useful when we want to modify a variable from outside the function without
passing it explicitly.
C++ example:
#include <iostream>
using namespace std;
int& getValue(int &num) { // Function returns a reference
return num;
}
int main() {
int x = 10;
cout << "Before: x = " << x << endl;
getValue(x) = 20; // Modifies the original variable
cout << "After: x = " << x << endl;
return 0;
}
Output- Before: x = 10
After: x = 20
In this program, the function getValue() returns a reference to num. When getValue(x) = 20;
is executed, it directly modifies x in main() because the function returns a reference to x.
This technique is useful when working with large data structures, as it avoids unnecessary
copies and improves efficiency.
4. Explain inline function with the help of C++ program.
An inline function is a function that is expanded at the place where it is called
instead of executing a separate function call. This reduces function call
overhead and makes the program faster, especially for small functions. To
declare an inline function, use the inline keyword before the function definition.
C++ example:
#include <iostream>
using namespace std;
inline int square(int n) { // Inline function
return n * n;
int main() {
int num = 5;
cout << "Square of " << num << " is: " << square(num) << endl;
return 0;
Output- Square of 5 is: 25
In this program, square() is an inline function. When square(num) is called,
the function directly replaces the function call with num * num during
compilation. This eliminates the overhead of calling a separate function,
making execution faster for small functions.
5. Explain default arguments with the help of C++ program.
Default arguments allow a function to have predefined values for its parameters. If a value is
not provided during the function call, the default value is used. This helps in reducing
function overloading and provides flexibility in function calls.
C++ example:
#include <iostream>
using namespace std;
void greet(string name = "Guest") { // Default argument
cout << "Hello, " << name << "!" << endl;
}
int main() {
greet(); // Calls function without an argument (uses default value)
greet("Alice"); // Calls function with an argument (overrides default)
return 0;
}
Output: Hello, Guest!
Hello, Alice!
In this program, the greet() function has a default argument "Guest". When called without an
argument, it uses the default value. When called with "Alice", it overrides the default and
prints "Hello, Alice!". Default arguments make functions more flexible and reduce the need
for multiple overloaded functions.
6. Explain the static member with C++ example.
A static member in C++ is a class member (variable or function) that is shared among all
objects of the class. It belongs to the class itself rather than any specific object.Static
Variables: Retain their value across all objects.Static Functions: Can access only static
members of the class.
C++ example:
#include <iostream>
using namespace std;
class Student {
private:
string name;
static int count; // Static variable declaration
public:
Student(string n) {
name = n;
count++; // Increments count for each object created
}
void show() {
cout << "Name: " << name << ", Student Count: " << count << endl;
}
static void showCount() { // Static function
cout << "Total Students: " << count << endl;
}
};
int Student::count = 0; // Static variable definition
int main() {
Student s1("Alice"), s2("Bob");
s1.show();
s2.show();
Student::showCount(); // Calling static function without an object
return 0;
}
Output- Name: Alice, Student Count: 2
Name: Bob, Student Count: 2
Total Students: 2
In this program, count is a static variable shared by all Student objects. Every time an object
is created, count is incremented. The showCount() function is static, meaning it can be
called without an object (Student::showCount()). This demonstrates how static members
belong to the class rather than individual objects.
7. Explain Polymorphism with its types . Write a C++ program for any one.
Polymorphism means "many forms" and allows functions or objects to have multiple
behaviors. It helps in code reusability and flexibility.
Types of Polymorphism:
1. Compile-time Polymorphism (Static Binding)
o Achieved using Function Overloading and Operator Overloading.
o Function execution is determined at compile time.
2. Run-time Polymorphism (Dynamic Binding)
o Achieved using Function Overriding and Virtual Functions.
o Function execution is determined at runtime using pointers and inheritance.
C++ example-
#include <iostream>
using namespace std;
class Math {
public:
int add(int a, int b) { // First function
return a + b;
}
double add(double a, double b) { // Overloaded function with different parameters
return a + b;
}
};
int main() {
Math obj;
cout << "Sum (int): " << obj.add(5, 3) << endl;
cout << "Sum (double): " << obj.add(2.5, 3.5) << endl;
return 0;
}
Output- Sum (int): 8
Sum (double): 6
n this program, the add() function is overloaded, meaning the same function name is used
with different parameter types. The compiler determines which function to execute based on
the provided arguments. This is an example of Compile-time Polymorphism.
For Run-time Polymorphism, function overriding using inheritance and virtual functions is
used.
8. Explain function overloading. Write a C++ program to overload volume()
function to calculate volume of cylinder, cube and sphere.
Function overloading is a feature in C++ that allows multiple functions with the same
name but different parameters. The compiler determines which function to call based
on the number and type of arguments.
C++ example-
#include <iostream>
using namespace std;
class VolumeCalculator {
public:
// Volume of Cylinder: π * r^2 * h
double volume(double r, double h) {
return 3.14159 * r * r * h;
}
// Volume of Cube: side^3
int volume(int side) {
return side * side * side;
}
// Volume of Sphere: (4/3) * π * r^3
double volume(double r) {
return (4.0 / 3.0) * 3.14159 * r * r * r;
}
};
int main() {
VolumeCalculator v;
cout << "Volume of Cylinder (r=3, h=5): " << v.volume(3.0, 5.0) << endl;
cout << "Volume of Cube (side=4): " << v.volume(4) << endl;
cout << "Volume of Sphere (r=3): " << v.volume(3.0) << endl;
return 0;
}
Output- Volume of Cylinder (r=3, h=5): 141.371
Volume of Cube (side=4): 64
Volume of Sphere (r=3): 113.097
The volume() function is overloaded:
For a cylinder, it takes two double arguments (radius, height).For a cube, it takes one integer
argument (side).For a sphere, it takes one double argument (radius).
This program demonstrates function overloading, where the same function name is used for
different shapes based on the parameters passed.
9. Explain the virtual function and give a suitable example.
A virtual function is a member function in a base class that is overridden in a derived
class. It allows runtime polymorphism, meaning the function call is determined at
runtime instead of compile time. This is achieved using function overriding with a
base class pointer pointing to a derived class object. The virtual keyword is used to
declare a virtual function.
C++ example-
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Animal makes a sound" << endl;
};
class Dog : public Animal {
public:
void sound() override { // Overriding base class function
cout << "Dog barks" << endl;
}
};
int main() {
Animal* a; // Base class pointer
Dog d;
a = &d; // Pointer to derived class object
a->sound(); // Calls derived class function
return 0;
Output- Dog barks
In this program, the base class Animal has a virtual function sound(). The derived
class Dog overrides this function. The base class pointer a is assigned the address of
the derived class object d. Because sound() is virtual, the derived class function is
called instead of the base class function. This is an example of runtime
polymorphism, where function execution is determined during program execution.
10. What is type casting? Explain explicit and implicit type conversion with
Programming example .
Type casting is the process of converting one data type into another. This can
happen automatically (implicit conversion) or be manually forced by the
programmer (explicit conversion).Implicit type conversion happens when the
compiler automatically converts a smaller data type into a larger one to avoid
data loss.
C++ example-
#include <iostream>
using namespace std;
int main() {
int num = 10;
double result = num; // Implicit conversion from int to double
cout << "Implicit Conversion: " << result << endl;
return 0;
}
Output- Implicit Conversion: 10.000000
The integer num is automatically converted into a double to match the result variable type.
Explicit type conversion is when the programmer forces the conversion using casting
operators like (type), static_cast<type>(), etc.
C++ example-
#include <iostream>
using namespace std;
int main() {
double num = 10.75;
int result = (int) num; // Explicit conversion from double to int
cout << "Explicit Conversion: " << result << endl;
return 0;
}
Output- Explicit Conversion: 10
Here, the double num is manually converted into an integer using (int), and the decimal part
is truncated. Implicit conversion happens automatically, while explicit conversion requires
manual intervention to avoid data loss or mismatched data types.
11. Write a C++ program to swap two numbers using call by reference.
#include <iostream>
using namespace std;
void swap(int &a, int &b) { // Call by reference using '&'
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
cout << "Before swapping: x = " << x << ", y = " << y << endl;
swap(x, y); // Function call by reference
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;
}
Output- Before swapping: x = 5, y = 10
After swapping: x = 10, y = 5
The swap() function takes two integer references as parameters. Since the function
receives references, any modifications made inside the function directly affect the original
variables. This allows x and y to be swapped without returning any value.