0% found this document useful (0 votes)
7 views20 pages

Cpp October

The document contains a series of questions and answers related to C++ programming concepts, including topics such as operator overloading, constructors, inheritance, encapsulation, and file operations. It provides definitions, examples, and syntax for various programming constructs and techniques. Additionally, it includes sample code snippets to illustrate the concepts discussed.
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)
7 views20 pages

Cpp October

The document contains a series of questions and answers related to C++ programming concepts, including topics such as operator overloading, constructors, inheritance, encapsulation, and file operations. It provides definitions, examples, and syntax for various programming constructs and techniques. Additionally, it includes sample code snippets to illustrate the concepts discussed.
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/ 20

1) ________ is used to format the data display.

1) Interator iii) Manipulator ii) Punctuator iv) Allocator

Ans- iii) Manipulator

2) Operator overloading is ________.

i) Making operators work with objects.

ii) Giving new meaning to existing operators

iii) Making new operators.

iv) Giving operators more than they can handle

ans- ii) Giving new meaning to existing operators

3) An object is an instance of _________.

i) Class iii) Behaviour ii) State iv) Message

ans- i) Class

4) _______ class supports opening file in write mode

i) ofstream iii) cstream ii) ifstream iv) wstream

Ans- i) ofstream

5) State whether following statements are true or false

1) Constructor should be declared in private section

2) Constructors are invoked automatically when the objects are created.

i) True, True iii) False, True ii) True, False iv) False, False

ans- iii) False, True

B) Answer the following.

1) What is Abstract class?

ans- An abstract class is a class that cannot create objects and is used as a base class to provide
common structure for other classes.

It can have abstract methods (without body) that must be defined in child classes.

2) List the different types of constructor.

Ans- 1⃣ Default Constructor – A constructor with no parameters.


2⃣ Parameterized Constructor – A constructor that takes arguments to initialize objects.
3⃣ Copy Constructor – A constructor that creates a new object as a copy of an existing object.
4⃣ Static Constructor (in some languages) – Used to initialize static members.
5⃣ Private Constructor – A constructor declared as private, often used in Singleton patterns.
3) Write the syntax to create a class.

Ans- class class_name

// body of class

};

4) List file opening modes.


Ans- File Opening Modes in PHP:
Mode Description

"r" Open for reading only. Starts at the beginning of the file.

"r+" Open for reading and writing. Starts at the beginning.

"w" Open for writing only. Erases the file or creates a new one.

"w+" Open for reading and writing. Erases the file or creates new.

"a" Open for writing only. Writes at the end of the file.

"a+" Open for reading and writing. Starts at the end.

"x" Create and open for writing only. Fails if the file exists.

"x+" Create and open for reading and writing. Fails if the file exists.

5) Define Encapsulation.
Ans- Encapsulation is the process of hiding the internal details of a class and protecting data
by bundling it with methods that control access. Bind data and function into single unit

Q2) Answer the following. (Any Five)


a) What is Inline function? Write its syntax and advantages.
Ans- Inline Function:
An inline function is a function where the compiler replaces the function call with the
actual code of the function, which helps to reduce the overhead of a function call. It is
commonly used for small, simple functions.

Syntax:
inline return_type function_name(parameters) {
// Function body
}
Example:
#include<iostream>
using namespace std;

inline int add(int a, int b) {


return a + b;
}
Advantages of Inline Functions:
1⃣ Faster execution (reduces function call overhead).
2⃣ Saves time by avoiding jumps to function calls.
3⃣ Improves performance for small, frequently used functions.

b) Write any 3 differences between OOP (Object Oriented Programming) and POP
(Procedure Oriented Programming)

Ans- page no 1.8

c) Write a program to find area of rectangle using constructor.

Ans- #include <iostream>

using namespace std;

class Rectangle {

int length, width;

public:

// Constructor to initialize length and width

Rectangle(int l, int w) {

length = l;

width = w;

// Function to calculate area

int area() {

return length * width;

};

int main() {

// Create object and pass values

Rectangle rect(10, 5);

cout << "Area of Rectangle: " << rect.area() << endl;

return 0;

d) What is static data member? List its characteristics.


Ans- Static Data Member:
A static data member in C++ is a variable that is shared by all objects of a class. It is declared using
the keyword static inside the class.

Characteristics of Static Data Member:

1⃣ It belongs to the class and not to any specific object.


2⃣ Only one copy of the static variable exists for the entire class.
3⃣ It is initialized only once at the start of the program.
4⃣ It can be accessed using the class name or through an object.
5⃣ Its lifetime is throughout the program execution.

Example:

class Test {

static int count; // static data member

};

e) What is Exception? Which Keywords are used? Write its general syntax.

Ans- What is Exception?


An exception is an error or unexpected event that occurs during program execution, which disrupts
the normal flow of the program. Exception handling helps to manage these errors without crashing
the program.

Keywords used in Exception Handling:

• try – Block to write code that may cause an exception.

• catch – Block to handle the exception.

• throw – Used to manually throw an exception.

General Syntax:

cpp

CopyEdit

try {

// Code that may cause exception

catch (ExceptionType e) {
// Code to handle exception

Simple Example:

#include <iostream>

using namespace std;

int main() {

try {

int num = 0;

if (num == 0)

throw "Division by zero error!";

cout << 10 / num;

catch (const char* msg) {

cout << "Exception: " << msg;

return 0;

f) Write a program to display factors of a number.


Ans- #include <iostream>
using namespace std;

int main() {
int num;

cout << "Enter a number: ";


cin >> num;

cout << "Factors of " << num << " are: ";

for(int i = 1; i <= num; i++) {


if(num % i == 0) {
cout << i << " ";
}
}
return 0;
}
Q3) Answer the following (any five)

a) Define constructor. Explain constructor overloading with example.

Ans- Constructor:
A constructor is a special function in a class that is automatically called when an object of the
class is created. It is used to initialize the data members of the class.

Constructor Overloading:
Constructor overloading means having multiple constructors in the same class with the same
name but different parameters. This allows objects to be initialized in different ways.

Example of Constructor Overloading:

#include <iostream>

using namespace std;

class Rectangle {

int length, width;

public:

// Default constructor

Rectangle() {

length = 0;

width = 0;

// Parameterized constructor

Rectangle(int l, int w) {

length = l;

width = w;

void display() {

cout << "Length: " << length << ", Width: " << width << endl;
}

};

int main() {

Rectangle rect1; // Calls default constructor

Rectangle rect2(10, 5); // Calls parameterized constructor

rect1.display();

rect2.display();

return 0;

b) What is Inheritance? What ambiguity can arise in Multiple Inheritance? How it is solved?

Ans- Inheritance:
Inheritance is an OOP (Object-Oriented Programming) concept where one class (child/derived
class) can acquire properties and methods of another class (parent/base class). It helps in code
reuse and creating relationships between classes.

Ambiguity in Multiple Inheritance:


In multiple inheritance, a class inherits from two or more base classes.
Ambiguity arises when two base classes have functions with the same name, and the derived
class doesn't know which one to use.

Example of Ambiguity:

#include <iostream>

using namespace std;

class A {

public:

void display() {

cout << "Display from A" << endl;

};
class B {

public:

void display() {

cout << "Display from B" << endl;

};

class C : public A, public B {};

int main() {

C obj;

// obj.display(); // Ambiguity error: which display()?

obj.A::display(); // Solution: specify class name

obj.B::display(); // Solution: specify class name

return 0;

c) What is friend function? Explain its characteristics.

Ans- Friend Function:


A friend function in C++ is a function that is not a member of a class but is given special
permission to access the private and protected members of the class.
It is declared using the keyword friend inside the class.

Characteristics of Friend Function:

1⃣ Declared with the friend keyword inside the class.


2⃣ It can access private and protected members of the class.
3⃣ It is not called using an object (unlike member functions).
4⃣ It can be a normal function or a function from another class.
5⃣ It helps in operator overloading and when two classes need to share private data.

Simple Example:

cpp

CopyEdit
#include <iostream>

using namespace std;

class Box {

private:

int length;

public:

Box() { length = 10; }

friend void display(Box b); // Friend function

};

void display(Box b) {

cout << "Length is: " << b.length << endl; // Accessing private data

int main() {

Box obj;

display(obj);

return 0;

d) Enlist the rules of operator overloading.

Ans- Rules of Operator Overloading in C++:

1⃣ Only existing operators can be overloaded – You cannot create new operators.

2⃣ Syntax cannot be changed – The way the operator works (like number of operands) stays the
same.

3⃣ At least one operand must be a user-defined type (like a class or struct).

4⃣ Certain operators cannot be overloaded, such as:

• :: (Scope Resolution Operator)

• . (Member Access Operator)


• .* (Pointer-to-member Operator)

• sizeof

• typeid

5⃣ Friend functions or member functions can be used to overload operators.

6️⃣ Overloading does not change the operator's precedence or associativity.

7️⃣ Default arguments are not allowed in overloaded operators.

Summary:
Operator overloading allows you to redefine the behavior of operators for user-defined types
while following strict syntax and usage rules.

e) Write a program to create a class student having roll no, name and percentage. Write a
member function to accept and display details of students (use Array of objects)

Ans- #include <iostream>

using namespace std;

class Student {

int roll_no;

char name[50];

float percentage;

public:

// Function to accept student details

void accept() {

cout << "Enter Roll No: ";

cin >> roll_no;

cout << "Enter Name: ";

cin.ignore(); // To clear the input buffer

cin.getline(name, 50);

cout << "Enter Percentage: ";

cin >> percentage;

}
// Function to display student details

void display() {

cout << "Roll No: " << roll_no << endl;

cout << "Name: " << name << endl;

cout << "Percentage: " << percentage << "%" << endl;

};

int main() {

int n;

cout << "Enter number of students: ";

cin >> n;

Student s[n]; // Array of objects

cout << "\n--- Enter Student Details ---\n";

for (int i = 0; i < n; i++) {

cout << "\nStudent " << i + 1 << ":\n";

s[i].accept();

cout << "\n--- Displaying Student Details ---\n";

for (int i = 0; i < n; i++) {

cout << "\nStudent " << i + 1 << ":\n";

s[i].display();

return 0;

f) What is Manipulator? Explain syntax and use of any three.


Ans- What is Manipulator?
A manipulator in C++ is a function that is used to modify the input/output format of data while
using streams like cin and cout.
Manipulators help control the display of data, such as width, precision, alignment, etc.

Syntax:

cpp

CopyEdit

cout << manipulator_name;

Manipulators are used along with cout or cin to format data.

Uses of Any Three Common Manipulators:

Manipulator Use Example

endl Moves to a new line (like \n). cout << "Hello" << endl;

setw() Sets the width of the next output field. cout << setw(10) << "Hello";

Sets the number of digits after the cout << setprecision(3) <<
setprecision()
decimal. 3.14159;

g) What are the various file operations performed write a program to read the contents from
the text file

Ans- #include <iostream>

#include <fstream>

using namespace std;

int main() {

string line;

// Open the file in read mode

ifstream file("example.txt");

if (file.is_open()) {

cout << "Contents of the file:\n";


// Read the file line by line

while (getline(file, line)) {

cout << line << endl;

// Close the file

file.close();

} else {

cout << "Unable to open the file.";

return 0;

Q4) Answer the following: (Any five)

a) Explain virtual Base class concept with example.

Ans- Virtual Base Class Concept:


In C++, a virtual base class is used to solve the Diamond Problem that occurs in multiple
inheritance when two base classes inherit from the same grandparent class.
Without virtual base classes, the derived class would inherit duplicate copies of the
grandparent’s members.

Virtual base class ensures only one copy of the common base class is inherited, avoiding
duplication.

Diamond Problem Example:

/\

B C

\/

Here, both B and C inherit from A, and D inherits from both B and C. Without virtual, D would
have two copies of A.

Syntax:
class A {

public:

int x;

};

class B : virtual public A {

};

class C : virtual public A {

};

class D : public B, public C {

};

Complete Example:

#include <iostream>

using namespace std;

class A {

public:

int x;

void getX() {

cout << "Enter value of x: ";

cin >> x;

};

class B : virtual public A {

};

class C : virtual public A {


};

class D : public B, public C {

public:

void display() {

cout << "Value of x is: " << x << endl;

};

int main() {

D obj;

obj.getX(); // Only one copy of x is shared

obj.display();

return 0;

b) What is function overloading? Write a program to overload function volume to calculate


volume of cube and cylinder.

Ans- Function overloading means having multiple functions with the same name but different
types or numbers of parameters.

#include <iostream>

using namespace std;

// Function to calculate volume of a cube

float volume(float side) {

return side * side * side;

// Function to calculate volume of a cylinder

float volume(float radius, float height) {

return 3.14159 * radius * radius * height;

}
int main() {

float side, radius, height;

cout << "Enter side of cube: ";

cin >> side;

cout << "Volume of Cube = " << volume(side) << endl;

cout << "\nEnter radius and height of cylinder: ";

cin >> radius >> height;

cout << "Volume of Cylinder = " << volume(radius, height) << endl;

return 0;

c) Read the code and answer the questions.


classA { };
int x;
public:
void display ( )
{
cout << x << endl;
}
class B : public A
{
int y;
public:
void display ( )
{ cout << y << endl; } };
main ( )
{
B b;
........ statement 1 ........ statement 2 }
1)Which object oriented feature in illustrated
Ans- Inheritance (Class B is inheriting from Class A)

ii) Write statement 1 to execute member function display in class A.


ans- b.A::display();

iii) Write statement 2 to execute member function display in class B.


ans-b.display();
iv) In which section are data members x and y declared
ans- Both x and y are declared in the private section by default

d) Explain Basic to class type conversion with example.


Ans- Basic to Class Type Conversion:
Basic to Class type conversion means converting basic data types (like int, float, etc.) into
class type objects.
This is done using a constructor that takes a basic data type as a parameter to initialize the
class object.

Syntax:
cpp
CopyEdit
class ClassName {
int data;
public:
ClassName(int value) { // Constructor with basic type parameter
data = value;
}
void display() {
cout << "Data = " << data << endl;
}
};

Example:
cpp
CopyEdit
#include <iostream>
using namespace std;

class Number {
int n;
public:
// Constructor for basic to class type conversion
Number(int x) {
n = x;
}
void display() {
cout << "Number = " << n << endl;
}
};

int main() {
int value = 50;
Number obj = value; // Basic to class type conversion
obj.display();
return 0;
}
e) Write the rules for virtual function.
Ans- 1⃣ Declared with virtual keyword
➤ You must use the keyword virtual before the function in the base class.
2⃣ Must be a member of a class
➤ Virtual functions are only used inside classes.
3⃣ Overridden in derived classes
➤ The derived class can provide its own version of the virtual function.
4⃣ Works through pointers or references
➤ Virtual functions are usually called using base class pointers or references pointing to
derived class objects.
5⃣ Cannot be static
➤ Virtual functions cannot be declared as static.
6️⃣ Constructors cannot be virtual
➤ But destructors can and should be virtual when using inheritance.
7️⃣ Prototype must be same
➤ The function signature (name, return type, and parameters) should be the same in the
base and derived class.

f) Write the significance of the following.

i) New operator ii) Delete operator iii)Destructor iv) Friend function v) Insertion and extraction
operator

ans- i) New Operator

• The new operator is used to dynamically allocate memory for an object or variable during
runtime.

• It returns a pointer to the allocated memory.

Example:

int *ptr = new int;

ii) Delete Operator

• The delete operator is used to free the memory that was allocated using the new operator.

• This helps to avoid memory leaks.

Example:

delete ptr;

iii) Destructor
• A destructor is a special member function that is automatically called when an object is
destroyed.

• It is used to release resources like memory, files, etc.

• Syntax: ~ClassName() { }

iv) Friend Function

• A friend function can access the private and protected members of a class.

• It is not a member of the class but is given special permission using the friend keyword.

Example:

friend void show();

v) Insertion (<<) and Extraction (>>) Operators

• Insertion (<<) operator: Used with cout to output data to the console.

• Extraction (>>) operator: Used with cin to input data from the user.

Example:

cout << "Enter number: ";

cin >> num;

g) Find output and justify


i) # include < iostream.h>
class Test
{ private:
Int x;
public: void set (int x)
{ Test : : x = x;}
void print ( )
{ cout << “x = ” <<x<<endl; } };
main ( )
{
Test obj;
int x = 40;
obj. set (x);
obj. print ( ); }

ans- Output:
x = 40

2) #include <iostream>
using namespace std;
class Base1 {
public:
Base1() {
cout << "Base1 constructor is called" << endl;
}
};

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

class Derived : public Base1, public Base2 {


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

int main() {
Derived d;
return 0;
}

ans- Base1 constructor is called


Base2 constructor is called
Derived constructor is called

You might also like