0% found this document useful (0 votes)
23 views57 pages

C++ Question Bank Solve

J

Uploaded by

raoh0605
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)
23 views57 pages

C++ Question Bank Solve

J

Uploaded by

raoh0605
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/ 57

UNIT 1

1. Define Object-Oriented Programming (OOP) and how it differs


from Procedural Programming (POP).
Object-Oriented Programming (OOP) is a programming approach that
uses "objects" to represent data and methods. An object can be
thought of as a mini-program that contains both data (like variables)
and functions (like methods) that operate on the data.
Key Differences between OOP and Procedural Programming (POP):

Object-Oriented Procedural
Feature
Programming (OOP) Programming (POP)

Organized around
Organized around
Structure functions and
objects and classes.
procedures.

Data is often global


Data is encapsulated
Data Handling and shared among
in objects.
functions.

Code reuse happens


Promotes code reuse
through functions and
Reusability via inheritance and
libraries, but less
polymorphism.
flexibility.

Code can become


Complexity Hides complexity complex as size grows
Management using abstraction. and is harder to
manage.

More flexible and Generally more rigid


Flexibility
easier to modify. once written.
2. List features of Object-Oriented Language. Explain any one.
Features of Object-Oriented Languages:
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
5. Classes and Objects
6. Message Passing
Explanation of Encapsulation:
• Encapsulation is the concept of bundling data and methods
together within a class. It restricts direct access to some of the
class’s internal components, which helps safeguard the data and
ensures that it can only be changed in controlled ways through
methods. This makes your code cleaner and reduces the chance
of unintended interference.

3. Discuss OOP Concepts in Detail.


Key OOP Concepts:
1. Classes and Objects:
o Class: A blueprint or template for creating objects (like a
blueprint for a house).
o Object: An instance created from a class (like the actual
house built from the blueprint).
2. Encapsulation:
o Groups data (attributes) and methods (functions) that
operate on the data in one unit—keeping data safe from
outside interference.
3. Abstraction:
o Hides complex reality while exposing only the necessary
parts. Think of it as using a TV remote: you don’t need to
know how the remote works internally; you only need to
press buttons to change the channels.
4. Inheritance:
o Allows one class to inherit properties and methods from
another, promoting code reuse. For example, if you have a
class Animal, you could create a class Dog that inherits
from Animal.
5. Polymorphism:
o The ability of different classes to be treated as instances of
the same class through a common interface. For example,
a function might take an Animal type object, but it can
handle Dog, Cat, or any other subclass of Animal.

4. Name the following operators and explain it: 1) << 2) >>.


1. << (Left Shift Operator):
o Shifts the bits of a number to the left by a specified number
of positions. Each left shift actually multiplies the number
by 2.
o Example: 5 << 1 (5 in binary is 0101; shifting left
gives 1010, which is 10).
2. >> (Right Shift Operator):
o Shifts the bits of a number to the right. Each right shift
divides the number by 2.
o Example: 5 >> 1 shifts 0101 right to 0010, which is 2.

5. What is a variable? Explain with their types in detail.


Variable: A variable is a named storage location in memory that can
hold a value. It allows programs to store, modify, and retrieve data.
Types of Variables:
1. Local Variables:
o Declared within a function or block. Accessible only within
that function/block.
o Example:
o def my_function():
o x = 10 # Local variable
o print(x) # Can only be accessed here
2. Global Variables:
o Declared outside any function. Can be accessed from
anywhere in the program.
o Example:
o y = 20 # Global variable
o def my_function():
o print(y) # Accessible here
3. Static Variables:
o Retain their value even after the function exits,
remembering their value between function calls.
o Example (in some languages):
o def my_function():
o static_variable = 0 # Will remain across calls
o static_variable += 1
o print(static_variable)
4. Instance Variables:
o Variables that belong to an instance of a class. Each object
has its own copy.
o Example:
o class MyClass:
o def __init__(self, value):
o self.instance_variable = value # Each instance has its
own.
5. Class Variables:
o Variables that are shared among all instances of a class.
They belong to the class rather than instances.
o Example:
o class MyClass:
o class_variable = 0 # Shared across all instances

6. Describe the Structure of a C++ Program and Explain the Use of


Namespaces with an Example.
Basic Structure of a C++ Program:
A C++ program typically consists of the following components:
1. Preprocessor Directives: These are commands that tell the
compiler to include certain libraries or enable certain features.
They start with #.
2. #include <iostream>
3. Namespace Declaration: The namespace keyword provides a
way to group identifiers and avoid name collisions. The most
commonly used namespace is std (standard).
4. using namespace std;
5. Main Function: The execution of the program starts from
the main function. It must return an integer value.
6. int main() {
7. cout << "Hello, World!";
8. return 0;
9. }
10. Function Definitions: Additional functions can be defined
outside the main function.
Example of a Simple C++ Program:
#include <iostream> // Preprocessor Directive

using namespace std; // Namespace Declaration

int main() { // Main function


cout << "Hello, World!"; // Output message
return 0; // Return statement
}
Use of Namespaces:
Namespaces prevent naming conflicts by grouping identifiers. For
instance, both the C++ Standard Library and a custom library might
have a function named print, but using namespaces allows you to
differentiate between them.
Example:
#include <iostream>

namespace myNamespace {
void print() {
std::cout << "Hello from myNamespace!" << std::endl;
}
}

int main() {
myNamespace::print(); // Calling the function from myNamespace
return 0;
}

7. List out C++ Tokens and Explain Any One.


C++ Tokens:
Tokens are the smallest element in a C++ program. They include:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators
6. Punctuation (like semicolons)
Explanation of Keywords:
Keywords are reserved words in C++ that have special meaning and
cannot be used as identifiers. They form the core of the language's
structure. Examples include int, return, if, while, class, namespace,
etc.

8. What is Operators? List All Types. Explain Any Two Operators in


Detail.
Operators: Operators are special symbols that perform operations on
variables and values. They allow us to manipulate data and variables
in various ways.
Types of Operators:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Conditional (Ternary) Operator
7. Increment and Decrement Operators
8. Member Selection Operators
9. Type Cast Operators
Explanation of Two Operators:
1. Arithmetic Operators:
o Used to perform basic mathematical operations.
o Examples: + (addition), - (subtraction), * (multiplication), /
(division), % (modulus).
Example:
int a = 5, b = 2;
int sum = a + b; // sum will be 7
2. Relational Operators:
o Used to compare two values.
o Examples: == (equal), != (not equal), > (greater
than), < (less than), >= (greater than or equal to), <= (less
than or equal to).
Example:
int a = 10, b = 20;
bool result = (a < b); // result will be true

9. Explain What a Loop Is. List All Loops. Explain Any One with an
Example.
Loop: A loop is a programming structure that repeats a block of code
multiple times, based on a specified condition.
Types of Loops:
1. For Loop
2. While Loop
3. Do-While Loop
Example of a For Loop:
The for loop is used when the number of iterations is known in
advance.
#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 5; i++) { // Looping from 0 to 4
cout << "Iteration: " << i << endl; // Outputs the current iteration
}
return 0;
}

10. Discuss Decision Making Statement in Detail with Example.


Decision-Making Statements: These statements allow a program to
make decisions and execute specific blocks of code based on
conditions. The most common decision-making statements are if, else
if, and switch.
Example of If-Else Statement:
#include <iostream>
using namespace std;

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

if (num > 0) {
cout << "Positive Number";
} else if (num < 0) {
cout << "Negative Number";
} else {
cout << "Zero";
}
return 0;
}
In this example, the program checks if the number is positive, negative,
or zero and outputs the result accordingly.
11. Discuss Branching Statement in Detail with Example.
Branching Statements: These are used to alter the flow of control in a
program, allowing it to skip certain parts or jump to specific blocks of
code. The main branching statements are break, continue, and return.
Example of Break Statement:
The break statement is used to terminate the current loop or switch
statement.
#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
cout << "Value of i: " << i << endl;
}
return 0;
}

12. Explain Reference Variable with Example.


Reference Variable: A reference variable is an alias for an existing
variable. It allows you to access and modify the original variable
without using a pointer.
Example:
#include <iostream>
using namespace std;

int main() {
int x = 10;
int& ref = x; // Reference variable ref is an alias for x

cout << "Original x: " << x << endl; // Outputs 10


ref = 20; // Modify x through ref
cout << "New x: " << x << endl; // Outputs 20
return 0;
}
In this example, ref is a reference to x. Changes made to ref will affect
the value of x.
13. Explain Scope Resolution Operator Without Using Class.
Scope Resolution Operator (::): It is used to define the scope in which
an identifier is declared. It can access global variables when there is a
local variable with the same name.
Example:
#include <iostream>
using namespace std;

int number = 5; // Global variable

int main() {
int number = 10; // Local variable

cout << "Local number: " << number << endl; // Outputs 10
cout << "Global number: " << ::number << endl; // Outputs 5
return 0;
}
In this example, the scope resolution operator is used to access the
global variable number which is shadowed by the local variable
in main.

14. Explain Memory Management Operators.


Memory management operators in C++ are used to manage dynamic
memory. The two primary operators are:
1. new: Allocates memory for a variable or an array on the heap.
Returns a pointer to the allocated memory.
2. int* p = new int; // allocates memory for an integer
3. *p = 42; // assigns value to the allocated memory
4. delete: Deallocates memory previously allocated with new.
Frees up the memory, making it available for future allocations.
5. delete p; // deallocates memory for the integer
For arrays, use new[] and delete[]:
int* arr = new int[10]; // allocates an array of 10 integers
delete[] arr; // deallocates the array

15. What Are the Limitations of Structures in 'C'?


• No Member Functions: Structures cannot have member
functions. They can only hold data.
• No Data Hiding: Members of a structure are public by default,
which means all the structure data is exposed.
• No Inheritance: Structures do not support inheritance, which
limits their ability to leverage polymorphism.
• Limited Flexibility: Structures cannot be members of other
structures (except when using pointers).

16. Describe Inline Function with Example in Detail.


Inline Function: An inline function is a function that is expanded in line
when it is called. This means the compiler replaces the function call
with the function code itself. This can improve performance by
eliminating function call overhead.
Declaration:
inline int square(int x) {
return x * x;
}
Example:
#include <iostream>
using namespace std;

inline int square(int x) {


return x * x; // A simple inline function
}

int main() {
cout << "Square of 5: " << square(5) << endl; // Calls the inline
function
return 0;
}
In this example, calling square(5) will replace the call with 5 * 5 during
compilation, making it faster.

17. Define Function and Their Types in Detail with Example.


Function: A function is a block of code designed to perform a particular
task. Functions help in code reusability and organization.
Types of Functions:
Standard Functions: Functions defined by C++ library
(like cout, cin).
User-Defined Functions: Functions created by the user to perform
specific tasks.
o Example of a User-Defined Function:
#include <iostream>
using namespace std;
void get () {
cout << "Hello, World!";
}

int main() {
greet(); // Function call
return 0;
}
1.Functions with Return Type: Functions that return a value.
o Example:
int add(int a, int b) {
return a + b; // Function returns sum
}

int main() {
cout << "Sum: " << add(2, 3) << endl; // Calls the add function
return 0;
}
2. Functions without Return Type: Functions declared with void,
which do not return a value.
o Example:
void display() {
cout << "Displaying!";
}

17. Write a C++. Program to… Using Friend Function.


Friend Function: A friend function is a function that is not a member
of a class but has access to its private and protected members.
Example:
#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box(int l) : length(l) {}

friend void printLength(Box box); // Friend function declaration


};
void printLength(Box box) { // Friend function definition
cout << "Length of box: " << box.length << endl;
}

int main() {
Box box(10);
printLength(box); // Calling friend function
return 0;
}
In this example, the printLength function has access to
the length private member of the Box class.

18. What is Default Argument? Explain with Example.


Default Argument: A default argument is a value that is automatically
assigned to a function parameter if no argument is provided during the
function call.
Example:
#include <iostream>
using namespace std;

void display(int num = 5) { // Default argument provided


cout << "Number: " << num << endl;
}
int main() {
display(); // Uses default value (5)
display(10); // Uses provided value (10)
return 0;
}

UNIT 2
1. Write a Short Note on Defining Member Functions
Defining Member Functions: Member functions are functions that
belong to a class and operate on its objects (instances). They can
access the class's data members and perform functionality related to
that class.
Syntax:
class ClassName {
public:
void memberFunction() {
// Implementation
}
};
Example:
#include <iostream>
using namespace std;

class Calculator {
public:
// Member function to add two numbers
int add(int a, int b) {
return a + b;
}
};

int main() {
Calculator calc; // Creating an object of Calculator
cout << "Sum: " << calc.add(5, 3) << endl; // Calling member function
return 0;
}
In this example, add is a member function of the Calculator class,
which performs addition.

2. Discuss Class and Object in Detail


Class: A class is a blueprint or prototype that defines the properties
(data members) and behaviors (member functions) of objects. It acts
as a template for creating objects.
Example:
class Dog {
public:
string name;
void bark() {
cout << "Woof! Woof!" << endl;
}
};
Object: An object is an instance of a class that holds specific values for
the class’s attributes and can call its methods. Each object can have
unique properties.
Example:
Dog dog1; // Creating an object of Dog
dog1.name = "Buddy"; // Assigning a value to the attribute
dog1.bark(); // Calling a method of the object

3. Explain How a Class Can Handle Arrays of Objects with Example


A class can contain arrays of objects, allowing it to manage multiple
instances of another class.
Example:
#include <iostream>
using namespace std;

class Student {
public:
string name;
void display() {
cout << "Student Name: " << name << endl;
}
};

int main() {
Student students[3]; // Array of Student objects

// Assign names to each student


students[0].name = "Alice";
students[1].name = "Bob";
students[2].name = "Charlie";

// Display student names


for (int i = 0; i < 3; i++) {
students[i].display();
}

return 0;
}
In this example, we create an array of Student objects and assign
names to each object, demonstrating how a class can handle arrays of
objects.

4. Differentiate Between Public, Private, and Protected Access


Specifiers in C++ with Examples
Access Specifiers control the visibility of class members (data and
functions):
1. Public:
o Members are accessible from outside the class.
o
o Example:
class Sample {
public:
int x; // Public member
};

2. Private:
o Members are accessible only within the class itself.
o Example:
class Sample {
private:
int y; // Private member
public:
void setY(int value) {
y = value; // Accessible within class
}
};

3. Protected:
o Members are accessible within the class and by derived
classes, but not from outside.
o Example:
class Base {
protected:
int z; // Protected member
};

class Derived : public Base {


public:
void accessZ() {
z = 10; // Accessible in derived class
}
};

5. Explain Static Data and Static Method in Details


Static Data Members: Static data members are shared among all
instances of a class. They are not tied to a specific object and can be
accessed using the class name.
• Example:
#include <iostream>
using namespace std;

class Counter {
public:
static int count; // Static data member

Counter() {
count++; // Increment count every time an object is created
}
};

// Definition of static member


int Counter::count = 0;

int main() {
Counter c1, c2; // Two instances created
cout << "Count: " << Counter::count << endl; // Outputs 2
return 0;
}
Static Methods: Static methods belong to the class rather than any
object instance. They can only access static data members or other
static methods.
• Example:
class Math {
public:
static int add(int a, int b) {
return a + b; // Static method
}
};

int main() {
cout << "Sum: " << Math::add(5, 10) << endl; // Call static method
using class name
return 0;
}

6. Explain the Concept of Constructors in C++ with Program Example


Constructors are special member functions that are automatically
called when an object of a class is created. They are used to initialize
objects.
Types of Constructors:
1. Default Constructor: No parameters.
2. Parameterized Constructor: One or more parameters.
Example:
#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
// Default constructor
Box() {
length = 0;
}
// Parameterized constructor
Box(int l) {
length = l;
}

void display() {
cout << "Length: " << length << endl;
}
};

int main() {
Box box1; // Calls default constructor
Box box2(10); // Calls parameterized constructor

box1.display(); // Output: Length: 0


box2.display(); // Output: Length: 10

return 0;
}
In this example, the Box class has both a default constructor and a
parameterized constructor. The appropriate constructor is
automatically called based on how we create the object.

7. Create a Program of Unary Operator Overloading and Explain the


Concept of Operator Overloading
Operator Overloading allows C++ operators to be used with user-
defined types (classes). Unary operators operate on a single operand.
Example - Unary Operator Overloading:
#include <iostream>
using namespace std;

class Counter {
private:
int count;

public:
Counter() : count(0) {} // Constructor initializing count to 0

// Overloading the unary ++ operator


Counter operator++() {
count++; // Increment count
return *this; // Return the object
}

void display() {
cout << "Count: " << count << endl;
}
};
int main() {
Counter c;
++c; // Calls overloaded ++ operator
c.display(); // Output: Count: 1

return 0;
}
In this example, the Counter class overloads the ++ operator to
increment the count member variable.

8. Discuss Unary and Binary Operator Overloading with Example


Unary Operator Overloading: Operators that operate on a single
operand.
Example of Unary Operator Overloading:
class Number {
public:
int value;

Number(int v) : value(v) {}

// Overloading unary - operator


Number operator-() {
return Number(-value);
}
};

int main() {
Number num(10);
Number negNum = -num; // Calls overloaded unary - operator
cout << "Negative Value: " << negNum.value << endl; // Output: -10
return 0;
}
Binary Operator Overloading: Operators that operate on two
operands.
Example of Binary Operator Overloading:
class Point {
public:
int x, y;

Point(int xCoord, int yCoord) : x(xCoord), y(yCoord) {}

// Overloading binary + operator


Point operator+(const Point& p) {
return Point(x + p.x, y + p.y);
}
};

int main() {
Point p1(1, 2);
Point p2(3, 4);
Point p3 = p1 + p2; // Calls overloaded binary + operator

cout << "Point p3: (" << p3.x << ", " << p3.y << ")" << endl; // Output:
(4, 6)
return 0;
}

9. What is an Array? Explain Their Types with Example in Detail


Array: An array is a collection of items stored at contiguous memory
locations. It can hold multiple values of the same data type.
Types of Arrays:
1. Single-Dimensional Array: A linear array that stores elements in
a single row.
Example:
int arr[5] = {1, 2, 3, 4, 5}; // Single-dimensional array
2. Multi-Dimensional Array: An array that can store data in more
than one dimension. Typically used for matrices.
Example:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // Two-dimensional array
3. Dynamic Array: An array whose size can be defined at runtime.
Example:
int* dynamicArray = new int[5]; // Dynamic array
// Don't forget to delete it later
delete[] dynamicArray; // Clean up

10. Discuss String in Detail with Example


String: A string is a sequence of characters. In C++, strings can be
managed using the C-style string (character arrays) or the C++
Standard Library string class.
C-style String:
#include <iostream>
using namespace std;

int main() {
char str[] = "Hello, World!"; // C-style string
cout << str << endl; // Output: Hello, World!
return 0;
}
C++ String:
#include <iostream>
#include <string> // Include string library
using namespace std;

int main() {
string str = "Hello, C++!"; // C++ string
cout << str.length() << endl; // Output: 13
cout << str[0] << endl; // Output: H
return 0;
}
C++ strings provide various member functions such
as .length(), .append(), .find(), etc., for more manageable string
manipulation.

11. Discuss Type Conversion in Detail with Example


Type Conversion: Type conversion refers to converting one data type
into another. In C++, this can be done implicitly or explicitly.
1. Implicit Conversion: Automatically done by the compiler.
Example:
int num = 10;
double d = num; // Implicit conversion from int to double
2. Explicit Conversion (Casting): The programmer does it manually
using a cast operator.
Example:
double d = 10.5;
int num = (int)d; // Explicit conversion from double to int
Class to Class Conversion: Objects of one class can be converted to
another class if a conversion constructor is defined.
Example of Class to Class Conversion:
class Distance {
public:
int meters;
Distance(int m) : meters(m) {} // Constructor

// Conversion operator
operator int() {
return meters; // Convert to int
}
};

int main() {
Distance d(5);
int dist = d; // Implicitly calls conversion operator
cout << "Distance in meters: " << dist << endl; // Output: 5
return 0;
}

12. Construct a Simple Class with Private Members and Demonstrate


How to Access These Members Using Public Member Functions
#include <iostream>
using namespace std;

class Rectangle {
private:
int width, height;
public:
// Constructor
Rectangle(int w, int h) : width(w), height(h) {}

// Public member function to calculate area


int area() {
return width * height;
}

// Public member function to display dimensions


void display() {
cout << "Width: " << width << ", Height: " << height << endl;
}
};

int main() {
Rectangle rect(10, 5); // Create an object
rect.display(); // Accesses private members
cout << "Area: " << rect.area() << endl; // Output: Area: 50

return 0;
}
In this example, the Rectangle class has private members for width
and height. These members are accessed and manipulated through
public member functions.

13. Write a Program to Friend Function Using Operator Overloading


Friend Functions are functions that can access the private and
protected members of a class even though they are not member
functions.
Example of Friend Function Overloading:
#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box(int l) : length(l) {}

// Friend functions to overload the << operator


friend ostream& operator<<(ostream& os, const Box& box) {
os << "Length: " << box.length;
return os; // Return the output stream for chaining
}
};
int main() {
Box box(10);
cout << box << endl; // Calls the overloaded << operator

return 0;
}

UNIT 3
1. Discuss Inheritance in C++:
Inheritance is a fundamental concept in object-oriented programming
that allows a class (derived class) to inherit properties and behaviors
(data members and member functions) from another class (base
class). This promotes code reusability and establishes a relationship
between classes.
Types of Inheritance
1. Single Inheritance: A derived class inherits from a single base
class.
2. Multiple Inheritance: A derived class inherits from more than
one base class.
3. Multilevel Inheritance: A derived class inherits from a base class
which itself is derived from another base class.
4. Hierarchical Inheritance: Multiple derived classes inherit from a
single base class.
5. Hybrid Inheritance: A combination of two or more types of
inheritance.
Examples
Single Inheritance Example:
#include <iostream>
using namespace std;

class Animal {
public:
void sound() {
cout << "Animal makes sound" << endl;
}
};

class Dog : public Animal {


public:
void bark() {
cout << "Dog barks" << endl;
}
};

int main() {
Dog dog;
dog.sound(); // Inherited from Animal
dog.bark(); // Own method
return 0;
}
Multiple Inheritance Example:
#include <iostream>
using namespace std;

class Canine {
public:
void bark() {
cout << "Barks like a Canine" << endl;
}
};

class Pet {
public:
void play() {
cout << "Pet plays" << endl;
}
};

class Dog : public Canine, public Pet {


public:
void display() {
bark(); // from Canine
play(); // from Pet
}
};

int main() {
Dog dog;
dog.display(); // Displays behavior from both base classes
return 0;
}

2. Describe a Virtual Base Class with Example


A virtual base class is used to solve the diamond problem in C++,
which occurs with multiple inheritance. It ensures that only one
instance of a base class is inherited, preventing ambiguity.
Example:
#include <iostream>
using namespace std;

class A {
public:
void show() {
cout << "Class A" << endl;
}
};
// A is a virtual base class for both B and C
class B : virtual public A {
public:
void display() {
cout << "Class B" << endl;
}
};

class C : virtual public A {


public:
void display() {
cout << "Class C" << endl;
}
};

// D inherits from both B and C


class D : public B, public C {
};

int main() {
D d;
d.show(); // Calls show from Class A, avoiding ambiguity
return 0;
}
3. Define the Concept of Polymorphism in C++
Polymorphism enables methods to do different things based on the
object that it is acting upon, allowing a unified interface to different
underlying forms. It can be implemented through function
overloading, operator overloading, and most significantly, through
virtual functions.
Implementation Using Virtual Functions:
A virtual function is a member function in a base class that you
expect to override in derived classes. When you use a base class
pointer/reference to point to a derived class object, the right
function is called according to the object's type, not the
pointer/reference's type.
Example:
#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base class show function" << endl;
}
};

class Derived : public Base {


public:
void show() override { // Override base class function
cout << "Derived class show function" << endl;
}
};

int main() {
Base* b = new Derived(); // Base class pointer pointing to derived
class
b->show(); // Calls derived class show function
delete b;
return 0;
}

4. Write a Program Using Constructor in Derived Class


When a derived class is instantiated, its constructor is called after the
base class constructor.
Example:
#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base constructor called" << endl;
}
};

class Derived : private Base {


public:
Derived() {
cout << "Derived constructor called" << endl;
}
};

int main() {
Derived d; // Instantiates derived class, calls base constructor first
return 0;
}

5. Explain the Concept of Method Overriding and Overloading with


Example
Method Overriding: This occurs when a derived class has a definition
for a member function that is already defined in its base class. It allows
the derived class to provide a specific implementation for the function.
Example of Overriding:
#include <iostream>
using namespace std;

class Base {
public:
virtual void display() { // Virtual function
cout << "Display from Base class" << endl;
}
};

class Derived : public Base {


public:
void display() override { // Overrides base class function
cout << "Display from Derived class" << endl;
}
};

int main() {
Base* b = new Derived();
b->display(); // Calls Derived's display method
delete b;
return 0;
}
Method Overloading: This occurs when two or more functions in the
same scope have the same name but different parameters (type or
number).
Example of Overloading:
#include <iostream>
using namespace std;
class Math {
public:
int add(int a, int b) {
return a + b; // Adds two integers
}
double add(double a, double b) {
return a + b; // Adds two doubles
}
};

int main() {
Math m;
cout << "Integer addition: " << m.add(5, 3) << endl; // Calls int
version
cout << "Double addition: " << m.add(5.4, 3.2) << endl; // Calls
double version
return 0;
}

6. Write a Program to Explain the this Pointer


The this pointer is an implicit pointer available inside non-static
member functions. It points to the object for which the member
function is called. It allows access to the calling object's members and
is especially useful in scenarios like returning the calling object from a
method or distinguishing between instance variables and parameters.
Example:
#include <iostream>
using namespace std;

class Example {
private:
int value;

public:
Example(int value) {
this->value = value; // Using 'this' to distinguish between
parameter and member variable
}

void printValue() {
cout << "Value: " << this->value << endl; // Accessing the member
variable
}
};

int main() {
Example obj(10);
obj.printValue(); // Output: Value: 10
return 0;
}
In this program, this->value distinguishes between the member
variable value and the constructor parameter.

7. Discuss Pointer and Object in Detail


A pointer is a variable that stores the memory address of another
variable, which can be a simple variable or an object. Pointers to
objects allow dynamic memory allocation and can be used to call
member functions in a flexible manner.
Object Pointer:
When you create an object of a class, you can use a pointer to point to
that object. This allows you to manage the object's identity and access
its properties/methods.
Example:
#include <iostream>
using namespace std;

class MyClass {
public:
void display() {
cout << "Displaying MyClass object" << endl;
}
};
int main() {
MyClass obj; // Create an object
MyClass* ptr = &obj; // Create a pointer to the object

ptr->display(); // Access the display method using the pointer


return 0;
}
In this code, ptr is a pointer pointing to the object obj of class MyClass,
allowing access to its display() function.

8. Describe Virtual Function in Detail


A virtual function is a member function in a base class that you expect
to override in derived classes. It enables dynamic (or run-time)
polymorphism. When you call a virtual function through a base class
pointer or reference, the actual function that gets executed is
determined by the type of the object being pointed to, rather than the
type of the pointer/reference.
Key Features:
• Declared using the virtual keyword in the base class.
• Derived classes can override virtual functions to provide specific
implementations.
• Virtual functions enable polymorphism and are essential for
using base class pointers to invoke derived class methods.
Example:
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() { // Virtual function
cout << "Base class show function" << endl;
}
};

class Derived : public Base {


public:
void show() override { // Overriding base class function
cout << "Derived class show function" << endl;
}
};

int main() {
Base* b; // Base class pointer
Derived d; // Derived class object
b = &d; // Pointing to derived class object
b->show(); // Calls Derived's show method
return 0;
}
9. Construct a Program of Virtual Base Class. What Is the Need of
Virtual Base Class?
A virtual base class is used primarily in multiple inheritance scenarios
to prevent the ambiguity and redundancy of base class subobjects.
Example:
#include <iostream>
using namespace std;

class A {
public:
void show() {
cout << "Class A" << endl;
}
};

// A is declared as a virtual base class


class B : virtual public A {
public:
void display() {
cout << "Class B" << endl;
}
};

class C : virtual public A {


public:
void display() {
cout << "Class C" << endl;
}
};

class D : public B, public C {


};

int main() {
D d;
d.show(); // No ambiguity: "Class A"
return 0;
}
Need for Virtual Base Class
• Avoids Redundant Instances: When a derived class inherits from
multiple base classes that share a common base class, using a
virtual base class ensures that only one instance of the common
base class exists.
• Solves Diamond Problem: It eliminates the ambiguity when
calling methods or accessing members of the base class.
10. Discuss Manipulators in Detail
Manipulators are used in C++ for formatting the output of streams.
They are functions which can be used to alter the formatting state of
the output stream. Common manipulators include:
• std::endl: Inserts a new line and flushes the stream.
• std::setw(int n): Sets the width of the next input/output field.
• std::setprecision(int n): Sets decimal precision for floating-point
outputs.
• std::fixed: Forces floating-point numbers to be displayed in fixed-
point notation.
• std::scientific: Forces floating-point numbers to be displayed in
scientific notation.
Example:
#include <iostream>
#include <iomanip> // Required for manipulators
using namespace std;

int main() {
double num = 123.456789;

cout << "Default: " << num << endl;

cout << fixed << setprecision(2); // Fixed format with 2 decimal


points
cout << "Fixed: " << num << endl;
cout << setw(10) << num << endl; // Set width for output
return 0;
}

11. Differentiate Virtual Function and Pure Virtual Function


• Virtual Function:
o Can provide a default implementation in the base class.
o Invoked when a derived class does not override.
o Declared using the virtual keyword.
• Pure Virtual Function:
o Does not provide any implementation in the base class.
o Must be overridden in derived classes.
o Declared by assigning 0 in its declaration, e.g., virtual void
myFunc() = 0;.
Example:
#include <iostream>
using namespace std;

class Base {
public:
virtual void display() { // Virtual function with default
implementation
cout << "Display from Base" << endl;
}

virtual void pureVirtualFunc() = 0; // Pure virtual function


};

class Derived : public Base {


public:
void display() override { // Overriding
cout << "Display from Derived" << endl;
}

void pureVirtualFunc() override { // Must override


cout << "Implemented pure virtual function" << endl;
}
};

int main() {
Derived d;
d.display(); // Calls Derived's display
d.pureVirtualFunc(); // Calls implemented pure virtual function
return 0;
}
12. What Is the Difference Between Unformatted and Formatted I/O?
• Formatted I/O:
o It involves reading or writing data in a specific format.
o Provides options to control width, alignment, precision,
etc.
o Uses manipulators to format data.
o Example: cout << setw(10) << num; formats the output to
10 width.
• Unformatted I/O:
o Involves reading or writing data without any special
formatting.
o Directly writes bytes to the output without conversion.
o Typically faster than formatted I/O.
o Example: cout.write(buffer, size); writes raw byte data.
Example:
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
double value = 123.456;

// Formatted I/O
cout << "Formatted output:" << endl;
cout << setw(10) << fixed << setprecision(2) << value << endl;
// Unformatted I/O
cout << "Unformatted output:" << endl;
cout.write(reinterpret_cast<const char*>(&value), sizeof(value));
cout << endl;

return 0;
}

You might also like