0% found this document useful (0 votes)
10 views32 pages

CPP Complete For Exam

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)
10 views32 pages

CPP Complete For Exam

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/ 32

1) what is Encapsulation?

• Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden
data can be restricted to the members of that class.
• Levels are Public, Protected, Private, Internal, and Protected Internal.
2) Define the following?
- Early Binding - late binding.
• Early Binding:- is when the function call is linked with its corresponding function definition at
compile time..
• late Binding :- on the other hand, occurs at runtime
3) What us inline Function?
• An inline function is a technique used by the compilers and instructs to insert complete body of
the function wherever that function is used in the program source code.
4) Explain Get() and Put() Function?
• Get :- The get() function reads a single character from the associated streams and puts the
value in ch.
• Puts :- The put() function Write ch to the stream and return a reference to the value.
5) What is stream ?
• A stream is a sequence of characters that can be read from or written to. It provides a
convenient way to handle input and output operations in a standardized manner.
• Streams can be associated with various devices such as the keyboard, files, or even other
programs.
6) Define Friends Function?
• A friend function is a friend of a class that is allowed to access to Public, private, or
protected data in that same class.
• If the function is defined outside the class cannot access such information.
• A friend can be declared anywhere in the class declaration, and it cannot be affected by
access control keywords like private, public, or protected.
7) Explain the use of new Operator state the syntex.?
• The `new` operator is used to dynamically allocate memory for objects at runtime.
• SYNTAX is `new dataType;` or `new dataType[size];` for arrays.
8)State the need of virtual keywords?
• The `virtual` keyword is used to enable dynamic polymorphism, allowing derived classes to
override base class functions.
• This is essential when working with inheritance hierarchies and wanting to invoke the
appropriate function based on the actual object type at runtime.
9)State user define data types in c++?
• User-defined data types are created using structures, classes, and enumerations.
• These allow programmers to define their own custom data types that can hold multiple values
and have specific behaviors and properties.
10) Explain the use of Scope Resolution Operators?
• The scope resolution operator (::) in C++ helps us access entities in different scopes or
namespaces.
11) What is extraction and insertion operator?
• Extraction operator (>>) is used for input operations, like reading values from an input stream.
• Insertion operator (<<) is used for output operations, like displaying values to an output
stream.
12) Explain any two Manipulators?
• 'setw` is used to set the width of the output field
• `setprecision` is controls the precision of floating-point values. They help format output.
13) Define constructor?
• A constructor is a method used to initialize the state of an object, and it gets invoked at the
time of object creation.
—---Rules for constructor are:
• Constructor Name should be the same as a class name.
• A constructor must have no return type.
14) What is Reference Variable?
• A reference variable is an alias or alternative name for an existing variable.
• Its major use is to provide a way to access and modify the same memory location as the
original variable.
15) What is abstraction?
• Abstraction is a useful feature of OOPS, and it shows only the necessary details to the client of
an object. Meaning, it shows only required details for an object, not the inner constructors, of an
object.
• Example:- When you want to switch on the television, it is not necessary to know the inner
circuitry/mechanism needed to switch on the TV. Whatever is required to switch on TV will be
shown by using an abstract class.
16) What is compile Time polymorphism?
• Is when different operations are performed based on the object's type at compile-time.
• It's achieved through function and operator overloading.
17) What is Default Argument?
• Is a value assigned to a function parameter that is used when no argument is provided by the
caller.
• It allows functions to be called with fewer arguments, providing convenience and flexibility in
function usage.
18) What is Access Specifies used in c++?
• Control the visibility of class members. They are `public`, `private`, and `protected`.
19) What is return by reference?
• Return by reference in C++ allows a function to return a reference to a variable instead of
creating a copy.
• This can be useful when you want to modify the original variable directly from the calling
function.
• It can help save memory and improve performance in certain situations.
20) Define Class Template or Function Template?
• Class Template:- A class template in C++ allows you to create a generic class that can work
with different data types.
• Function Template :- A function template in C++ allows you to create a generic function that
can work with different data types
21) Explain Structure of C++ Program?
• A C++ program has preprocessor directives, libraries, main function, declarations, definitions,
statements, and a return statement.
22) What is This pointer?
• This pointer refers to the current object of a class. This keyword is used as a pointer which
differentiates between the current object with the global object. It refers to the current object.
23) Define Destructor?
• A destructor is a method which is automatically called when the object is made of scope or
destroyed.
• Destructor name is also same as class name but with the tilde symbol before the name.
• The class preceded by a tilde (~) simbols
24) Define Pure Virtual Function?
• A pure virtual function is a function which can be overridden in the derived class but cannot be
defined.
• A virtual function can be declared as Pure by using the operator =0.
• Example: -
Virtual void function2()=0 ; //Pure virtual.
25)Explain Break Continue Statement?
• `break` statement: Exits a loop or switch statement prematurely.
• `continue` statement: Skips the remaining statements within a loop iteration and moves to
the next iteration.
26) What is Static data members?
• A static data member is a member of a class that is shared by all instances of that class. It is
associated with the class itself rather than with individual objects.
• SYNTAX:-
static data_ type Veritable_name;
28) What is Setf() function?
• Is used to set specific formatting flags for the output stream.
• It allows you to control the formatting of the output by enabling or disabling various flags such
as setting the precision, width, or alignment of the output. It provides flexibility.
29) Define Dynamic Binding Message passing?
• Dynamic binding:- is refers to determining which function to call at runtime based on the
actual type of the object, allowing for polymorphism.
• Message passing :- is a way for objects to communicate with each other by sending
messages or calling member functions, enabling flexible and modular collaboration.
30) Explain Const Argument?
• `const` argument: Parameter that cannot be modified within a function. Ensures
immutability.Parameter that can't be changed in a function. Keeps things constant.
31) What is OOPS?
• OOPS is abbreviated as Object Oriented Programming system in which programs are
considered as a collection of objects. Each object is nothing but an instance of a class.
32) What is a class?
• A class is simply a representation of a type of object.
• It is the blueprint/plan/template that describes the details of an object.
33) What is an Object?
• An object is an instance of a class. It has its own state, behavior, and identity.
34) What is Polymorphism?
• Polymorphism is nothing but assigning behavior or value in a subclass to something that was
already declared in the main class. Simply, polymorphism takes more than one form.
35) What is Inheritance?
• Inheritance is a concept where one class shares the structure and behavior defined in another
class. If Inheritance applied to one class is called Single Inheritance, and if it depends on
multiple classes, then it is called multiple Inheritance.
36) What are manipulators?
• Manipulators are the functions which can be used in conjunction with the insertion (<<) and
extraction (>>) operators on an object. Examples are endl and setw.

37) What is a virtual function?


• A virtual function is a member function of a class, and its functionality can be overridden in its
derived class.
• This function can be implemented by using a keyword called virtual, and it can be given during
function declaration.
• A virtual function can be declared using a token(virtual) in C++.
• It can be achieved in C/Python Language by using function pointers or pointers to function.
38)List different types of constructor. Explain any one constructor with example.?
--Different types of constructors--
• Default Constructor :-Constructor with no parameters.
• Parameterized Constructor :- Constructor with parameters.
• Copy Constructor :- Constructor that initializes an object using another object of the same
class.
• Ex:- of a Parameterized Constructor :-
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int width;
public:
Rectangle(int l, int w) {
length = l;
width = w;
}
void displayArea() {
cout << "Area: " << length * width << endl;
}
};
int main() {
Rectangle rect(5, 4);
rect.displayArea(); // Output: Area: 20
return 0;
}
39) What is function overloading? Explain with suitable example.?
• ---Function Overloading---
• Function overloading is a feature in C++ that allows creating multiple functions with the same
name but with different parameter lists or types. The compiler selects the appropriate function to
call based on the number and types of arguments passed to it.
• Example:-
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
int main() {
cout << "Sum of integers: " << add(5, 3) << endl;
cout << "Sum of floats: " << add(2.5f, 3.7f) << endl; // Output: Sum of floats: 6.2
return 0;
)}
40)Describe different types of inheritance.?
• ---Different types of inheritance---
• Single Inheritance :- A derived class inherits from only one base class.
• Multiple Inheritance :- A derived class inherits from multiple base classes.
• Multilevel Inheritance :- A derived class inherits from another derived class.
• Hierarchical Inheritance :- Multiple derived classes inherit from a single base class.
• Hybrid Inheritance :- Combination of two or more types of inheritance.
41) Explain virtual base class with suitable diagram.?
• A virtual base class is used to resolve the ambiguity that arises when a derived class inherits
from multiple base classes, and those base classes have a common base class. It ensures that
only one instance of the common base class is inherited by the derived class.
• Example :-
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "Animal is eating" << endl;
}
};
class Dog : virtual public Animal {
public:
void bark() {
cout << "Dog is barking" << endl;
}
};
class Cat : virtual public Animal {
public:
void meow() {
cout << "Cat is meowing" << endl;
}
};
class DogCat : public Dog, public Cat {
public:
void action() {
eat();
bark();
meow();
}
};
int main() {
DogCat dc;
dc.action(); // Output: Animal is eating, Dog is barking, Cat is meowing
return 0;
}
42) Describe file manipulators with their syntaxes.?
• File manipulators in C++ are used to control the formatting of input and output operations on
files. They are used with the `fstream` classes for file handling.
• SYNTAX:-
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile("example.txt");
outfile << "Name: John" << endl;
outfile << "Age: 30" << endl;
outfile << "Location: New York" << endl;
outfile.close();
return 0;
}
43) Explain memory management operators with the help of suitable example.?
• Memory management operators are used to dynamically allocate and deallocate memory
during program execution.
• `new` operator :- Allocates memory for a single object or an array of objects from the heap.
• `delete` operator :- Deallocates memory allocated by the `new` operator.
• Example :-
#include <iostream>
using namespace std;
int main() {
int *ptr = new int;
*ptr = 10;
cout << "Value stored at dynamically allocated memory: " << *ptr << endl;
delete ptr;
return 0;
}
44) Explain memory allocation for objects with non-static data momber and static data
member.?
• Non-static Data Member :- Memory for non-static data members of an object is allocated
when an object of that class is created. Each object has its own copy of non-static data
members.
• Static Data Member :- Memory for static data members is allocated once for the entire class
and shared among all objects of that class.
• Example :-
#include <iostream>
using namespace std;
class MyClass {
public:
int x; // Non-static data member
static int y; // Static data member
};
int MyClass::y = 0; // Initializing static data member
int main() {
MyClass obj1, obj2;
obj1.x = 5;
obj2.x = 10;
cout<< "obj1.x: "<< obj1.x << endl; //Output: 5
cout m<<"obj2.x: "<< obj2.x << endl; //Output 10
MyClass::y = 15; // Accessing static data member
cout << "MyClass::y: " << MyClass::y << endl; // Output: 15
return 0;
}
45) When do we make a class virtual base class? Explain it with suitable example.?
• A class is made a virtual base class when it is intended to be inherited by multiple derived
classes, and we want to avoid ambiguity caused by multiple inheritance.
• Example:-
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "Animal is eating" << endl;
}
};
class Dog : virtual public Animal {
public:
void bark() {
cout << "Dog is barking" << endl;
}
};
class Cat : virtual public Animal {
public:
void meow() {
cout << "Cat is meowing" << endl;
}
};
class DogCat : public Dog, public Cat {
public:
void action() {
eat(); // Ambiguity resolved by virtual base class
bark();
meow();
}
};
int main() {
DogCat dc;
dc.action(); // Output: Animal is eating, Dog is barking, Cat is meowing
return 0;
}
46)Explain array of object in C++ with example.?
• Arrays of objects allow us to create multiple objects of a class and store them in a contiguous
block of memory.
• Example :-
#include <iostream>
using namespace std;
class Employee {
private:
int id;
string name;
public:
Employee(int i, string n) : id(i), name(n) {}
void display() {
cout << "ID: " << id << ", Name: " << name << endl;
}
};
int main() {
const int size = 3;
Employee empArr[size] = { Employee(101, "John"), Employee(102, "Alice"), Employee(103,
"Bob") };
for (int i = 0; i < size; ++i) {
empArr[i].display();
}
return 0;
}
47) Explain any four formatted input/output functions.?
• `setw(int n)`:- Sets the width of the next input/output field to n characters.
• `setprecision(int n)`:- Sets the number of digits to be displayed after the decimal point for
floating-point numbers.
• `setfill(char c)`:- Sets the fill character used to pad the output to the specified character c.
• `setw(int n)`:- Sets the width of the next input/output field to n characters.
• These functions are part of the `<iomanip>` header.
48) Explain try, catch and throw in exception handling.?
• Try :- The try block identifies a block of code in which exceptions can occur. It is followed by
one or more catch blocks. If an exception occurs within the try block,
• it is thrown (using the throw keyword) and the execution moves to the corresponding catch
block. If no exception is thrown, the catch block is skipped.
• Catch :- The catch block handles exceptions thrown by the try block. It specifies a parameter
(usually of type `std::exception` or derived classes) that can receive the exception object.
• The catch block can have multiple catch handlers for different types of exceptions.
• Throw :- The throw statement generates an exception. It can throw any type of object, which
can be caught by a catch block that matches the type or a base class of the thrown object.
• The throw statement interrupts the normal flow of the program and jumps to the closest
matching catch block.
49) What is Destructor? State the importance of destructor with example.?
• A destructor is a member function of a class that is used to clean up resources that were
allocated by an object during its lifetime.
• It is automatically called when the object goes out of scope or is explicitly deleted.
• The importance of a destructor lies in releasing resources,
• such as memory, file handles, network connections, etc.,
• That were allocated by the object during its lifetime. Failing to release these resources can
lead to memory leaks, resource leaks, or other problems.
• Example :-
#include <iostream>
class Resource {
public:
Resource() {
std::cout << "Resource allocated!" << std::endl;
}
~Resource() {
std::cout << "Resource released!" << std::endl;
}
};
int main() {
{
Resource r;
}
return 0;
}
50)What is tokens in C++? Explain in detail.?
• Tokens are the smallest units of a program.
• Keywords :- Reserved words with a predefined meaning in the C++ language. • Examples :-
include `int`, `return`, `class`, `if`, `else`, etc.
• Identifiers :- Names given to entities in a program,
• Example :- variables, functions, classes, etc.
• They must start with a letter (uppercase or lowercase) or an underscore and can be followed
by letters, digits, or underscores.
• Examples: `var1`, `_var2`,`ClassName`
• Constants:- Fixed values in a program that cannot be changed during program execution.
• Constants can be numeric constants (e.g., `5`, `3.14`), character constants (e.g., `'A'`, `'\n'`),
string literals
(e.g., `"Hello"`), or user-defined constants (e.g., `#define PI 3.14159`).
• Strings :- A sequence of characters enclosed in double quotes (`"`).
• Example: `"Hello World"`.
• Operators :- Symbols that represent operations, arithmetic operators
(`+`, `-`, `*`, `/`),
• relational operators (`<`, `>`, `==`, `!=`),
• logical operators (`&&`, `||`, `!`),
• assignment operators (`=`, `+=`, `-=`),etc.
51) Can we pass class object as function arguments? Explain with the help of an
example.?
• #include <iostream>
using namespace std;
class MyClass {
private:
int num;
public:
MyClass(int n) : num(n) {}
void display() {
cout << "Number: " << num << endl;
}
};
void displayObject(MyClass obj) {
obj.display();
}
int main() {
MyClass obj(10);
displayObject(obj);
return 0;
}
52)Explain various stream classes used to perform console input/output (I/o)operations.
• `cin`:- Standard input stream used for console input.
• `cout`:- Standard output stream used for console output.
• `cerr`:- Standard error stream used for error output.
• `clog`:- Standard error stream used for logging.
• These streams are part of the `iostream` header in C++.
53) What is class Template? Explain syntax of class template with suitable example?
• A class template in C++ is a blueprint for creating a family of classes. It allows us to define a
class with generic types that can be used with different data types. Here's the
• SYNTAX of a class template:
template <class T>
class ClassName {
// Class members and functions
};
• Example of a class template:
#include <iostream>
using namespace std;
template <class T>
class Pair {
private:
T first;
T second;
public:
Pair(T f, T s) : first(f), second(s) {}
void display() {
cout << "Pair: " << "(" << first << ", " << second << ")" << endl;
}
};
int main() {
Pair<int> intPair(10, 20);
intPair.display();
Pair<double> doublePair(3.14, 2.71);
doublePair.display();
return 0;
}
54)Explain inline function. Write the circumstances in which inline function will work like
a normal functions.?
• Inline Function :- An inline function is a function defined with the `inline` keyword.
• It is a request to the compiler to insert the code of the function in place of each call to the
function.
• This can result in faster execution of the program as there is no overhead of function calling
and returning.
• However, using `inline` is just a request to the compiler, and it may choose not to inline the
function if it deems it inappropriate (e.g., if the function is too large or complex).
• --Circumstances when inline function will work like a normal function:
• When the function is small:- If the function is relatively small (a few lines of code), the
compiler may choose to inline it, treating it like a normal function. However, this depends on the
compiler and its optimization settings.
• When the function does not contain loops or switches: If the function does not contain loops or
switches, it is more likely to be inlined.
• When the function does not contain static variables or other complex constructs: If the function
does not contain static variables or other complex constructs, it is more likely to be inlined.

55)Explain various errors handling functions used during file operations.?


• `fail()`:- Returns `true` if either a read/write operation fails. For example, when we attempt to
read an integer from a file, but the file has characters instead of an integer.
• `bad()`:- Returns `true` if there is a fatal i/o operation. For example, when a disk error occurs.
• `eof()`:- Returns `true` if the end-of-file has been reached. This happens when we attempt to
read beyond the end of the file.
• `clear()`:-Clears the error flags set by any of the above functions.
56) What is friend function ? Which are the features of friend function ?
• A friend function is a function that is not a member of a class, but has access to the private
and protected members of that class. It is declared inside the class with the keyword `friend`.
– features of friend functions include:--
• Friend functions can access private and protected members of a class.
• They are not called using the object of the class, but can be invoked like a normal function.
• Friend functions can be declared in multiple classes, granting them access to multiple
classes' private members.
• Friend functions are not inherited, so they cannot be accessed by derived classes.
• Friend functions can be used to implement operator overloading, allowing them to operate on
private data members of the class.
57) What is inheritance ? Explain it with its types.?
• Inheritance is a mechanism in C++ by which one class can inherit properties and behavior
from another class. It allows a class to reuse the properties and behavior of another class, and
also to add new properties and behavior to the derived class.
• —----Types of Inheritance:- —------
• Single Inheritance:- When a class inherits from only one base class.
• Multiple Inheritance :- When a class inherits from more than one base class.
• Multilevel Inheritance :- When a class inherits from another class, which in turn inherits from
another class.
• Hierarchical Inheritance :- When multiple derived classes inherit from a single base class.
• Hybrid Inheritance :- When a class has a combination of single, multiple, multilevel, and
hierarchical inheritance.
58) Explain virtual base class with suitable diagram.?
• Virtual Base Class :- A virtual base class is a class that is intended to be inherited by
multiple derived classes.
• When a base class is made virtual, a derived class inherits only one copy of the base class's
members, rather than multiple copies.
• This is useful when a derived class inherits from multiple base classes, and there are common
base classes among those base classes.
• The following diagram illustrates a scenario where a virtual base class is used to prevent
ambiguity in multiple inheritance:
A
/ \
B C <- Diagram
\ /
D
• In this diagram, if `A` is a virtual base class, then `D` will only inherit one copy of `A`, rather
than two copies, preventing ambiguity.
59) Explain compile time polymorphism and runtime polymorphism with example.?
• Compile-time Polymorphism:- Compile-time polymorphism, also known as static
polymorphism,
• Is a type of polymorphism that is resolved at compile time.
• It allows different implementations of the same function or method to be invoked depending
on the types of the arguments passed to the function or method at compile time.
• Example:
#include <iostream>
class Shape {
public:
virtual void draw() {
std::cout << "Drawing Shape\n";
}
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing Circle\n";
}
};
class Square : public Shape {
public:
void draw() override {
std::cout << "Drawing Square\n";
}
};
int main() {
Shape* s;
Circle c;
Square sq;
s = &c;
s->draw(); // Drawing Circle
s = &sq;
s->draw(); // Drawing Square
return 0;
}
60)What is stream? Explain a stream class hierarchy.
• A stream is an object used to send data from a program to an external source (output stream)
or from an external source to a program (input stream).
• The standard library provides two classes to perform input and output operations:
- `iostream` (for console input/output)
- `fstream` (for file input/output).
• Stream Class Hierarchy :-
- `iostream`:- The base class for input and output streams.
- `ostream`:- Output stream class for writin data to a stream.
- `ofstream`:- File output stream class for writing data to a file.
- `stringstream`:- Stream class that operates on strings.
- `istream`:- Input stream class for reading data from a stream.
- `ifstream`:- File input stream class for reading data from a file.
- `stringstream`:- Stream class that operates on strings.
61) Differentiate between object oriented programming and procedure Oriented
programming.?
• -----------OOP----------
1. Object oriented programming language is object oriented.
2. In OOP, the unit of programming is the class.
3. OOP trace on data.
4. Follow bottom-up approach program design.
5. Basic building block of OOP is object.
6. OOP has access specifiers named Public, Private, and Protected.
7. In OOP, overloading is possible in the form of Function Overloading and Operator
Overloading.
8. In OOP, importance is given to the data rather than procedures or functions because it works
as a real world.
9. OOP provide Data Hiding so it provides more security.
10. Examples of OOP are C++, JAVA, VB.NET, C#.NET.
•--------------POP-------------
1. Procedural programming languages tend to be action oriented.
2. In procedural programming, unit of programming is the function.
3. POP trace on procedures.
4. Follow top-down approach in program design.
5. Basic building block of POP is function.
6. POP does not have any access specifiers.
7. In POP, Overloading is not possible.
8. In POP, importance is not given to data but to functions as well as sequence of actions to be
done.
9. POP does not have any proper way for hiding data so it is less secure.
10. Examples of POP are C, VB, FORTRAN, Pascal.
62) Differentiate between Inline function and Micro ?
•---------- inline function----------------
1. These are functions provided by C++
2. Inline keyword is used to declare the function as inline.
3. It can be define inside or outside the class.
4. Inline functions are parsed by the compiler.
5. Inline function can access the data member of the class
6. compiler replaces the function call with the function code
7. Inline functions follows strict parameter type checking
8. Can be used for debugging a program
9. inline int sum(int a, int b) {
return (a+b); }
•--------------Micro---------------
1. Macros are preprocessor directives.
2. #define is used to declare the macro.
3. It cannot be declare inside the class.
4. Macros are expanded by the C++ preprocessor.
5. Macros cannot access the data member of the class
6. C preprocessor replaces every occurrence of macro template with its corresponding
definition.
7. Macros does not follows parameter type checking.
8. Cannot be used for debugging as they are expanded at pre-compile time.
9. #define SUM(a,b) (a+b)
63) Write a C++ program to copy contents of one file to another file.?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream source("source.txt"); // Open source file for reading
ofstream dest("destination.txt"); // Open destination file for writing
if (source.is_open() && dest.is_open()) { // Check if both files are open
char c;
while (source.get(c)) { // Read character by character from source
dest.put(c); // Write character to destination
}
cout << "Contents copied successfully." << endl;
} else {
cerr << "Error opening files!" << endl;
}
source.close(); // Close source file
dest.close(); // Close destination file
return 0;
}
64) Write a program to calculate area and circumference of a circle using inline function.?
#include <iostream>
#include <cmath> // For M_PI
using namespace std;
inline double calculateArea(double radius) {
return M_PI * pow(radius, 2); // Pi * r^2
}
inline double calculateCircumference(double radius) {
return 2 * M_PI * radius; // 2 * Pi * r
}
int main() {
double radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
cout << "Area: " << calculateArea(radius) << endl;
cout << "Circumference: " << calculateCircumference(radius) << endl;
return 0;
}
65) Declare a class of vehicle. Derived classes are two wheeler, three wheeler and four
wheeler. Display the properties of each type of vehicle using member functions of class.?
#include <iostream>
using namespace std;
// Base class
class Vehicle {
public:
virtual void display() {
cout << "Vehicle: Base class" << endl;
}
};
// Derived classes
class TwoWheeler : public Vehicle {
public:
void display() override {
cout << "Two Wheeler: Two wheels" << endl;
}
};
class ThreeWheeler : public Vehicle {
public:
void display() override {
cout << "Three Wheeler: Three wheels" << endl;
}
};
class FourWheeler : public Vehicle {
public:
void display() override {
cout << "Four Wheeler: Four wheels" << endl;
}
};
int main() {
Vehicle* vehicle = new Vehicle();
Vehicle* twoWheeler = new TwoWheeler();
Vehicle* threeWheeler = new ThreeWheeler();
Vehicle* fourWheeler = new FourWheeler();
vehicle->display();
twoWheeler->display();
threeWheeler->display();
fourWheeler->display();
delete vehicle;
delete twoWheeler;
delete threeWheeler;
delete fourWheeler;
return 0;
}
66) Write a C++ program to use setfile () and setiosflags () manipulator.?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Set floatfield to fixed, setprecision to 2, set width to 10
cout << setiosflags(ios::fixed) << setprecision(2) << setw(10);
cout << 1.2345 << endl;
// Set width to 10, set fill character to #
cout << setw(10) << setfill('#');
cout << 1.2345 << endl;
// Restore default settings for output
cout << resetiosflags(ios::fixed) << setfill(' ') << setw(0);
return 0;
}
67) Write a C++ program to compare two strings using overload operater.?
#include <iostream>
#include <cstring>
using namespace std;
class StringComparator {
char* str;
public:
StringComparator(const char* s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
bool operator==(const StringComparator& s) const {
return strcmp(str, s.str) == 0;
}
bool operator!=(const StringComparator& s) const {
return strcmp(str, s.str) != 0;
}
bool operator<(const StringComparator& s) const {
return strcmp(str, s.str) < 0;
}
bool operator>(const StringComparator& s) const {
return strcmp(str, s.str) > 0;
}
~StringComparator() {
delete[] str;
}
};
int main() {
StringComparator s1("Hello");
StringComparator s2("World");
if (s1 == s2) {
cout << "Strings are equal." << endl;
} else {
cout << "Strings are not equal." << endl;
}
if (s1 < s2) {
cout << "s1 is less than s2." << endl;
} else {
cout << "s1 is greater than s2." << endl;
}
return 0;
}
68) Write a C++ program to create a class which contains two data members. Write
member functions to accept, display and swap two entered numbers using call by
reference.?
#include <iostream>
using namespace std;
class NumberSwapper {
int a, b;
public:
NumberSwapper(int num1, int num2) {
a = num1;
b = num2;
}
void accept() {
cout << "Enter two numbers: ";
cin >> a >> b;
}
void display() {
cout << "a = " << a << ", b = " << b << endl;
}
void swap() {
int temp = a;
a = b;
b = temp;
}
};
int main() {
NumberSwapper ns(10, 20);
ns.accept();
cout << "Before swapping: ";
ns.display();
ns.swap();
cout << "After swapping: ";
ns.display();
return 0;
}
69) Write a C++ program to create a class Book which contains data members as B-Id,
B-Name, B-Author, B- publication. Write member functions to accept and display Book
information also display count of books. (Use static data member to maintain count of
books)?
#include <iostream>
#include <string>
using namespace std;
class Book {
static int count;
string id, name, author, publication;
public:
Book() {
count++;
}
void accept() {
cout << "Enter Book ID: ";
cin >> id;
cout << "Enter Book Name: ";
cin >> name;
cout << "Enter Book Author: ";
cin >> author;
cout << "Enter Book Publication: ";
cin >> publication;
}
void display() {
cout << "Book ID: " << id << endl;
cout << "Book Name: " << name << endl;
cout << "Book Author: " << author << endl;
cout << "Book Publication: " << publication << endl;
}
static void displayCount() {
cout << "Total Books: " << count << endl;
}
};
int Book::count = 0;
int main() {
Book b1, b2, b3;
b1.accept();
b2.accept();
b3.accept();
b1.display();
b2.display();
b3.display();
Book::displayCount();
return 0;
}
70) Write a C++ program to calculate square and cube of integer number by using inline
function.?
#include <iostream>
using namespace std;
inline int square(int num) {
return num * num;
}
inline int cube(int num) {
return num * num * num;
}
int main() {
int number;
cout << "Enter an integer number: ";
cin >> number;
cout << "Square: " << square(number) << endl;
cout << "Cube: " << cube(number) << endl;
return 0;
}
71) Design C++ class which contains function display(). Write a program to count number
of times display() is called. (use static data member).?
#include <iostream>
using namespace std;
class Counter {
static int count;
public:
static void display() {
cout << "Display function called." << endl;
count++;
}
static int getCount() {
return count;
}
};
int Counter::count = 0;
int main() {
Counter::display();
Counter::display();
Counter::display();
cout << "Display function called " << Counter::getCount() << " times." << endl;
return 0;
}
72) Write a C++ program to read contents of a text file and count number of characters,
Words and lines in a file?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("example.txt");
string line;
int charCount = 0, wordCount = 0, lineCount = 0;
if (file.is_open()) {
while (getline(file, line)) {
lineCount++;
charCount += line.length();
bool inWord = false;
for (char c : line) {
if (isalnum(c)) {
if (!inWord) {
wordCount++;
inWord = true;
}
} else {
inWord = false;
}
}
}
file.close();
cout << "Number of characters: " << charCount << endl;
cout << "Number of words: " << wordCount << endl;
cout << "Number of lines: " << lineCount << endl;
} else {
cout << "Unable to open file." << endl;
}
return 0;
}
73) Write a program to perform addition of two matrices using operator overloading.?
#include <iostream>
using namespace std;
class Matrix {
int rows, cols;
int **data;
public:
Matrix(int r, int c) : rows(r), cols(c) {
data = new int*[rows];
for (int i = 0; i < rows; ++i) {
data[i] = new int[cols];
for (int j = 0; j < cols; ++j) {
data[i][j] = 0;
}
}
}
~Matrix() {
for (int i = 0; i < rows; ++i) {
delete[] data[i];
}
delete[] data;
}
Matrix operator+(const Matrix& other) {
if (rows != other.rows || cols != other.cols) {
cerr << "Matrices are not of the same dimensions." << endl;
exit(1);
}
Matrix result(rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}
return result;
}
void setData(int r, int c, int value) {
data[r][c] = value;
}
void display() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << data[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
Matrix mat1(3, 3), mat2(3, 3);
cout << "Enter elements of matrix 1: " << endl;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
int num;
cin >> num;
mat1.setData(i, j, num);
}
}
cout << "Enter elements of matrix 2: " << endl;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
int num;
cin >> num;
mat2.setData(i, j, num);
}
}
cout << "Matrix 1:" << endl;
mat1.display();
cout << "Matrix 2:" << endl;
mat2.display();
Matrix result = mat1 + mat2;
cout << "Matrix 1 + Matrix 2:" << endl;
result.display();
return 0;
}
74) Write a program for constructor with default arguments.?
#include <iostream>
using namespace std;
class Rectangle {
int length;
int breadth;
public:
Rectangle(int l = 0, int b = 0) : length(l), breadth(b) {}
void area() {
cout << "Area of rectangle: " << length * breadth << endl;
}
};
int main() {
Rectangle r1;
r1.area();
Rectangle r2(5, 10);
r2.area();
return 0;
}
75) Write a program to overload unary operator.?
#include <iostream>
using namespace std;
class Complex {
int real;
int imaginary;
public:
Complex(int r = 0, int i = 0) : real(r), imaginary(i) {}
Complex operator-() {
Complex temp;
temp.real = -real;
temp.imaginary = -imaginary;
return temp;
}
void display() {
cout << real << (imaginary < 0 ? " - " : " + ") << abs(imaginary) << "i" << endl;
}
};
int main() {
Complex c1(3, 5), c2;
c2 = -c1;
c2.display();
return 0;
}
76) Write a C++ program using friend function to calculate sum of digits of a number.?
#include <iostream>
using namespace std;
class Number {
int value;
public:
Number(int val) : value(val) {}
friend int sumOfDigits(Number num);
};
int sumOfDigits(Number num) {
int sum = 0;
while (num.value > 0) {
sum += num.value % 10;
num.value /= 10;
}
return sum;
}
int main() {
Number num(12345);
cout << "Sum of digits: " << sumOfDigits(num) << endl;
return 0;
}
78) Write a template program to sort integer and float array elements of size five.?
#include <iostream>
using namespace std;
template <typename T>
void bubbleSort(T arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int intArray[] = {5, 3, 7, 1, 2};
float floatArray[] = {5.5, 3.3, 7.7, 1.1, 2.2};
int intSize = sizeof(intArray) / sizeof(intArray[0]);
int floatSize = sizeof(floatArray) / sizeof(floatArray[0]);
bubbleSort(intArray, intSize);
bubbleSort(floatArray, floatSize);
cout << "Sorted integer array: ";
for (int i = 0; i < intSize; ++i) {
cout << intArray[i] << " ";
}
cout << endl;
cout << "Sorted float array: ";
for (int i = 0; i < floatSize; ++i) {
cout << floatArray[i] << " ";
}
cout << endl;
return 0;
}
79) Design a C++ program to create two base classes personnel (name, address,
e-mail-id, DOB) and academic (10th std marks, 12th std marks, class obtained). Derive a
class Bio_data from both these classes and prepare a bio data of a student having
personal and academic information.?
#include <iostream>
#include <string>
using namespace std;
class Personnel {
protected:
string name;
string address;
string email;
string dob;
public:
void setPersonalInfo(string n, string add, string em, string db) {
name = n;
address = add;
email = em;
dob = db;
}
void displayPersonalInfo() {
cout << "Name: " << name << endl;
cout << "Address: " << address << endl;
cout << "Email: " << email << endl;
cout << "Date of Birth: " << dob << endl;
}
};
class Academic {
protected:
float tenthMarks;
float twelfthMarks;
string classObtained;
public:
void setAcademicInfo(float tenth, float twelfth, string cl) {
tenthMarks = tenth;
twelfthMarks = twelfth;
classObtained = cl;
}
void displayAcademicInfo() {
cout << "10th Marks: " << tenthMarks << endl;
cout << "12th Marks: " << twelfthMarks << endl;
cout << "Class Obtained: " << classObtained << endl;
}
};
class BioData : public Personnel, public Academic {
public:
void setBioData(string n, string add, string em, string db, float tenth, float twelfth, string cl) {
setPersonalInfo(n, add, em, db);
setAcademicInfo(tenth, twelfth, cl);
}
void displayBioData() {
cout << "----Bio Data----" << endl;
displayPersonalInfo();
cout << endl;
displayAcademicInfo();
}
};
int main() {
BioData student;
student.setBioData("John Doe", "123 Street, City", "[email protected]", "01/01/2000",
95.5, 97.8, "A+");
student.displayBioData();
return 0;
}
80)Create a class time which contains data members as hours, minutes and seconds.
Write a C++ program using operator overloading for the following:
(i) == to check whether two times same or not.
(ii) >> to accept time
(iii) << to display time.
#include <iostream>
using namespace std;
class Time {
int hours;
int minutes;
int seconds;
public:
Time() : hours(0), minutes(0), seconds(0) {}
Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}
bool operator==(const Time &other) {
return hours == other.hours && minutes == other.minutes && seconds == other.seconds;
}
friend istream &operator>>(istream &in, Time &time) {
cout << "Enter hours: ";
cin >> time.hours;
cout << "Enter minutes: ";
cin >> time.minutes;
cout << "Enter seconds: ";
cin >> time.seconds;
return in;
}
friend ostream &operator<<(ostream &out, const Time &time) {
out << time.hours << " hours, " << time.minutes << " minutes, " << time.seconds << "
seconds";
return out;
}
};
int main() {
Time t1, t2;
cout << "Enter time t1 (in hh:mm:ss format): ";
cin >> t1;
cout << "Enter time t2 (in hh:mm:ss format): ";
cin >> t2;
cout << "t1: " << t1 << endl;
cout << "t2: " << t2 << endl;
if (t1 == t2) {
cout << "t1 and t2 are the same." << endl;
} else {
cout << "t1 and t2 are not the same." << endl;
}
return 0;
}
81) Operator overloading?
• Operator overloading is a feature of object-oriented programming that allows an operator to
have different meanings when applied to different data types.
• It allows you to define how an operator should behave when used with a class or a
user-defined data type.
• For example:- you can overload the `+` operator to add two objects of a class or the `<<`
operator to display the contents of an object.
• Example of Operator Overloading:-
#include <iostream>
class Complex {
private:
double real;
double imaginary;
public:
Complex() : real(0), imaginary(0) {}
Complex(double r, double i) : real(r), imaginary(i) {}
Complex operator+(const Complex& c) {
Complex result;
result.real = real + c.real;
result.imaginary = imaginary + c.imaginary;
return result;
}
friend std::ostream& operator<<(std::ostream& os,const Complex& c) {
os << c.real << " + " << c.imaginary << "i";
return os;
}
};
int main() {
Complex c1(2, 3);
Complex c2(4, 5);
Complex c3 = c1 + c2;
std::cout << c3;
return 0;
}
82) Pointer to object with example.?
• A pointer to an object is a variable that holds the memory address of an object.
• It allows you to manipulate the object indirectly by accessing its members through the pointer.
In C++, you can use the `new` operator to create an object dynamically and store its address in
a pointer.
• Example of Pointer to Object :-
#include <iostream>
class MyClass {
public:
void print() {
std::cout << "Hello, World!" << std::endl;
}
};
int main() {
MyClass* ptr = new MyClass;
ptr->print(); // Hello, World!
delete ptr; // Free memory allocated for object
return 0;
}
83) Memory management operators?
• Memory management operators in C++ allow you to allocate and deallocate memory
dynamically.
• `new`:- The `new` operator is used to allocate memory for a new object and returns a pointer
to the allocated memory.
int* p = new int;
• `delete`:- The `delete` operator is used to deallocate memory that was previously allocated
with the `new` operator.
• delete p;
• `new[]`:- The `new[]` operator is used to allocate memory for an array of objects and returns a
pointer to the allocated memory.
• int* arr = new int[10];
• `delete[]`:- The `delete[]` operator is used to deallocate memory that was previously allocated
with the `new[]` operator.
• delete[] arr;
84)Exception handling?
• Exception handling is a mechanism in C++ that allows you to handle runtime errors, such as
division by zero, out-of-range array access, or memory allocation failure, gracefully.
• It provides a way to transfer control from one part of a program to another when an exceptional
situation (an exception) occurs.
• There are three main keywords used in exception handling:
• Try :-The `try` block contains the code that may throw an exception. It is followed by one or
more `catch` blocks.
• Catch :- The `catch` block is used to catch and handle an exception thrown by the `try` block.
It specifies the type of exception that can be caught and the actions to be taken.
• Throw :- The `throw` statement is used to throw an exception. It can be used in the `try` block
or in a function to signal an exceptional situation.
• Example:-
#include <iostream>
int main() {
int x = 10, y = 0;
try {
if (y == 0) {
throw "Division by zero";
}
std::cout << x / y << std::endl;
} catch (const char* msg) {
std::cerr << "Error: " << msg << std::endl;
}
return 0;
}
85)Call-by-value and call-by-reference
•------Call-by-Value--------
- In call-by-value, the actual parameter (argument) value is copied to the formal parameter of
the function.
• Any changes made to the parameter inside the function do not affect the actual parameter.
• Example:-
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
return 0;
}
•--------Call-by-Reference---------
- In call-by-reference, the actual parameter's address is passed to the formal parameter,
allowing the function to modify the original variable.
• Example:-
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
return 0;
}
86) Data abstraction?
• Data abstraction is a programming concept that focuses on exposing only the necessary
details of an object while hiding its implementation details.
• It allows programmers to create more modular and maintainable code by separating the
interface(what a class does) from its implementation (how it does it).
• In C++, data abstraction is achieved using classes and access specifiers like `private` and
`public`.
• By making data members private and providing public member functions to access and modify
the data, we can hide the internal details of a class.
• Example:
class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
};
87) Default Argument?
• In C++, you can provide default arguments for function parameters.
• Default arguments are used when the function is called without providing a value for that
parameter.
• If a default argument is not provided, the default value is used.
• Example:-
void print(int x = 10) {
std::cout << x << std::endl;
}
int main() {
print(); // 10 (default value used)
print(20); // 20 (provided value used)
return 0;
}

88) Explain the rules of Operator Overloading.?


• The overloaded operator must have at least one operand of a user-defined type.
• You cannot change the number of operands or their precedence.
• Some operators, like assignment (=) and function call (()), have specific rules and restrictions.
• Overloaded operators can be implemented as member functions or global functions.
• The return type of the overloaded operator should be appropriate for the operation being
performed.

You might also like