C++ Question Bank Solve
C++ Question Bank Solve
Object-Oriented Procedural
Feature
Programming (OOP) Programming (POP)
Organized around
Organized around
Structure functions and
objects and classes.
procedures.
namespace myNamespace {
void print() {
std::cout << "Hello from myNamespace!" << std::endl;
}
}
int main() {
myNamespace::print(); // Calling the function from myNamespace
return 0;
}
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;
}
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;
}
int main() {
int x = 10;
int& ref = x; // Reference variable ref is an alias for x
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.
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.
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!";
}
class Box {
private:
int length;
public:
Box(int l) : length(l) {}
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.
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.
class Student {
public:
string name;
void display() {
cout << "Student Name: " << name << endl;
}
};
int main() {
Student students[3]; // Array of Student objects
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.
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 Counter {
public:
static int count; // Static data member
Counter() {
count++; // Increment count every time an object is created
}
};
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;
}
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
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.
class Counter {
private:
int count;
public:
Counter() : count(0) {} // Constructor initializing count to 0
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.
Number(int v) : value(v) {}
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;
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;
}
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.
// 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;
}
class Rectangle {
private:
int width, height;
public:
// Constructor
Rectangle(int w, int h) : width(w), height(h) {}
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.
class Box {
private:
int length;
public:
Box(int l) : length(l) {}
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;
}
};
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;
}
};
int main() {
Dog dog;
dog.display(); // Displays behavior from both base classes
return 0;
}
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;
}
};
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;
}
};
int main() {
Base* b = new Derived(); // Base class pointer pointing to derived
class
b->show(); // Calls derived class show function
delete b;
return 0;
}
class Base {
public:
Base() {
cout << "Base constructor called" << endl;
}
};
int main() {
Derived d; // Instantiates derived class, calls base constructor first
return 0;
}
class Base {
public:
virtual void display() { // Virtual function
cout << "Display from Base 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;
}
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.
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
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;
}
};
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;
class Base {
public:
virtual void display() { // Virtual function with default
implementation
cout << "Display from Base" << 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;
}