Theory based question answers of c++ language
### 1. What is C++? How is it different from C?
**C++** is a general-purpose programming language that was
developed as an extension of the C programming language. It was
created by Bjarne Stroustrup in the early 1980s. C++ introduces object-
oriented programming (OOP) features, such as classes and objects,
while retaining the efficiency and flexibility of C.
**Key Differences Between C and C++:**
- **Paradigm**: C is a procedural programming language, while C++
supports both procedural and object-oriented programming paradigms.
- **OOP Features**: C++ introduces classes, objects, inheritance,
polymorphism, encapsulation, and abstraction, which are not present in
C.
- **Standard Library**: C++ has a richer standard library, including the
Standard Template Library (STL), which provides templates for common
data structures and algorithms.
- **Function Overloading**: C++ supports function overloading (multiple
functions with the same name but different parameters), while C does
not.
- **Namespaces**: C++ uses namespaces to avoid name collisions,
whereas C does not have this feature.
- **Exception Handling**: C++ provides built-in support for exception
handling using `try`, `catch`, and `throw`, which is absent in C.
- **Constructors and Destructors**: C++ allows the use of constructors
and destructors for object initialization and cleanup, which C lacks.
- **References**: C++ supports references (an alias for a variable),
while C only uses pointers.
---
### 2. What are the key features of C++?
The key features of C++ include:
1. **Object-Oriented Programming (OOP)**:
- Supports classes, objects, inheritance, polymorphism,
encapsulation, and abstraction.
- Enables modular and reusable code.
2. **Procedural Programming**:
- Retains the procedural programming style of C, allowing for
structured programming.
3. **Standard Template Library (STL)**:
- Provides pre-built templates for data structures (e.g., vectors, lists,
maps) and algorithms (e.g., sorting, searching).
4. **Function Overloading**:
- Allows multiple functions with the same name but different
parameters.
5. **Operator Overloading**:
- Enables defining custom behavior for operators (e.g., `+`, `-`, `*`)
for user-defined types.
6. **Exception Handling**:
- Provides mechanisms for handling runtime errors using `try`,
`catch`, and `throw`.
7. **Namespaces**:
- Helps avoid naming conflicts by grouping entities under a unique
scope.
8. **Constructors and Destructors**:
- Automates object initialization and cleanup.
9. **Templates**:
- Supports generic programming by allowing functions and classes to
operate with any data type.
10. **Memory Management**:
- Provides control over dynamic memory allocation and deallocation
using `new` and `delete`.
11. **Multi-threading**:
- Supports concurrent programming through libraries like
`<thread>`.
12. **Portability**:
- C++ code can be compiled and run on various platforms with
minimal changes.
---
### 3. What is the difference between procedural and object-oriented
programming?
| **Aspect** | **Procedural Programming** |
**Object-Oriented Programming (OOP)** |
|-----------------------------|---------------------------------------------------------|----------
---------------------------------------------|
| **Focus** | Focuses on procedures or functions.
| Focuses on objects and their interactions. |
| **Program Structure** | Programs are divided into functions.
| Programs are divided into classes and objects. |
| **Data and Behavior** | Data and functions are separate.
| Data and functions are encapsulated together in objects. |
| **Reusability** | Limited reusability through functions.
| High reusability through inheritance and polymorphism. |
| **Approach** | Top-down approach (programs are broken into
functions).| Bottom-up approach (programs are built using objects).|
| **Data Security** | Less secure, as data is globally accessible.
| More secure, as data is encapsulated and accessed via methods. |
| **Examples** | C, Pascal, FORTRAN. | C+
+, Java, Python. |
| **Key Concepts** | Functions, variables, and procedures.
| Classes, objects, inheritance, polymorphism, encapsulation, and
abstraction. |
| **Complexity Management** | Suitable for small to medium-sized
programs. | Suitable for large and complex programs. |
In summary, procedural programming is function-centric, while object-
oriented programming is object-centric, emphasizing modularity,
reusability, and data security. C++ supports both paradigms, making it
a versatile language.
### 1. What are tokens in C++? Explain with examples.
**Tokens** are the smallest individual units in a C++ program. They are
the building blocks of a program and are recognized by the compiler.
Tokens include:
- **Keywords** (e.g., `int`, `if`, `else`)
- **Identifiers** (e.g., variable names like `count`, `sum`)
- **Constants/Literals** (e.g., `10`, `3.14`, `'A'`)
- **Operators** (e.g., `+`, `-`, `*`, `/`)
- **Special Symbols** (e.g., `;`, `{}`, `()`)
**Example:**
```cpp
int main() {
int a = 10; // 'int', 'main', 'a', '10', ';' are tokens
return 0;
}
```
---
### 2. What are keywords, identifiers, constants, and literals in C++?
#### **Keywords**:
- Keywords are reserved words that have special meaning in C++.
- They cannot be used as identifiers (e.g., variable names).
- Examples: `int`, `if`, `else`, `while`, `return`, `class`, `public`, etc.
#### **Identifiers**:
- Identifiers are names given to variables, functions, classes, etc.
- Rules for identifiers:
- Must start with a letter or underscore (`_`).
- Can contain letters, digits, or underscores.
- Cannot be a keyword.
- Case-sensitive.
- Examples: `sum`, `myVariable`, `calculateArea`, `_count`.
#### **Constants/Literals**:
- Constants are fixed values that do not change during program
execution.
- Literals are the actual values assigned to variables or constants.
- Examples:
- Integer literal: `10`
- Floating-point literal: `3.14`
- Character literal: `'A'`
- String literal: `"Hello"`
---
### 3. Explain the different data types in C++.
C++ supports a variety of data types, which can be categorized as
follows:
#### **Primitive/Built-in Data Types**:
1. **Integer Types**:
- `int`: Stores whole numbers (e.g., `10`, `-5`).
- `short`: Smaller range than `int`.
- `long`: Larger range than `int`.
- `long long`: Even larger range.
2. **Floating-Point Types**:
- `float`: Single-precision floating-point numbers (e.g., `3.14f`).
- `double`: Double-precision floating-point numbers (e.g., `3.14`).
- `long double`: Extended precision floating-point numbers.
3. **Character Types**:
- `char`: Stores a single character (e.g., `'A'`).
- `wchar_t`: Wide character for larger character sets.
4. **Boolean Type**:
- `bool`: Stores `true` or `false`.
#### **Derived Data Types**:
1. **Arrays**:
- Collection of elements of the same type (e.g., `int arr[5];`).
2. **Pointers**:
- Stores memory addresses (e.g., `int *ptr;`).
3. **References**:
- Alias for a variable (e.g., `int &ref = a;`).
#### **User-Defined Data Types**:
1. **Structures (`struct`)**:
- Groups related data items of different types.
2. **Classes (`class`)**:
- Blueprint for objects, supporting OOP features.
3. **Unions (`union`)**:
- Similar to structures but shares memory for its members.
4. **Enumerations (`enum`)**:
- Defines a set of named integer constants.
---
### 4. What is type conversion? Explain implicit and explicit type
conversion.
#### **Type Conversion**:
- Type conversion is the process of converting a value from one data
type to another.
#### **Implicit Type Conversion**:
- Also called **automatic type conversion**.
- Performed by the compiler automatically when compatible types are
involved.
- Example:
```cpp
int a = 10;
double b = a; // 'a' is implicitly converted to double
```
#### **Explicit Type Conversion**:
- Also called **type casting**.
- Requires manual intervention using casting operators.
- Example:
```cpp
double x = 3.14;
int y = (int)x; // 'x' is explicitly cast to int
```
---
### 5. What is the difference between type casting and type
conversion?
| **Aspect** | **Type Conversion** | **Type
Casting** |
|------------------------|----------------------------------------------|--------------------------
-----------------|
| **Definition** | General term for converting one type to another. |
Specific form of type conversion, often explicit. |
| **Implicit/Explicit** | Can be implicit (automatic) or explicit. |
Always explicit (manual). |
| **Syntax** | Implicit: No syntax required. | Uses
casting operators like `(int)`, `static_cast<int>()`. |
| **Example** | `double b = 10;` (implicit). | `int y =
(int)3.14;` (explicit). |
| **Use Case** | Used when types are compatible. | Used
when types are incompatible or precision loss is expected. |
In summary, type conversion is a broader term that includes both
implicit and explicit changes, while type casting specifically refers to
explicit conversion.
### 1. What are control statements in C++? Explain types of loops.
**Control Statements** in C++ are used to control the flow of execution
in a program based on certain conditions or loops. They include:
1. **Conditional Statements**:
- `if`, `else if`, `else`: Execute code based on a condition.
- `switch`: Execute code based on the value of a variable.
2. **Looping Statements**:
- **`for` loop**: Repeats a block of code a specific number of times.
```cpp
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
```
- **`while` loop**: Repeats a block of code as long as a condition is
true.
```cpp
int i = 0;
while (i < 5) {
cout << i << endl;
i++;
}
```
- **`do-while` loop**: Executes the block of code at least once, then
repeats as long as the condition is true.
```cpp
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 5);
```
3. **Jump Statements**:
- `break`: Exits a loop or switch statement.
- `continue`: Skips the current iteration of a loop.
- `return`: Exits a function and optionally returns a value.
- `goto`: Jumps to a labeled statement (rarely used).
---
### 2. What is the difference between "while" and "do-while" loops?
| **Aspect** | **`while` Loop** | **`do-while`
Loop** |
|------------------------|-----------------------------------------------|-------------------------
-------------------|
| **Condition Check** | Condition is checked **before** the loop body
executes. | Condition is checked **after** the loop body executes. |
| **Execution** | The loop body may not execute at all if the
condition is false initially. | The loop body executes **at least once**,
even if the condition is false initially. |
| **Syntax** | ```cpp while (condition) { ... } ``` | ```cpp do
{ ... } while (condition); ``` |
| **Use Case** | Used when the loop body should execute only if
the condition is true. | Used when the loop body must execute at least
once. |
**Example**:
```cpp
int i = 5;
while (i < 5) { // This loop will not execute
cout << i << endl;
i++;
}
do { // This loop will execute once
cout << i << endl;
i++;
} while (i < 5);
```
---
### 3. What are functions in C++? Explain types of functions.
**Functions** in C++ are reusable blocks of code that perform a specific
task. They help in modularizing code and improving readability.
#### **Types of Functions**:
1. **Predefined (Library) Functions**:
- Functions provided by C++ standard libraries (e.g., `cout`, `sqrt()`).
2. **User-Defined Functions**:
- Functions defined by the programmer.
- Example:
```cpp
int add(int a, int b) {
return a + b;
}
```
3. **Parameterized Functions**:
- Functions that accept parameters (arguments).
4. **Non-Parameterized Functions**:
- Functions that do not accept any parameters.
5. **Return Type Functions**:
- Functions that return a value using the `return` statement.
6. **Void Functions**:
- Functions that do not return any value.
---
### 4. What is function overloading? Explain with an example.
**Function Overloading** is a feature in C++ that allows multiple
functions to have the same name but different parameters (number or
type of parameters).
**Example**:
```cpp
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Function to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Function to add two doubles
double add(double a, double b) {
return a + b;
}
int main() {
cout << add(2, 3) << endl; // Calls first function
cout << add(2, 3, 4) << endl; // Calls second function
cout << add(2.5, 3.5) << endl; // Calls third function
return 0;
}
```
**Output**:
```
5
9
6.0
```
---
### 5. What is the difference between call by value and call by
reference?
| **Aspect** | **Call by Value** | **Call by
Reference** |
|------------------------|----------------------------------------------|--------------------------
------------------|
| **Definition** | A copy of the actual value is passed to the
function. | The address of the actual value is passed to the function. |
| **Effect on Original Value** | Changes made to the parameter do not
affect the original value. | Changes made to the parameter affect the
original value. |
| **Syntax** | ```cpp void func(int a) { ... } ``` | ```cpp void
func(int &a) { ... } ``` |
| **Use Case** | Used when the original value should not be
modified. | Used when the original value needs to be modified. |
**Example**:
```cpp
#include <iostream>
using namespace std;
// Call by value
void incrementByValue(int a) {
a++;
}
// Call by reference
void incrementByReference(int &a) {
a++;
}
int main() {
int x = 5;
incrementByValue(x); // x remains 5
cout << x << endl;
incrementByReference(x); // x becomes 6
cout << x << endl;
return 0;
}
```
**Output**:
```
5
6
```
---
### 6. What are inline functions? What are their advantages?
**Inline Functions**:
- Inline functions are functions where the compiler replaces the function
call with the actual code of the function to reduce the overhead of
function calls.
- Defined using the `inline` keyword.
**Example**:
```cpp
#include <iostream>
using namespace std;
inline int square(int x) {
return x * x;
}
int main() {
cout << square(5) << endl; // Compiler replaces square(5) with 5 * 5
return 0;
}
```
**Advantages**:
1. **Reduced Overhead**:
- Eliminates the overhead of function calls (saving and restoring
registers, stack operations, etc.).
2. **Faster Execution**:
- Suitable for small, frequently called functions.
3. **Improved Performance**:
- Useful in performance-critical applications.
**Disadvantages**:
1. **Increased Binary Size**:
- The code is duplicated at each call site, increasing the size of the
executable.
2. **Not Suitable for Large Functions**:
- Inlining large functions can lead to code bloat.
**Note**: The `inline` keyword is a request to the compiler, and the
compiler may ignore it for large or complex functions.