CPP
CPP
The extraction (>>) and insertion (<<) operators are used in C++ for input and
output operations, respectively. The extraction operator (>>) is used to extract
data from a stream (e.g., keyboard, file) into variables, while the insertion
operator (<<) is used to mani data from variables into a stream (e.g., console,
file).
2. Define constructor.
A constructor in C++ is a special member function that is automatically called
when an object is created. It is used to initialize the object's data members and
allocate necessary resources.
3. What is inline function.
An inline function in C++ is a function that is expanded in place during
compilation, instead of being called like a regular function. It is typically used
for small, frequently called functions to improve performance by reducing
function call overhead.
4. What is reference variable? What is its major use.
A reference variable in C++ is an alias for another variable. Once a reference is
initialized to refer to a variable, any changes made to the reference variable
affect the original variable, and vice versa. One major use of reference variables
is in passing arguments to functions by reference, allowing functions to modify
their arguments.
5. What is Abstraction and Encapsulation.
Abstraction in programming refers to the concept of hiding complex
implementation details and exposing only necessary interfaces or functionalities
to the user. Encapsulation, on the other hand, is the bundling of data and the
methods that operate on that data into a single unit (class in C++), while hiding
the internal details of how those methods work.
6. What is compile - Time polymorphism.
Compile-time polymorphism in C++ is achieved through function overloading
and operator overloading. Function overloading allows multiple functions with
the same name but different parameters to be defined, while operator
overloading enables operators to be redefined for user-defined types.
7. What is default argument.
A default argument in C++ is a function parameter that has a default value
assigned to it. If a value is not provided for a default argument when calling the
function, the default value is used instead.
8. What is the use of scope resolution operator.
The scope resolution operator (::) in C++ is used to access global variables or
functions from within a local scope, or to define a function outside of a class
declaration.
9. What are the access specifiers used in C++.
There are three access specifiers used for class members:
- public: Members declared as public are accessible from outside the class.
- protected: Members declared as protected are accessible within the class and
by derived classes.
- private: Members declared as private are accessible only within the class.
10.What is data abstraction?
Data abstraction in programming refers to the process of hiding the complex
implementation details of data and exposing only the necessary parts to the user.
This is typically achieved through the use of classes and objects, where the
internal data and methods are encapsulated within the class, and only the public
interface is accessible to the user.
11. What is return by reference?
Return by reference in C++ allows a function to return a reference to a variable
rather than a copy of the variable. This can be useful for functions that need to
modify the value of a variable directly in the calling function.
12. Define:
(i) Dynamic binding
Dynamic binding, also known as late binding or runtime polymorphism, is a
programming concept where the actual method or function called is determined
during runtime based on the object's type rather than at compile time.
(ii)Message Passing.
Message passing is a communication mechanism in object-oriented
programming where objects interact by sending and receiving messages. This
involves invoking methods or functions of one object from another object.
13. Explain structure of C++ program.
- Preprocessor directives (e.g., #include for including header files)
- Global declarations (e.g., global variables, function prototypes)
- ‘main()’ function as the entry point of the program
- User-defined functions or classes
- Statements and expressions for program logic
- Return statement to indicate the end of main() function
14. What is this pointer?
The ‘this’ pointer in C++ is a special pointer that points to the current object
instance within a member function of a class. It is used to access members of
the current object and differentiate them from local variables with the same
names.
15. Explain const arguments.
Const arguments in C++ refer to function parameters that are declared as const,
indicating that the function promises not to modify the values of those
arguments. This helps in ensuring the immutability of certain arguments passed
to functions.
16. Define pure virtual function.
A pure virtual function in C++ is a virtual function declared in a base class with
"= 0" after the function declaration. It is meant to be overridden in derived
classes, and the base class becomes an abstract class, which cannot be
instantiated.
17. Explain break, continue statements.
The break statement in C++ is used to exit a loop or switch statement
prematurely. When encountered, it terminates the current loop or switches
control to the statement immediately following the loop or switch.
The continue statement in C++ is used to skip the remaining code in a loop
iteration and jump to the next iteration.
18. What is static data member?
A static data member in C++ is a member of a class that belongs to the class
itself rather than individual objects. It is shared among all instances of the class
and is initialized only once.
19. What is setf() function ?
The setf() function in C++ is used to set various formatting flags for output
streams, such as setting the precision for floating-point numbers or specifying
the base for integer output. It is part of the <iomanip> header.
20.Explain tellg() and tellp() with syntax.
tellg() and tellp() are member functions of input streams (istream) and output
streams (ostream) in C++ respectively, used for file positioning.
Syntax:- streampos tellg(); , streampos tellg();
21. Explain any two manipulators.
-setw(int width): Sets the field width of the next input or output operation.
-setprecision(int n): Sets the precision of floating-point output to n decimal
places
22. What is destructor?
A destructor in C++ is a special member function of a class that is automatically
called when an object of that class is destroyed or goes out of scope. It is used
to clean up resources allocated by the object, such as memory, file handles, etc.
23. What are the visibility lables used in C++.
There are three visibility labels used for class members:
- public: Members declared as public are accessible from outside the class.
- protected: Members declared as protected are accessible within the class and
by derived classes.
- private: Members declared as private are accessible only within the class.
24. What is default argument in function?
A default argument in a function in C++ is an argument that is automatically
used if the caller does not provide a corresponding argument. It allows the
function to be called with fewer arguments than declared, providing a default
value for the missing arguments.
25. What is static Polymorphism.
Static polymorphism in C++ is achieved through function overloading and
operator overloading. Function overloading allows multiple functions with the
same name but different parameters, while operator overloading enables
operators to be redefined for user-defined types.
26. Function overriding
Function overriding is a concept in object-oriented programming where a
derived class provides a specific implementation for a method that is already
defined in its base class.
The overridden method in the derived class must have the same signature (name
and parameters) as the base class method.
This allows polymorphic behavior, where a function call is resolved at runtime
based on the actual type of the object.
27. Exception handling.
Exception handling in C++ allows you to handle runtime errors or exceptional
situations gracefully, without terminating the program abruptly.
It involves three keywords: try, catch, and optionally throw.
The try block contains the code that may throw an exception.
The catch block catches and handles the exceptions thrown by the try block.
The throw keyword is used to explicitly throw an exception.
28. Explain memory management operators with the help of suitable example.
Memory management operators in C++ are used for dynamic memory
allocation and deallocation. The main memory management operators are new
and delete. Let's delve into each of these operators with suitable examples:
- new Operator: The new operator is used to dynamically allocate memory for a
single variable or an array. Here's an example of using the new operator to
allocate memory for a single variable:
int* numPtr = new int;
*numPtr = 10;
- delete Operator: The delete operator is used to deallocate memory that was
previously allocated dynamically using new. Here's how you can use the delete
operator to free the memory allocated for a single variable and an array:
delete numPtr;
delete[] arrPtr;
29. Explain memory allocation for objects with non-static data member and static
data member.
Memory allocation for objects with non-static data members and static data
members follows specific rules based on the nature of these members. Let's
delve into each type of member and how memory is allocated for them within
objects.
- Non-Static Data Members:
Non-static data members are unique to each object instance. When an object is
created, memory is allocated for each of its non-static data members separately
for each instance of the class. This means that every object has its own set of
non-static data members, and changes to one object's non-static data members
do not affect those of other objects.
- Static Data Members:
Static data members are shared among all instances of the class. Memory for
static data members is allocated only once, regardless of how many objects of
the class are created. This means that changes to static data members are
reflected across all instances of the class.
30. When do we make a class virtual base class? Explain it with suitable example.
A class is made a virtual base class when you want to avoid issues like diamond
inheritance and ambiguity in multiple inheritance scenarios. In C++, diamond
inheritance occurs when a class is derived from two classes that have a common
base class. This can lead to ambiguity and problems with member access if not
handled correctly.
To resolve such issues, you can make the common base class a virtual base
class. This means that only one instance of the common base class is shared
among the derived classes, thus avoiding duplication of inherited members.
#include <iostream>
class Example {
public:
static int staticVar; // Static data member
Example() {} // Default constructor
};
int Example::staticVar = 0; // Initializing staticVar outside the class
int main() {
Example obj1, obj2; // Two instances of Example class
Example::staticVar = 100; // Modify the staticVar
std::cout << "Object 1 staticVar: " << obj1.staticVar << std::endl;
std::cout << "Object 2 staticVar: " << obj2.staticVar << std::endl;
return 0;
}
31. Explain array of object in C++ with example.
An array of objects allows you to store multiple instances of a class in
contiguous memory locations. Each element of the array is an object of the
class type. This is useful when you need to work with multiple objects of the
same type in a structured manner.
#include <iostream>
class MyClass {
public:
int data;
MyClass() : data(0) {} // Default constructor
MyClass(int d) : data(d) {} // Parameterized constructor
};
int main() {
const int arraySize = 3; // Size of the array
MyClass objArray[arraySize]; // Array of MyClass objects
// Initializing objects in the array using different constructors
objArray[0] = MyClass(10);
objArray[1] = MyClass(20);
objArray[2] = MyClass(30);
// Accessing and modifying object data in the array
std::cout << "Object 1 data: " << objArray[0].data << std::endl;
std::cout << "Object 2 data: " << objArray[1].data << std::endl;
std::cout << "Object 3 data: " << objArray[2].data << std::endl;
return 0;
}
32. Explain any four formatted input/output functions.
- printf and scanf
printf: Used for formatted output to the console.
scanf: Used for formatted input from the console.
- std::cout and std::cin
std::cout: Used for formatted output to the console (standard output).
std::cin: Used for formatted input from the console (standard input).
- std::setw (from <iomanip>)
std::setw: Used for setting the width of output fields in formatted output.
- std::fixed and std::setprecision (from <iomanip>)
std::fixed: Used to display floating-point numbers in fixed-point notation.
std::setprecision: Used to set the precision (number of decimal places) for
33. Can we pass class object as function arguments? Explain with the help of an
example.
We can pass class objects as function arguments. This allows you to work with
objects of a class within functions, pass objects between functions, and perform
operations on them.
#include <iostream>
class MyClass {
public:
int data;
MyClass() : data(0) {} // Default constructor
MyClass(int d) : data(d) {} // Parameterized constructor
};
void displayObject(const MyClass& obj) {
std::cout << "Object data: " << obj.data << std::endl;
}
void modifyObject(MyClass& obj, int newData) {
obj.data = newData;
}
int main() {
MyClass obj1(10); // Create an object with initial data
// Pass object to functions
displayObject(obj1); // Pass object by const reference
modifyObject(obj1, 20); // Pass object by reference and modify its data
displayObject(obj1); // Display modified object data
return 0;
}
34. Explain various stream classes used to perform console input/output (I/o)
operations.
Various stream classes are used for performing console input/output (I/O)
operations. These stream classes are part of the C++ Standard Library
(iostream), and they provide a versatile and efficient way to interact with the
console for input and output.
- std::cout: The standard output stream class. It is used to write formatted output
to the console. Ex. std::cout << "Hello, World!" << std::endl;
- std::cin: The standard input stream class. It is used to read input from the
console.
int num;
std::cin >> num;
- std::cerr: The standard error stream class. It is used to write error messages to
the console. Ex. std::cerr << "Error: File not found!" << std::endl;
- std::clog: The standard logging stream class. It is used for logging messages to
the console, similar to std::cerr
std::clog << "Logging information..." << std::endl;
35. What is class Template? Explain syntax of class template with suitable
example.
A class template in C++ is a blueprint for creating classes that can work with
any data type. It allows you to define a generic class where the type of data it
operates on is specified as a template parameter. This enables you to write
reusable code that can work with different data types without having to rewrite
the class for each type.
#include <iostream>
template <typename T>
class Box {
private:
T length;
T width;
T height;
public:
Box(T l, T w, T h) : length(l), width(w), height(h) {}
T calculateVolume() {
return length * width * height;
}
};
int main() {
Box<int> intBox(3, 4, 5);
Box<double> doubleBox(2.5, 3.5, 4.5);
std::cout << "Volume of intBox: " << intBox.calculateVolume() << std::endl;
std::cout << "Volume of doubleBox: " << doubleBox.calculateVolume() <<
std::endl;
return 0;
}
36. Trace the output of the following program and explain it. Assume there is no
syntax error.
# include < iostream.h>
Class abc
{
int i; public : abc
(int v = 0)
37. Explain array of object with diagram.
An array of objects in C++ is a sequential collection of objects of the same class
type. Just as a regular array holds elements of a basic data type, an array of
objects stores and manipulates multiple instances of a particular class. Each
element of an array of objects represents an individual object which possesses
its own attributes and methods.