Nepal Engineering Council · Electronics, Communication & Information Engineering · Chapter 3
Programming Language and Its Applications
Tap an option to check it. Wrong picks show the right answer and the hint.
504 questions in 6 syllabus topics · 28 tagged from past exams or NEC model sets.
3.1 Introduction to C programming
110 questions · ACtE0301
1. What is the purpose of a semicolon in C programming?
Aasadh 2081 examShow hintHide hint
Semicolon marks the end of an instruction.
Show answerHide answer
Answer: A. Indicate end of statement
Semicolon (;) indicates the end of a C statement and is required for statement termination.
2. What is C++ for loop correct syntax?
Aasadh 2081 examShow hintHide hint
Init-Cond-Update order.
Show answerHide answer
Answer: A. for (initialization; condition; increment/decrement)
Correct C++ for loop syntax: for (initialization; condition; increment/decrement) { statements }
3. What is the correct syntax for declaring a function in C?
Show hintHide hint
Function declarations end with semicolon in C.
Show answerHide answer
Answer: A. type_of_return name_of_function (argument type);
Correct C function declaration syntax: return_type function_name(parameter_types); The declaration specifies what the function does without implementing it.
4. Which of the following is NOT a C format specifier?
Show hintHide hint
Valid specifiers: %d, %f, %s, %c. What's missing?
Show answerHide answer
Answer: D. %t
%t is not a standard C format specifier. Valid specifiers include %d (int), %f (float), %s (string), %c (char), %x (hex), %o (octal).
5. What is compiler vs interpreter difference?
Show hintHide hint
Timing of translation differs.
Show answerHide answer
Answer: B. Compiler all at once, interpreter line-by-line
Compiler translates entire program before execution. Interpreter translates and executes line by line during runtime.
6. What are C Tokens?
Show hintHide hint
C tokens are the building blocks of source code - think of what compiler recognizes.
Show answerHide answer
Answer: B. Smallest individual units of a C program
C Tokens are the smallest individual units of a C program that the compiler recognizes. They include keywords (like int, void, return), identifiers (variable names), constants (literal values like 5, 3.14, 'a'), strings ("hello"), operators (+, -, *, /), and special symbols ({}, [], ()). Every valid C program is a sequence of tokens separated by whitespace. For example, in 'int x = 5;', the tokens are: int, x, =, 5, and ;. Tokens cannot be broken down further without losing meaning. Understanding tokens is fundamental because the lexical analyzer (first phase of compilation) converts source code into a token stream, which the parser then uses to build the syntax tree.
7. Which of the following is NOT a C token?
Show hintHide hint
Tokens are individual units, not complete statements.
Show answerHide answer
Answer: A. int x;
'int x;' is a complete statement consisting of multiple tokens: 'int' (keyword token), 'x' (identifier token), and ';' (special symbol token). A statement is a sequence of tokens, not a single token. Each component 'int', 'x', and ';' individually are tokens. This distinction is crucial in understanding how compilers parse code - they first break code into tokens, then analyze token sequences to understand program structure. The semicolon marks statement termination and is itself a token.
8. What are the main categories of C operators?
Show hintHide hint
Consider operators like +, &&, ==, =, &, and others like sizeof.
Show answerHide answer
Answer: B. Arithmetic, logical, relational, assignment, bitwise, and special operators
C supports multiple operator categories: (1) Arithmetic operators (+, -, *, /, %) for mathematical operations; (2) Relational operators (==, !=, <, >, <=, >=) for comparison returning boolean values; (3) Logical operators (&&, ||, !) for boolean logic; (4) Assignment operators (=, +=, -=, *=, /=, %=, etc.) for variable assignment; (5) Bitwise operators (&, |, ^, ~, <<, >>) for bit-level operations; (6) Special operators like sizeof (memory size), & (address), * (pointer dereference), ?: (ternary), and comma. Operator precedence and associativity determine evaluation order - for example, * and / have higher precedence than + and -. Understanding all operator categories is essential for writing correct expressions and avoiding logical errors.
9. What is the purpose of formatted input in C?
Show hintHide hint
Think about scanf() and how %d, %f, %s work.
Show answerHide answer
Answer: B. To read input data according to specified format specifications
Formatted input in C uses functions like scanf() and fscanf() to read data from standard input or files according to format specifications. Format specifiers (%d for integer, %f for float, %s for string, %c for character, %x for hexadecimal, %o for octal) tell the function what type of data to expect and how to interpret the input stream. For example, scanf("%d %f %s", &integer, &floating, string) expects an integer, then a float, then a string from input. This allows reading mixed data types in a structured manner. The advantage is flexibility in input handling, but disadvantages include complexity and potential buffer overflow risks with %s. Format specifications also include width and precision modifiers like %5d (read 5 characters) or %.2f (2 decimal places). Proper format specification matching with variable types is critical to prevent undefined behavior.
10. What does unformatted input in C do?
Show hintHide hint
Functions like getchar(), gets(), and fgets() are unformatted.
Show answerHide answer
Answer: B. Reads data character by character or in raw form
Unformatted input in C reads data without requiring format specifications, processing input as-is. Functions include getchar() (reads single character), getche() (reads character with echo), getch() (reads character without echo), gets() (reads entire line - UNSAFE, causes buffer overflow), and fgets() (safe alternative to gets(), reads line with specified size limit). Unformatted input is simpler and faster than formatted input but lacks automatic type conversion. For example, getchar() returns an int (ASCII value) of the character read, or EOF (-1) on end-of-file. This approach is useful when you want to process data character-by-character or handle raw input. Important: gets() is deprecated and removed from modern C standards due to security risks; fgets() is preferred as it allows specifying maximum characters to read. Unformatted functions are also useful in interactive programs where you want immediate character processing.
11. What is the difference between if-else and switch control statements?
Show hintHide hint
Consider what each statement is best used for - flexibility vs. simplicity.
Show answerHide answer
Answer: D. if-else can check multiple conditions, switch checks single variable
if-else and switch are both control statements but serve different purposes: if-else allows checking multiple independent conditions with boolean expressions (if x > 10 && y < 5), handles ranges, and uses comparison operators. switch evaluates a single expression and compares it against multiple constant cases, executing matching case block. switch is more efficient when checking one variable against many discrete values, as it may use jump tables. However, if-else is more flexible for complex conditions. Example: switch (day) {case 1: ...; break; case 2: ...} vs if (day==1) {...} else if (day==2) {...}. switch requires break statements to prevent fall-through (executing subsequent cases). switch cases must be constants, while if-else conditions can be complex expressions. For simple discrete value comparisons, switch is preferred; for range checks or multiple condition logic, if-else is necessary. The default case in switch is like final else in if-else chain.
12. What are the types of loops in C?
Show hintHide hint
How many different loop constructs does C provide?
Show answerHide answer
Answer: B. for, while, and do-while
C provides three types of loops: (1) while loop: checks condition before each iteration, may not execute at all if condition is false initially. Syntax: while(condition) { statements }. Best for unknown iteration count. (2) do-while loop: executes body first, then checks condition, guaranteeing at least one execution. Syntax: do { statements } while(condition). Best for input validation where you must process at least once. (3) for loop: most compact, combines initialization, condition, and increment. Syntax: for(init; condition; increment) { statements }. Best for known iteration count. Additionally, C supports nested loops (loop inside another loop), break statement (exits current loop), continue statement (skips current iteration), and goto statement (though discouraged). Understanding loop selection is crucial: for loops suit array iterations, while loops suit event-driven processing, and do-while suits menu systems. Loop control variables should be carefully managed to prevent infinite loops.
13. What is function prototyping in C?
Show hintHide hint
Why do we write function declarations at the top of files?
Show answerHide answer
Answer: B. Declaring function signature before definition
Function prototyping is declaring a function's signature (return type, name, and parameters) before its implementation. Syntax: return_type function_name(parameter_types); without the body. Prototypes allow forward declaration, enabling the compiler to verify function calls before seeing the actual implementation. Benefits: (1) Type checking - compiler ensures calls match declaration; (2) Organization - main() can call functions defined later; (3) Compilation - prevents 'function undeclared' errors; (4) Readability - clearly documents function interfaces. Example: int add(int a, int b); before int add(int a, int b) { return a+b; }. Prototypes are typically placed in header files or at file top. Parameters can be empty () or specified with types. Parameter names in prototypes are optional: int add(int, int) is valid. This is different from function definition which includes the implementation body. Modern C standards (C99, C11) recommend explicit prototyping of all functions.
14. What is a recursive function?
Show hintHide hint
Think of factorial or Fibonacci calculations.
Show answerHide answer
Answer: A. Function that calls itself directly or indirectly
A recursive function is one that calls itself (direct recursion) or calls another function that eventually calls back to it (indirect recursion). Every recursive function needs: (1) Base case - condition that stops recursion to prevent infinite loops; (2) Recursive case - call with simplified/modified parameters approaching base case; (3) Progress toward base case. Example: factorial(n) = n * factorial(n-1) with base case factorial(0) = 1. Recursion uses the call stack, storing return addresses and local variables. Each recursive call creates new stack frame. Disadvantages: stack overflow risk, slower than iteration, higher memory usage. Advantages: elegant solution for inherently recursive problems (trees, divide-and-conquer), cleaner code. Tail recursion (recursive call is last operation) can be optimized by compilers. Common recursive problems: factorial, Fibonacci, tree traversal, permutations, binary search. Understanding stack depth is crucial - deep recursion can exhaust stack memory. Iterative solutions are often more efficient than recursive ones, but recursion provides conceptual clarity for certain algorithms.
15. What are one-dimensional arrays in C?
Show hintHide hint
Think of a simple list or vector accessed by single index.
Show answerHide answer
Answer: B. Linear collection of elements of same type with single index
One-dimensional (1D) arrays are linear collections of elements of the same data type accessed using a single index. Declaration: type array_name[size]; Example: int arr[5]; creates integer array for 5 elements indexed 0-4. Memory allocation: contiguous block of (size * sizeof(type)) bytes. Initialization: int arr[] = {1,2,3,4,5} or int arr[5] = {0}. Accessing: arr[i] retrieves i-th element. Array operations: traversal (loop through all), search (find element), sorting, mathematical operations. Passing arrays to functions: decays to pointer (int* arr), so array modifications affect original. Advantages: random access (O(1)), cache-friendly, simple. Disadvantages: fixed size (in C, dynamic allocation needed for variable size), requires bounds checking to prevent overflow. String arrays: char str[50] stores null-terminated strings. Multi-dimensional arrays are treated as arrays of arrays. Important: array indices are 0-based; arr[5] in size-5 array is undefined (out of bounds). Arrays form foundation for data structures like queues, stacks, and heaps.
16. What is a two-dimensional array in C?
Show hintHide hint
Think of a spreadsheet or matrix structure.
Show answerHide answer
Answer: A. Array with rows and columns like a matrix
Two-dimensional (2D) arrays are tables with rows and columns, representing matrices. Declaration: type array[rows][cols]; Example: int matrix[3][4] creates 3x4 integer matrix. Memory layout: stored row-major order in C - all of row 0, then row 1, etc. Access: matrix[i][j] accesses element at row i, column j. Initialization: int matrix[2][3] = {{1,2,3},{4,5,6}}; Total size: 3*4*sizeof(int) bytes contiguous. Passing to functions: void func(int arr[][4]) - second dimension must be specified because compiler calculates stride. Nested loops for traversal: for(i=0;i<rows;i++) for(j=0;j<cols;j++) process matrix[i][j]. Applications: image processing (pixels), game boards, spreadsheets, mathematical matrices. Alternative: array of pointers (int *arr[3]) creates jagged array with flexible row sizes. Multidimensional arrays generalize to 3D, 4D, etc., but overhead increases. Memory is still contiguous in C, unlike some languages. Index bounds checking is programmer's responsibility - out-of-bounds access is undefined behavior. Understanding memory layout is crucial for passing to functions and pointer arithmetic.
17. What is string manipulation in C?
Show hintHide hint
Strings in C are char arrays ending with '\0'. Consider operations like strlen, strcpy, etc.
Show answerHide answer
Answer: B. Operations on character arrays terminated by null character
String manipulation involves operations on null-terminated character arrays. Strings in C: char str[20] = "hello" stores h,e,l,l,o,\0 (null terminator marks end). Key operations: strlen(str) returns string length excluding null. strcpy(dest, src) copies string src to dest (unsafe, no bounds check). strncpy(dest, src, n) copies max n characters (safer). strcat(dest, src) concatenates src to dest. strncat(dest, src, n) concatenates max n characters. strcmp(str1, str2) compares strings, returns 0 if equal. strchr(str, c) finds character c in string. strstr(str1, str2) finds substring str2 in str1. sprintf(buffer, format, ...) formats string into buffer. String operations require string.h header. Common pitfalls: buffer overflow with strcpy (use strncpy), forgetting null terminator, comparing pointers instead of content with ==. Modern approach: use safer functions with size limits. Strings are immutable in sense that operations create new copies or modify arrays. Understanding null-termination is crucial - forgetting it causes undefined behavior. String functions are fundamental for text processing, parsing input, and data manipulation.
18. What is multidimensional array in C?
Show hintHide hint
Generalization of 2D arrays to 3D, 4D, and beyond.
Show answerHide answer
Answer: A. Arrays with more than two dimensions
Multidimensional arrays extend beyond 2D to any number of dimensions. Declaration: type array[d1][d2][d3]...[dn]; Example: int cube[3][3][3] creates 3x3x3 array (27 elements). Memory: allocated contiguously in row-major order. Access: cube[i][j][k] accesses element using all indices. Storage: total size = d1*d2*d3*...*dn*sizeof(type). Initialization: int cube[2][2][2] = {{{1,2},{3,4}},{{5,6},{7,8}}}; Traversal: nested loops for each dimension. Practical applications: 3D graphics (x,y,z coordinates), 3D grids (physics simulations), time-series data (3D with time dimension), image stacks. Passing to functions requires specifying all but first dimension: void func(int arr[][3][3]) for 3D array. Memory layout understanding critical - for cube[i][j][k], memory position calculated as: base + ((i*d2*d3 + j*d3 + k)*sizeof(type)). Performance: cache efficiency decreases with dimensions due to fewer elements per cache line. Pointers of pointers alternative: int ***arr for dynamic allocation but more complex. Higher dimensions increase complexity significantly; careful memory management essential.
19. What does printf() do in C?
Show hintHide hint
Formatted output function - think of how you display variables.
Show answerHide answer
Answer: B. Writes formatted output to stdout
printf() writes formatted output to standard output (stdout). Syntax: printf(format_string, arguments); Format specifiers: %d (int), %f (float), %lf (double), %c (char), %s (string), %x (hex), %o (octal), %p (pointer). Modifiers: %5d (width 5), %.2f (2 decimal places), %-5d (left-aligned), %05d (zero-padded). Example: printf("Value: %d, Name: %s\n", 42, "test") outputs formatted text with values. Return value: number of characters printed (or negative on error). Escape sequences: \n (newline), \t (tab), \" (quote), \\ (backslash). Printf advantage: single function for multiple data types. Disadvantages: no type checking (dangerous), complex format strings, slower than direct output. Variants: fprintf(FILE*, format, args) writes to file; sprintf(buffer, format, args) writes to string buffer; snprintf(buffer, size, format, args) with size limit (safer). Format string vulnerabilities: untrusted format strings cause security issues. Understanding format specifiers crucial - %d for pointer using %p, mismatches cause undefined behavior. Printf is fundamental for debugging and user interaction, but modern C developers prefer snprintf for safety.
20. What is the difference between formatted and unformatted output in C?
Show hintHide hint
Compare printf with putchar or puts.
Show answerHide answer
Answer: B. Formatted specifies output format, unformatted outputs as-is
Formatted output uses format specifiers to control output appearance: printf("%5d %.2f", x, y) - explicit format. Unformatted output displays data as-is without specification: putchar(c) outputs character, puts(str) outputs string with newline, putch(c) with echo. Key differences: Formatted: requires format string with specifiers (%d, %f, %s, etc.), supports width/precision, allows multiple arguments, slower due to parsing, risk of format vulnerabilities. Unformatted: simple character/string output, faster (direct write), no format parsing, suitable for raw output. Examples: printf("Number: %d", 42) vs putchar('x'). Use formatted for structured output (reports, formatted tables, numbers with specific precision). Use unformatted for simple character I/O, interactive menus, raw data output. Unformatted functions: putchar() (single char), putch() (char with echo), puts() (string + newline), fputc() (to file), fputs() (string to file). Modern practice: printf/fprintf/sprintf family dominates due to flexibility. Buffer flushing: fflush(stdout) ensures output appears immediately. Understanding performance difference matters for high-frequency output scenarios.
21. What are user-defined functions in C?
Show hintHide hint
Functions you write yourself, not from library.
Show answerHide answer
Answer: B. Functions written by programmer for specific tasks
User-defined functions are functions written by programmers to perform specific tasks, promoting code reusability and modularity. Structure: return_type function_name(parameters) { function body; return value; }. Example: int add(int a, int b) { return a + b; }. Benefits: code reuse, modularity, easier debugging, improved readability, maintainability. Function components: (1) Function signature: defines interface. (2) Function body: implementation. (3) Return statement: sends value back to caller. (4) Parameters: input values. Scope rules: local variables exist within function, global variables accessible from anywhere. Parameter passing: pass-by-value (copy of value), pass-by-pointer (address, allows modification). Return types: void (no return), int, float, pointer, struct, array (as pointer). Recursion: function calling itself. Function pointers: void (*funcPtr)(int); pointing to functions. Benefits for larger programs: divide complex logic into manageable pieces, enable team development (different team members write functions), facilitate testing. Organization: function declaration (prototype), then main(), then function definitions. Many programmers place function definitions before main() to avoid forward declarations. Understanding scope, parameter passing, and return values essential for effective function use.
22. Which of the following is not a data type in C?
NEC model setShow hintHide hint
C has primitive data types. String is a construct, not a built-in primitive type.
Show answerHide answer
Answer: C. String
In C, 'String' is not a built-in data type. The primitive data types in C are: (1) int (integers), (2) float (floating-point numbers), (3) char (single characters), (4) double (double-precision floating-point), (5) void. Strings in C are represented as arrays of characters (char arrays), not as a primitive type. For example: char str[] = "Hello"; creates a string. Unlike languages such as Java or Python that have a String class, C does not have a native string type. Strings are created using null-terminated char arrays. C provides string handling functions in the standard library (string.h) like strlen(), strcpy(), etc., but these work with char arrays, not a built-in String type. This is an important distinction for C programmers.
23. Which of the following is an example of indirect recursion?
NEC model setShow hintHide hint
Indirect recursion involves cycle through intermediate functions, not direct self-call.
Show answerHide answer
Answer: B. Function X calls function Y, which calls function X
An example of indirect recursion is function X calls function Y, which calls function X. Recursion types: (1) Direct - Function calls itself, (2) Indirect - Function calls another, which eventually calls original. Direct recursion: factorial(n) = n * factorial(n-1), function directly calls itself. Indirect recursion example: (1) Function A calls B, (2) Function B calls A, (3) Creates cycle A → B → A. Cycle length can vary: (1) Mutual recursion - A and B call each other (cycle 2), (2) Longer cycle - A → B → C → A (cycle 3), (3) Any length possible. How indirect recursion works: (1) A calls B with modified parameter, (2) B calls A with different parameter, (3) Base case must exist - Stop cycle, (4) Without base case - Infinite recursion. Example code pattern: function A(n) { if (n <= 0) return 0; return B(n-1); } function B(n) { if (n <= 0) return 0; return A(n-1); }. Detecting: (1) Direct - Obvious from function code, (2) Indirect - Requires tracing call chain, (3) Tools can detect - Call graph analysis. Stack behavior: (1) Each call adds stack frame, (2) Indirect recursion - Stack grows across functions, (3) Same recursion depth concern - Stack overflow risk, (4) Need base case - To unwind stack. Different from: (1) Direct recursion - Self-call, (2) Tail recursion - Last operation is recursive call, (3) Mutual recursion - Specific indirect case. Practical: (1) Less common than direct recursion, (2) Mutual recursion in parsing - A parses expression, B parses term, (3) State machines - Functions represent states. This demonstrates recursion complexity.
24. What is the process of converting high-level programming language code to machine or assembly level code called?
Recalled from Jan 2026 examShow hintHide hint
Converting source code to lower-level code. What's this process?
Show answerHide answer
Answer: B. Compilation
Compilation is the process of converting high-level programming language code to machine or assembly level code. A compiler reads source code and translates it into executable machine code or intermediate code. Compilation happens before execution. Interpretation executes code line-by-line without pre-translation. Linking combines compiled object files. Loading places executable into memory for execution. Compilation produces standalone executables that run without the compiler. This is why compiled programs run faster than interpreted ones.
25. Which function is used to read a single character from the keyboard in C?
Recalled from Jan 2026 examShow hintHide hint
This function reads one character without pressing Enter. What is it?
Show answerHide answer
Answer: C. getch()
The getch() function is used to read a single character from the keyboard in C. getch() reads a character without waiting for Enter key, making it useful for immediate input in games and interactive programs. getchar() also reads a single character but waits for Enter. scanf() reads formatted input. gets() reads an entire string (unsafe). getch() is non-standard (mainly for DOS/Windows) but widely used. For portable code, getchar() is preferred.
26. What is an Identifier in C programming?
Show answerHide answer
Answer: B. A symbol used to represent a variable, function, or structure in a C program
27. What is a constant in C programming?
Show answerHide answer
Answer: C. A value that cannot be changed during program execution
28. What is an operator in C programming?
Show answerHide answer
Answer: A. A symbol used to perform operations on variables, constants, and expressions
29. What are some examples of operators in C programming?
Show answerHide answer
Answer: A. Arithmetic, relational, logical, and bitwise operators
30. What is a keyword in C programming?
Show answerHide answer
Answer: C. A word that has a specific meaning in the language and cannot be used as an identifier
31. What are some examples of keywords in C programming?
Show answerHide answer
Answer: A. int, float, char, if, for, while
32. What is the difference between keywords and identifiers in C programming?
Show answerHide answer
Answer: C. Keywords cannot be used as identifiers, while identifiers can be used as keywords
33. What is the difference between constants and variables in C programming?
Show answerHide answer
Answer: A. Constants have a fixed value that cannot be changed, while variables have a value that can be changed
34. What is the difference between an operator and a function in C programming?
Show answerHide answer
Answer: A. An operator performs an operation on one or more operands, while a function performs a set of operations on input data
35. What is the purpose of a semicolon at the end of a statement in C programming?
Show answerHide answer
Answer: A. To indicate the end of a statement
36. What is a token in C programming?
Show answerHide answer
Answer: A. A symbol or keyword used in a C program
37. What are some examples of tokens in C programming?
Show answerHide answer
Answer: A. Keywords, identifiers, constants, and operators
38. What is the purpose of arithmetic operators in C programming?
Show answerHide answer
Answer: A. To perform basic mathematical operations such as addition, subtraction, multiplication, and division
39. What is the purpose of relational operators in C programming?
Show answerHide answer
Answer: B. To compare values and make decisions based on the comparison results
40. What is the purpose of logical operators in C programming?
Show answerHide answer
Answer: C. To perform logical operations such as AND, OR, and NOT on boolean values
41. What is the purpose of bitwise operators in C programming?
Show answerHide answer
Answer: C. To manipulate bits and perform bitwise operations on binary data
42. What is the difference between the logical AND operator (&&) and the bitwise AND operator (&) in C programming?
Show answerHide answer
Answer: A. The logical AND operator performs a logical operation on boolean values, while the bitwise AND operator performs a bitwise operation on binary data
43. What is the difference between the logical OR operator (||) and the bitwise OR operator (|) in C programming?
Show answerHide answer
Answer: A. The logical OR operator performs a logical operation on boolean values, while the bitwise OR operator performs a bitwise operation on binary data
44. What is the result of the following expression: 5 & 6
Show answerHide answer
Answer: C. 4
45. What is the result of the following expression: 5<6
Show answerHide answer
Answer: B. 1
46. What is the purpose of the conditional operator (?:) in C programming?
Show answerHide answer
Answer: A. To perform a conditional operation based on the value of a condition
47. What is the difference between the bitwise AND operator (&) and the bitwise OR operator (|) in C programming?
Show answerHide answer
Answer: A. The bitwise AND operator performs a bitwise AND operation, while the bitwise OR operator performs a bitwise OR operation
48. What is the purpose of the assignment operator (=) in C programming?
Show answerHide answer
Answer: B. To assign a value to a variable
49. What is the result of the following expression: 5 + 7 * 2
Show answerHide answer
Answer: A. 19
50. What is the difference between formatted and unformatted input/output in C programming?
Show answerHide answer
Answer: A. Formatted input/output is used to input/output data in a specific format, while unformatted input/output is used to input/output data without any format.
51. What are some examples of formatted input functions in C programming?
Show answerHide answer
Answer: A. scanf(), gets(), and fscanf()
52. What are some examples of formatted output functions in C programming?
Show answerHide answer
Answer: C. printf(), puts(), and fprintf()
53. What is the purpose of the scanf() function in C programming?
Show answerHide answer
Answer: B. To input data from the standard input device
54. What is the purpose of the printf() function in C programming?
Show answerHide answer
Answer: A. To output data to the standard output device
55. What is the difference between the gets() and scanf() functions in C programming?
Show answerHide answer
Answer: A. The gets() function inputs data without any format, while the scanf() function inputs data in a specific format.
56. What is the difference between the puts() and printf() functions in C programming?
Show answerHide answer
Answer: A. The puts() function outputs data without any format, while the printf() function outputs data in a specific format.
57. What is the standard library function used to read a string from the user in C?
Show answerHide answer
Answer: B. gets()
58. Which of the following functions is used to print a string to the screen in C?
Show answerHide answer
Answer: A. puts()
59. What is the purpose of the %d format specifier in the printf() function in C?
Show answerHide answer
Answer: A. To print an integer
60. What is the purpose of the %f format specifier in the printf() function in C?
Show answerHide answer
Answer: C. To print a float
61. What is the purpose of the %lf format specifier in the printf() function in C?
Show answerHide answer
Answer: D. To print a double
62. Which of the following functions is used to read a single character from the standard input in C?
Show answerHide answer
Answer: C. getchar()
63. What is the purpose of the if statement in C programming?
Show answerHide answer
Answer: C. To execute a block of code if a certain condition is true
64. What is the purpose of the else statement in C programming?
Show answerHide answer
Answer: B. To execute a block of code if a condition is false
65. What is the purpose of the switch statement in C programming?
Show answerHide answer
Answer: A. To execute one of several blocks of code based on the value of an expression
66. What is the purpose of the break statement in C programming?
Show answerHide answer
Answer: B. To exit a switch statement
67. What is the purpose of the continue statement in C programming?
Show answerHide answer
Answer: C. To skip an iteration of a loop
68. What is the purpose of the for loop in C programming?
Show answerHide answer
Answer: A. To execute a block of code a specified number of times
69. What is the purpose of the while loop in C programming?
Show answerHide answer
Answer: B. To execute a block of code indefinitely until a condition is met
70. What is an if statement in C programming used for?
Show answerHide answer
Answer: C. To execute a block of code if a certain condition is met, and execute another block of code if the condition is not met
71. What is the purpose of the do-while loop in C programming?
Show answerHide answer
Answer: C. To execute a block of code at least once, and then repeatedly until a condition is met
72. What is the difference between the for loop and the while loop in C programming?
Show answerHide answer
Answer: A. The for loop is used for a specified number of iterations, while the while loop is used until a condition is met
73. What does the "if" statement in C do?
Show answerHide answer
Answer: A. Executes a block of code if a condition is true
74. What is the syntax of the "if" statement in C?
Show answerHide answer
Answer: A. if (condition) { statements }
75. What is the purpose of the "else" statement in C?
Show answerHide answer
Answer: D. To execute a block of code if the condition in the if statement is false
76. What is the syntax of the "switch" statement in C?
Show answerHide answer
Answer: A. switch (expression) { case constant-expression: statements; break; default: statements; }
77. What is the index of the first element in a one-dimensional array in C?
Show answerHide answer
Answer: A. 0
78. What is the syntax for declaring a two-dimensional integer array of size 3x4 in C?
Show answerHide answer
Answer: A. int arr[3][4];
79. How can you access the value of the 3rd element of the 2nd row of a two-dimensional array in C?
Show answerHide answer
Answer: A. arr[1][2]
80. What is the difference between a one-dimensional array and a two-dimensional array in C?
Show answerHide answer
Answer: A. A one-dimensional array has one row and multiple columns, whereas a two-dimensional array has multiple rows and multiple columns.
81. What is the syntax for initializing a one-dimensional array in C?
Show answerHide answer
Answer: A. int arr[] = {1,2,3,4,5};
82. How can you find the number of elements in a one-dimensional array in C?
Show answerHide answer
Answer: C. sizeof(arr)/sizeof(arr[0])
83. What is the syntax for declaring a multidimensional array in C?
Show answerHide answer
Answer: D. int arr[...][...][...];
84. What is the use of the strlen() function in C when working with arrays?
Show answerHide answer
Answer: C. To find the length of a string
85. What is a one-dimensional array in C?
Show answerHide answer
Answer: A. A set of values of the same data type stored in a contiguous block of memory
86. How can you access the value at the third position of a one-dimensional array named "array"?
Show answerHide answer
Answer: A. array[2]
87. What is a two-dimensional array in C?
Show answerHide answer
Answer: A. An array of arrays
88. How can you access the value at the first row and second column of a two-dimensional array named "array"?
Show answerHide answer
Answer: A. array[0][1]
89. What is a multidimensional array in C?
Show answerHide answer
Answer: A. An array of arrays of arrays
90. What is the difference between a one-dimensional array and a two-dimensional array in C?
Show answerHide answer
Answer: A. A two-dimensional array has more dimensions than a one-dimensional array
91. What is a string in C programming?
Show answerHide answer
Answer: B. An array of characters
92. How can you find the length of a string in C programming?
Show answerHide answer
Answer: B. By using the strlen() function
93. How can you concatenate two strings in C programming?
Show answerHide answer
Answer: B. By using the strcat() function
94. What does the strcpy() function do in C programming?
Show answerHide answer
Answer: A. Copies one string to another
95. What is the difference between the strcpy() and strcat() functions in C programming?
Show answerHide answer
Answer: A. strcpy() copies one string to another, while strcat() concatenates two strings
96. How can you compare two strings in C programming?
Show answerHide answer
Answer: A. By using the strcmp() function
97. What is the return value of the strcmp() function when two strings are equal?
Show answerHide answer
Answer: A. 0
98. What is the return value of the strcmp() function when the first string is greater than the second string?
Show answerHide answer
Answer: B. 1
99. What is the return value of the strcmp() function when the first string is less than the second string?
Show answerHide answer
Answer: C. -1
100. How can you reverse a string in C programming?
Show answerHide answer
Answer: B. By using a loop and swapping characters
101. What is the purpose of the strcat() function in C programming?
Show answerHide answer
Answer: B. To concatenate two strings.
102. What is the purpose of the strcmp() function in C programming?
Show answerHide answer
Answer: D. To compare two strings.
103. What is the purpose of the strcpy() function in C programming?
Show answerHide answer
Answer: A. To copy a string to another string.
104. What is the purpose of the strlen() function in C programming?
Show answerHide answer
Answer: C. To find the length of a string.
105. What is the purpose of the strstr() function in C programming?
Show answerHide answer
Answer: A. To find a substring in a string.
106. How can you reverse a string in C programming?
Show answerHide answer
Answer: B. By using a loop and swapping characters.
107. How can you convert a string to uppercase in C programming?
Show answerHide answer
Answer: B. By using a loop and converting each character.
108. How can you convert a string to lowercase in C programming?
Show answerHide answer
Answer: B. By using a loop and converting each character.
109. What is the purpose of the sprintf() function in C programming?
Show answerHide answer
Answer: A. To format and store a string in a buffer.
110. What is the purpose of the sscanf() function in C programming?
Show answerHide answer
Answer: A. To read formatted input from a string.
3.2 Pointers, structures and data files in C
122 questions · ACtE0302
111. What does int *p = NULL mean in C++?
Aasadh 2081 examShow hintHide hint
NULL represents no valid address.
Show answerHide answer
Answer: A. p is a null pointer
p is a null pointer pointing to no valid memory address.
112. What is the syntax for binary file writing in C?
Show hintHide hint
Binary mode adds 'b' to the mode string.
Show answerHide answer
Answer: B. fp=fopen("abc.txt","wb");
Correct syntax for binary write mode: fopen("filename", "wb") where 'w' means write and 'b' means binary.
113. Which C function finds current position in file?
Show hintHide hint
Returns file pointer position.
Show answerHide answer
Answer: B. ftell()
ftell() returns the current position of the file pointer in the file.
114. What does fwrite(str, strlen(str) + 1, 1, filePointer) do?
Show hintHide hint
strlen(str) + 1 includes null terminator.
Show answerHide answer
Answer: B. Prints all chars including null
strlen(str) + 1 includes null character, so fwrite writes entire string with null terminator.
115. How do arrays and pointers relate in C?
Show hintHide hint
Consider how arr[i] relates to *(arr+i).
Show answerHide answer
Answer: B. Arrays decay to pointers when used in expressions
Arrays and pointers are intimately related in C. Array name represents address of first element (except with sizeof or &). When array appears in expression, it automatically converts (decays) to pointer to first element. Example: int arr[5]; declares array, arr is equivalent to &arr[0]. Pointer arithmetic: *(arr+i) is equivalent to arr[i]. Accessing: arr[3] translates to *(arr+3). This relationship is why functions receiving arrays get pointers: void func(int arr[]) is identical to void func(int *arr) - both receive pointer to array. Multi-dimensional arrays: int matrix[3][4]; matrix is pointer to array of 4 ints, matrix[i] is pointer to int, matrix[i][j] is int. Differences: sizeof(arr) gives total array size; sizeof(&arr[0]) gives pointer size. & on array: &arr gives pointer to whole array (type int (*)[5] for int arr[5]), not same as arr (type int*). String arrays: "hello" is array decaying to pointer to 'h'. Using this decay concept: for(int *p = arr; p < arr+5; p++) iterates through array using pointers. Understanding this relationship crucial for pointer arithmetic, function parameters, dynamic allocation patterns. Modern trend: using pointers more than arrays for flexibility, but understanding both essential.
116. What is pointer arithmetic in C?
Show hintHide hint
When you do ptr+1, ptr-2, etc., what actually happens to the address?
Show answerHide answer
Answer: B. Mathematical operations on addresses stored in pointers
Pointer arithmetic involves mathematical operations on pointer values (addresses). Operations: increment (ptr++), decrement (ptr--), addition (ptr+n), subtraction (ptr-n), comparison (ptr1 < ptr2), difference (ptr1-ptr2). Crucial: increment/decrement scale by data type size. For int *p, p++ moves pointer by sizeof(int) bytes (usually 4), not 1 byte. Example: if p = 1000 (address), p++ becomes 1004 for int pointer. This scaling automatic based on pointer type. Pointer difference: (ptr2 - ptr1) gives number of elements between, not bytes. Uses: array traversal with pointers, dynamic array management, building linked lists. Allowed operations: ++ (increment), -- (decrement), +n (advance n positions), -n (retreat n positions), comparison (<, >, <=, >=), subtraction (two pointers), +=, -=. Disallowed: multiplication, division, addition of two pointers. Valid: comparison of pointers from same array, subtraction of pointers from same array. Out-of-bounds arithmetic: technically allowed but undefined behavior if dereferenced. Array iteration: for(int *p = arr; p < arr+5; ++p) uses pointer arithmetic. Void pointers: void *p cannot be incremented (don't know size). Understanding scaling essential for correct pointer operations and avoiding off-by-one errors.
117. How are pointers and arrays passed to functions?
Show hintHide hint
When you pass arr[] to function, what does it actually receive?
Show answerHide answer
Answer: B. Both decay to pointers, function receives address
Arrays and pointers passed to functions share a common mechanism: arrays decay to pointers to first element. Function declaration: void func(int arr[10]) is identical to void func(int arr[]) and void func(int *arr) - all receive pointer to array's first element. This means: (1) Array size info lost in function - must pass size separately or use sentinel. (2) Modifications in function affect original array (passed by reference effectively). (3) No array copying occurs - efficient even for large arrays. Example: int arr[100]; func(arr) passes &arr[0], not entire array. For comparison: structs passed by value (copied) unless pointer passed, arrays always by reference. Multi-dimensional arrays: void func(int arr[][5]) receives pointer to array of 5 ints. Other dimensions required: void func(int (*ptr)[5][10]) for 3D array. Function pointers: void (*func)(int arr[]) can point to function receiving array. Return considerations: cannot return array from function (cannot create array on stack of unknown size), must return pointer to dynamically allocated array. For 2D arrays: void func(int **arr) works for ragged arrays, void func(int arr[][5]) for rectangular arrays. Understanding this decay crucial for function parameter design and memory safety.
118. What does passing pointers to functions enable?
Show hintHide hint
If you want function to modify original variable or return multiple values, what do you pass?
Show answerHide answer
Answer: B. Multiple return values and variable modification
Passing pointers to functions enables multiple important capabilities: (1) Modifying caller's variables: void swap(int *a, int *b) can modify both arguments by dereferencing. (2) Multiple return values: instead of single return, use output parameters (pointers). Example: void divmod(int a, int b, int *quo, int *rem) returns quotient and remainder through pointers. (3) Dynamic memory allocation: allocate in function, pass pointer back. (4) Avoiding large data copies: pass pointer to large structure instead of copying entire structure. (5) Building complex data structures: linked lists, trees use pointers extensively. (6) Callback functions: pass function pointer for flexible function behavior. Pointer parameter patterns: input parameters (const int *), output parameters (int *), input-output (modify and use). Example: void double_it(int *x) { *x = *x * 2; } modifies original variable. Contrast with pass-by-value: void double_it(int x) { x = x * 2; } modifies only local copy. Dangers: null pointer dereference, dangling pointers (freed memory), uninitialized pointers. Best practices: validate pointer before use, use const for input-only pointers, document which parameters are output. Modern C: use const pointers for read-only, document intent clearly. In C++, references often preferred over pointers for cleaner syntax, but concept similar.
119. What is the difference between struct and union in C?
Show hintHide hint
Think about memory layout - do all members get their own space?
Show answerHide answer
Answer: B. Struct allocates separate memory for each member, union shares memory
Struct vs Union - fundamental difference in memory allocation: Struct: allocates memory for ALL members. struct Point { int x; int y; } has size = sizeof(int) + sizeof(int). Each member independent, all exist simultaneously. Access: point.x and point.y both valid. Union: members share same memory location. union Data { int i; float f; } has size = max(sizeof(int), sizeof(float)). Only one member can hold value at a time. Access: data.i or data.f, but setting one overwrites other. Use cases - Struct: grouping related data (person name, age, address). Union: memory-constrained systems, hardware registers (different data types in same location), variant data types. Example: network packet header (fixed fields in struct) vs hardware register (different interpretations in union). Padding/alignment: struct size ≥ sum of members (compiler adds padding), union size = largest member. Union efficiency: saves memory (only one variant active), but requires careful management. Nested: union within struct or vice versa possible. Sizeof: struct A { int x; char c; } likely 8 bytes (int 4 + char 1 + padding 3). Union U { int x; char c; } size 4 (max of int/char). Accessing wrong union member returns garbage - type safety burden on programmer. C doesn't enforce which union member is active. Tagged unions (struct with int tag and union) provide safe variant handling. Useful in interpreters, protocol implementations, embedded systems.
120. What is an array of structures in C?
Show hintHide hint
Like a table where each row is a structure instance.
Show answerHide answer
Answer: B. Array where each element is a structure
Array of structures: array where each element is a structure instance. Declaration: struct Student { char name[50]; int id; float gpa; } students[100]; creates array of 100 Student structures. Memory: contiguous block where each Student occupies sizeof(struct Student) bytes. Accessing: students[0].name accesses name of first student, students[i].id accesses id of i-th student. Nested: structure already contains arrays (name[50] is array within structure). Initialization: struct Student s[3] = { {"Alice", 1, 3.8}, {"Bob", 2, 3.5}, {"Charlie", 3, 3.9} }; Iteration: for(int i=0; i<100; i++) process_student(&students[i]); Passing: arrays decay to pointers, so function receives struct Student *arr. Sorting: qsort(students, 100, sizeof(struct Student), compare_func) sorts array. Comparison function: int compare_func(const void *a, const void *b) { return ((struct Student*)a)->id - ((struct Student*)b)->id; }. Dynamic allocation: struct Student *arr = malloc(n * sizeof(struct Student)); for flexible sizing. Advantages: organize related data (each student's complete info), efficient storage (contiguous memory), cache-friendly access. Common in: databases (records), game development (entities), scientific computing (datasets). Understanding memory layout crucial for pointer arithmetic and efficient access patterns.
121. How are structures passed to functions?
Show hintHide hint
What happens - does entire structure get copied or just address?
Show answerHide answer
Answer: B. Structures passed by value by default, by pointer if specified
Structures passed to functions by value by default - entire structure copied to function's stack frame. void process(struct Student s) receives copy of s, modifications don't affect original. For large structures, this copying is inefficient. Alternative: pass by pointer - void process(struct Student *s) receives address only, modifies original. Pointer parameters: void set_id(struct Student *s, int id) { s->id = id; } modifies original through pointer. Accessing pointer members: use -> operator (s->id) instead of . operator (s.id). Efficiency: for structures > 2-3 pointers, pass by pointer preferred. Const pointers: void display(const struct Student *s) for read-only access, compiler prevents modifications. Return values: functions can return structures by value (struct Student create_student()) but inefficient for large structures. Pattern: for output parameters, use pointers (void func(struct Student *out)). Dynamic allocation: struct Student *s = malloc(sizeof(struct Student)); then pass s to functions. Array of structures: arrays passed as pointers automatically (struct Student arr[100] becomes struct Student *arr in function). Memory consideration: stack limited, large structure copies waste stack space. Rule of thumb: pass primitive types by value, structures/arrays by pointer. Modern practice: C++ uses references for cleaner syntax, but concept similar. Understanding calling convention crucial for performance and correctness.
122. What is the relationship between structure and pointer in C?
Show hintHide hint
How do you work with structures dynamically? How do you access structure members through pointers?
Show answerHide answer
Answer: B. Pointers point to structures, enabling dynamic allocation and modification
Structures and pointers closely related: pointers point to structures, enabling dynamic allocation, flexible data structures, and efficient passing. Pointer to structure: struct Student *ptr; or struct Student *ptr = &s; Accessing members: ptr->field (equivalent to (*ptr).field). Arrow operator -> preferred for readability. Dynamic allocation: struct Student *ptr = malloc(sizeof(struct Student)); ptr->id = 1; creates structure on heap. Linked structures: struct Node { int data; struct Node *next; } builds linked lists. Self-referential structures use pointers to own type. Pointer arrays: struct Student *students[100] - array of pointers, flexible sizing. Dynamic array: struct Student **arr = malloc(n * sizeof(struct Student*)); for array of pointers to structures. Typedef for cleaner syntax: typedef struct { int x; int y; } Point; then Point *p; Advantages: dynamic memory (allocate/deallocate as needed), data structure building (linked lists, trees), efficient passing (no copying). Memory layout: structure pointer stores address, accessing member calculates offset. Null check essential: if(ptr != NULL) before accessing members. Linked structures: struct Node { int data; struct Node *left; struct Node *right; } enables trees. Common pattern: struct with function pointers for object-oriented behavior. Understanding pointer-structure relationship crucial for building complex data structures and dynamic memory management.
123. What are file operations in C?
Show hintHide hint
Think about complete file lifecycle - from opening to closing.
Show answerHide answer
Answer: C. Opening, reading, writing, and closing files
File operations involve complete file handling cycle: (1) Opening: FILE *fp = fopen("file.txt", "r") opens file (modes: r-read, w-write, a-append, r+, w+, a+); (2) Reading: fgetc(fp) reads character, fgets(line, size, fp) reads line, fread(buffer, size, count, fp) reads binary; (3) Writing: fputc(c, fp) writes character, fputs(line, fp) writes line, fwrite(buffer, size, count, fp) writes binary; (4) Closing: fclose(fp) closes file, flushing buffers. File pointer: FILE * represents stream, maintains file state (position, EOF, error). Status checking: feof(fp) checks end-of-file, ferror(fp) checks errors, fgetc returns EOF (-1) at end. Seeking: fseek(fp, offset, origin) positions pointer (origins: SEEK_SET start, SEEK_CUR current, SEEK_END end). ftell(fp) returns current position. rewind(fp) goes to start. Modes: text mode handles newline conversion, binary mode preserves exact bytes. Common patterns: while(!feof(fp)) { /* read */ } or while(fgets(line, sizeof(line), fp)) { /* process */ }. Error handling: check return values, validate file opened successfully. File operations essential for data persistence, logging, configuration files. Binary vs Text: text for human-readable data, binary for fixed-size records, images, executables. Safety: always close files, even on error (use cleanup code or close in finally equivalent). Resource leaks: unclosed files waste OS resources. File I/O slower than memory access - buffer strategically for performance.
124. What is sequential access to files in C?
Show hintHide hint
You process file data in order, not jumping around - like reading book page by page.
Show answerHide answer
Answer: B. Reading/writing file from start to end in order
Sequential access: reading/writing file data from beginning to end in order, without skipping or jumping. Suitable for: text files, log files, data streams where linear processing sufficient. Example: FILE *fp = fopen("data.txt", "r"); while(fgets(line, sizeof(line), fp)) { process(line); } reads entire file sequentially. Characteristics: simple, efficient for full-file processing, natural for streaming. Operations: fgetc (next character), fgets (next line), fread (next block). Position: always moves forward, fseek seldom used. Search: to find specific record, must read from start (O(n) complexity). Advantages: straightforward logic, suitable for large files (memory-efficient streaming), commonly used for text processing. Disadvantages: inefficient for finding specific records, must re-read from start for multiple passes. Contrast with random access: jumping to specific record using fseek. Performance: sequential often faster than random due to disk head positioning and prefetching. Common uses: log file analysis, data import/export, stream processing, ETL (extract-transform-load). Implementation: maintain state variables for custom record format. Combined approach: sequential for parsing, random for specific lookups if structure known. Error handling: feof(), ferror() for end-of-file and error detection. Understanding sequential vs random access helps choose appropriate file handling strategy.
125. What is random access to files in C?
Show hintHide hint
You can jump to specific positions in file using fseek.
Show answerHide answer
Answer: B. Using fseek to position file pointer at specific location
Random access: jumping directly to specific file position without reading from start. Enabled by fseek(): fseek(fp, offset, whence) positions file pointer. Whence values: SEEK_SET (beginning, offset 0), SEEK_CUR (current position), SEEK_END (end of file). Examples: fseek(fp, 100, SEEK_SET) moves to byte 100; fseek(fp, -10, SEEK_CUR) moves back 10 bytes; fseek(fp, 0, SEEK_END) moves to end. Fixed-record files: if records are fixed size (e.g., 256 bytes each), random access efficient: fseek(fp, record_num * 256, SEEK_SET) jumps directly to record. ftell(): returns current position (bytes from start). rewind(): equivalent to fseek(fp, 0, SEEK_SET). Binary files: random access natural, text files problematic (variable-length records). Use case: database files, lookup by record number, editing specific portion. Advantages: O(1) access to any record (vs O(n) sequential), efficient for large files with specific record access. Disadvantages: requires fixed structure or index, not suitable for streaming. Typical pattern: open file, fseek to position, fread block, modify, fseek to original position, fwrite. Implementation detail: some systems (non-seekable) don't support fseek (pipes, sockets). Error checking: fseek returns 0 on success, non-zero on failure. Index files: separate index stores record positions for efficient lookup. Comparison with sequential: sequential simple but slow for specific records; random fast for lookups but requires structure. Modern databases use both: indexes (fast lookup) and sequential scans (bulk operations).
126. What is the size of a pointer in C?
NEC model setShow hintHide hint
Pointer size varies with the operating system and processor architecture. Think about 32-bit vs 64-bit systems.
Show answerHide answer
Answer: D. It depends on the system architecture
The size of a pointer in C depends on the system architecture. On 32-bit systems, pointers are typically 4 bytes (32 bits), while on 64-bit systems, pointers are typically 8 bytes (64 bits). This is because pointers store memory addresses, and the address space size determines pointer size. A pointer must be large enough to address all available memory. On a 32-bit system with 4 GB maximum addressable memory, 4 bytes (32 bits) are sufficient. On a 64-bit system, 8 bytes are needed for larger address spaces. The size() operator can determine pointer size: printf("%zu", sizeof(int*)); typically outputs 4 (on 32-bit) or 8 (on 64-bit). Specialized architectures may use different pointer sizes. This architecture-dependence is important when writing portable C code.
127. What is the purpose of the fscanf() function in C programming?
Show answerHide answer
Answer: C. To input/output data to/from a file
128. What is the difference between scanf() and fscanf() in C?
Show answerHide answer
Answer: A. scanf() reads from the standard input and fscanf() reads from a file
129. What is the purpose of the fopen() function in C?
Show answerHide answer
Answer: A. To open a file for reading
130. What is the purpose of the fclose() function in C?
Show answerHide answer
Answer: C. To close a file that was opened for reading and writing
131. What is the difference between fprintf() and sprintf() in C?
Show answerHide answer
Answer: A. fprintf() writes to a file and sprintf() writes to a string
132. What is the purpose of the "malloc" function in C programming?
Show answerHide answer
Answer: B. To allocate memory
133. What is the purpose of the "free" function in C programming?
Show answerHide answer
Answer: B. To free memory
134. What is the difference between an array and a pointer in C programming?
Show answerHide answer
Answer: A. An array is a set of values stored in a contiguous block of memory, while a pointer is a variable that stores the address of another variable
135. What is the output of the following code? int a = 10; int *p = &a; printf("%p", p);
Show answerHide answer
Answer: C. Address of a
136. What is the output of the following code? int a = 10; int *p = &a; printf("%d", *p);
Show answerHide answer
Answer: A. 10
137. What is the correct way to declare a pointer to a character in C?
Show answerHide answer
Answer: A. char *str;
138. What is the output of the following code? int arr[5] = {1, 2, 3, 4, 5}; int *p = arr; printf("%d", *(p+3));
Show answerHide answer
Answer: A. 4
139. What is the output of the following code? int arr[5] = {1, 2, 3, 4, 5}; int *p = arr + 2; printf("%d", *(p-1));
Show answerHide answer
Answer: A. 2
140. What is the output of the following code? int a = 10; int *p = &a; int **q = &p; printf("%d", **q);
Show answerHide answer
Answer: A. 10
141. Which of the following is a valid way to declare a pointer to an integer array of size 5?
Show answerHide answer
Answer: A. int (*arr)[5];
142. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr + 1; printf("%d", *(p--));
Show answerHide answer
Answer: A. 2
143. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr + 2; printf("%d", *(--p));
Show answerHide answer
Answer: A. 2
144. What is the output of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *p++);
Show answerHide answer
Answer: A. 1
145. Which of the following is true about pointer arithmetic in C?
Show answerHide answer
Answer: A. Addition and subtraction operations can be performed on pointers
146. If 'ptr' is a pointer to an integer variable, what will be the output of the following code? printf("%d", ptr+1);
Show answerHide answer
Answer: D. The value of the integer variable ptr+1 is pointing to
147. If 'ptr' is a pointer to an integer variable, what will be the output of the following code? printf("%d", *(ptr+1));
Show answerHide answer
Answer: D. The value of the integer variable ptr+1 is pointing to
148. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *(p++));
Show answerHide answer
Answer: A. 1
149. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *(p-2));
Show answerHide answer
Answer: None of the options
The source’s answer, “Undefined”, is not one of the options.
150. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *(p+4));
Show answerHide answer
Answer: D. Undefined
151. What is the result of the following code? int a = 5, b = 10; int *p1 = &a; int *p2 = &b; int *temp; temp = p1; p1 = p2; p2 = temp; printf("%d %d", *p1, *p2);
Show answerHide answer
Answer: B. 10 5
152. What is the output of the following code? int a = 10; int *p = &a; (*p)++; printf("%d", a);
Show answerHide answer
Answer: C. 11
153. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr + 2; printf("%d", p[-1]);
Show answerHide answer
Answer: B. 2
154. What is the result of the following code? int arr[] = {1, 2, 3, 4, 5}; int *p = arr + 2; printf("%d", *p);
Show answerHide answer
Answer: C. 3
155. What is the data type of the pointer variable in the following code? char *p;
Show answerHide answer
Answer: A. char
156. What is the result of the following code? int x = 10, y = 20, z; int *p = &x, *q = &y; z = *p + (*q)++; printf("%d %d %d", x, y, z);
Show answerHide answer
Answer: None of the options
The source’s answer, “10 21 30”, is not one of the options.
157. What is the result of the following code? int arr[] = {1, 2, 3, 4, 5}; int *p = &arr[3]; printf("%d", *(p-2));
Show answerHide answer
Answer: B. 2
158. What is the result of the following code? int arr[] = {1, 2, 3, 4, 5}; int *p = arr; printf("%d", *(++p));
Show answerHide answer
Answer: B. 2
159. What is the result of the following code? int arr[] = {1, 2, 3, 4, 5}; int *p = arr; printf("%d", *(p+2));
Show answerHide answer
Answer: C. 3
160. Which of the following is true about structures in C?
Show answerHide answer
Answer: B. Structures can contain variables of different data types
161. How do you declare a structure in C?
Show answerHide answer
Answer: C. struct person { char name[20]; int age; };
162. Which of the following is used to access the members of a structure?
Show answerHide answer
Answer: B. .
163. How do you assign values to members of a structure in C?
Show answerHide answer
Answer: A. using the assignment operator
164. What is the purpose of typedef in C structures?
Show answerHide answer
Answer: B. to define a new data type
165. Which of the following statements is true regarding the size of a structure in C?
Show answerHide answer
Answer: A. The size of a structure is the sum of the sizes of its members
166. What is the operator used to dynamically allocate memory for a structure in C?
Show answerHide answer
Answer: D. malloc()
167. What is the operator used to deallocate memory allocated for a structure in C?
Show answerHide answer
Answer: C. free()
168. What is the purpose of a union in C?
Show answerHide answer
Answer: D. to share the same memory location for different data types
169. Which of the following is true about nested structures in C?
Show answerHide answer
Answer: C. Nested structures can be defined inside another structure
170. What is a structure in C programming?
Show answerHide answer
Answer: A. A data type that groups variables of different types
171. What is the correct syntax to access a member of a nested structure?
Show answerHide answer
Answer: A. outer_structure.inner_structure.member_name
172. What is the size of an empty structure in C programming?
Show answerHide answer
Answer: A. 0 bytes
173. Which of the following is not a valid way to initialize a structure variable in C programming?
Show answerHide answer
Answer: D. struct book b; b = {"C Programming", "John Doe", 100};
174. What is a nested structure in C programming?
Show answerHide answer
Answer: B. A structure that is defined inside another structure
175. In C programming, which keyword is used to define a structure?
Show answerHide answer
Answer: D. struct
176. Which of the following statements is true about passing a structure to a function in C programming?
Show answerHide answer
Answer: B. Structures are passed by value to a function.
177. Which of the following is not a valid way to declare a pointer to a structure in C programming?
Show answerHide answer
Answer: A. struct *book b;
178. What is the keyword used to access the address of a structure variable in C programming?
Show answerHide answer
Answer: A. &
179. What is the main difference between a structure and a union in C programming?
Show answerHide answer
Answer: A. A structure allows for multiple members to be accessed at once, while a union only allows for one member to be accessed at a time.
180. Which of the following is the correct way to access a structure member using a pointer to a structure?
Show answerHide answer
Answer: A. structure_pointer->member_name
181. What is the difference between passing a structure by value and passing a structure by pointer in C?
Show answerHide answer
Answer: A. When a structure is passed by value, any modifications made to it in the function are lost when the function returns. When a structure is passed by pointer, the modifications are retained.
182. In a union, how much memory is allocated for the union itself?
Show answerHide answer
Answer: A. The size of the largest member
183. What is the main advantage of using a union over a structure?
Show answerHide answer
Answer: A. It uses less memory
184. In a union, can two or more members be accessed simultaneously?
Show answerHide answer
Answer: C. No, only one member can be accessed at a time
185. What is the purpose of declaring a bit field in a structure?
Show answerHide answer
Answer: A. To save memory
186. Can a structure or union contain a member that is itself a structure or union?
Show answerHide answer
Answer: A. Yes, there is no restriction on the type of members
187. How do you access a member of a structure or union using a pointer?
Show answerHide answer
Answer: A. -> operator
188. In a union, what is the value of a member that was not explicitly set?
Show answerHide answer
Answer: B. Garbage value
189. Which of the following statements is true about the size of a structure or union in C programming?
Show answerHide answer
Answer: C. The size of a structure or union depends on the alignment requirements of its members
190. What is the difference between a structure and a union in C programming?
Show answerHide answer
Answer: A. A structure allows for multiple members to be accessed at once, while a union only allows for one member to be accessed at a time.
191. What is the size of a structure in C programming?
Show answerHide answer
Answer: A. The size of a structure is equal to the sum of the sizes of its members.
192. How do you access a member of a structure in C programming?
Show answerHide answer
Answer: A. Using the dot (.) operator.
193. What is the keyword used to define a structure in C programming?
Show answerHide answer
Answer: A. struct
194. Which of the following statements about unions is true in C programming?
Show answerHide answer
Answer: A. Unions can contain members of different types.
195. What is the difference between a structure and a typedef struct in C programming?
Show answerHide answer
Answer: C. Typedef struct is a faster way to create a new structure type.
196. Can a structure contain a pointer to itself in C programming?
Show answerHide answer
Answer: A. Yes
197. Which of the following statements is true about the alignment of structure members in C programming?
Show answerHide answer
Answer: B. Members of a structure are aligned based on their size and type.
198. What is the purpose of a bit-field in a structure in C programming?
Show answerHide answer
Answer: B. To create a member that is only one bit in size.
199. Which of the following is an example of a valid structure declaration in C programming?
Show answerHide answer
Answer: A. struct person {char name[50]; int age;}
200. What is the syntax for declaring an array of structures in C?
Show answerHide answer
Answer: A. struct array_name[size];
201. In C programming, how do you access a particular member of a structure within an array of structures?
Show answerHide answer
Answer: A. array_name[index].member_name
202. What is the purpose of using an array of structures in C?
Show answerHide answer
Answer: A. To group similar data types together in a single entity.
203. How do you initialize an array of structures in C?
Show answerHide answer
Answer: A. By setting each member of the array individually.
204. What is the maximum number of dimensions that an array of structures can have in C?
Show answerHide answer
Answer: D. There is no limit
205. What is the purpose of using a typedef with an array of structures in C?
Show answerHide answer
Answer: D. To create a new data type.
206. Which of the following is a valid way to access a member of a structure within an array of structures in C?
Show answerHide answer
Answer: B. array_name[index].member_name
207. How do you declare a pointer to an array of structures in C?
Show answerHide answer
Answer: B. struct (*array_name)[size]; or D. struct (*array_name)[size];
Two options have the same text; both match the source’s answer.
208. In C programming, how do you access a particular member of a structure within a pointer to an array of structures?
Show answerHide answer
Answer: D. pointer_name[index].member_name
209. How do you dynamically allocate memory for an array of structures in C?
Show answerHide answer
Answer: A. By using the malloc() function.
210. How do you declare an array of structures in C?
Show answerHide answer
Answer: C. struct Array[] = {...}
211. What is the correct syntax for accessing the member variable "age" of the first structure in an array of structures named "people"?
Show answerHide answer
Answer: B. people[0].age
212. What is the maximum number of elements that can be stored in an array of structures?
Show answerHide answer
Answer: D. The maximum number is determined by the amount of available memory
213. Which of the following is a valid way to initialize an array of structures in C?
Show answerHide answer
Answer: A. struct person[] = {{1, "John"}, {2, "Jane"}}
214. What is the size of the following structure? struct student { char name[50]; int age; float gpa; };
Show answerHide answer
Answer: B. 60 bytes
215. Which operator is used to access a member of a structure through a pointer to the structure?
Show answerHide answer
Answer: B. ->
216. What is the correct syntax for declaring a pointer to a structure?
Show answerHide answer
Answer: D. struct person *p;
217. How can you dynamically allocate memory for an array of structures in C?
Show answerHide answer
Answer: A. struct array = (struct *) malloc(sizeof(struct) * n);
218. How can you access the last element in an array of structures with n elements?
Show answerHide answer
Answer: B. arr[n-1]
219. Which of the following is an advantage of using an array of structures instead of multiple individual structures?
Show answerHide answer
Answer: D. All of the above
220. What is the syntax for passing a structure to a function in C?
Show answerHide answer
Answer: A. function(struct s)
221. How do you declare a function that takes a structure as an argument in C?
Show answerHide answer
Answer: A. void myFunction(struct myStruct);
222. Can you pass an array of structures to a function in C?
Show answerHide answer
Answer: B. Yes, you can pass an array of structures to a function using a pointer
223. How does passing a structure to a function by reference (i.e. using a pointer) differ from passing it by value?
Show answerHide answer
Answer: B. Passing by reference allows the function to modify the original structure, while passing by value does not
224. What is the advantage of passing a structure to a function by reference instead of by value?
Show answerHide answer
Answer: A. Passing by reference is faster
225. How do you access a structure member inside a function that takes a pointer to the structure as an argument?
Show answerHide answer
Answer: D. s->member
226. What is the correct way to pass a structure to a function by reference?
Show answerHide answer
Answer: C. function(&s)
227. Can a function return a structure in C?
Show answerHide answer
Answer: C. Yes, by returning a pointer to the structure
228. How do you initialize a structure variable inside a function?
Show answerHide answer
Answer: A. struct s = {...}
229. What is the advantage of passing a structure by pointer to a function in C?
Show answerHide answer
Answer: C. It allows the function to modify the original structure
230. Which of the following is the correct syntax to pass a structure by value to a function in C?
Show answerHide answer
Answer: C. function_name(structure_variable)
231. Which of the following is the correct syntax to pass a structure by reference to a function in C?
Show answerHide answer
Answer: A. function_name(&structure_variable)
232. Which of the following is the correct syntax to pass a structure by pointer to a function in C?
Show answerHide answer
Answer: C. function_name(structure_pointer)
3.3 C++ language constructs with objects and classes
225 questions · ACtE0303
233. Can two functions in C++ have the same name and parameters?
Show hintHide hint
Namespaces provide scope separation.
Show answerHide answer
Answer: B. Yes, if in different namespaces
Functions can have same name and parameters if in different namespaces, due to namespace scope separation.
234. What is default access specifier for C++ class members?
Show hintHide hint
Unless explicitly specified otherwise.
Show answerHide answer
Answer: C. Private
By default, all class members in C++ are private unless declared as public or protected.
235. What namespace feature does C++ provide?
Show hintHide hint
Global scope feature.
Show answerHide answer
Answer: A. Can be used anywhere
Namespaces provide scope for identifiers and can be used throughout the program.
236. How to alias namespace in C++?
Show hintHide hint
Create alias for namespace.
Show answerHide answer
Answer: C. namespace B = A
Correct syntax: namespace new_name = existing_namespace; creates alias.
237. What is static variable in C++?
Show hintHide hint
Retains value.
Show answerHide answer
Answer: B. Persists between calls
Static variables retain their value between function calls and are initialized only once.
238. What are namespaces in C++?
Show hintHide hint
Multiple libraries might have function with same name - how do you avoid collision?
Show answerHide answer
Answer: B. Scopes for declaring names to avoid conflicts
Namespaces: organize code into logical groups, avoiding name conflicts in large projects. Declaration: namespace MyLib { function definitions, class definitions, variables }. Prevents collisions: two libraries with function calc() can coexist in different namespaces. Accessing: MyLib::calc() or using namespace MyLib; then calc(). Nested namespaces: namespace A { namespace B { class C { }; } } accessed as A::B::C. Using statement: using namespace std; brings std namespace into current scope (avoid at global scope in headers - causes pollution). Using declaration: using std::cout; imports specific identifier. Scope: identifiers in namespace not visible outside unless qualified or using declaration. Example: namespace math { int square(int x) { return x*x; } } then math::square(5) or using math::square; square(5). Standard library: std namespace contains cout, cin, vector, etc. Alias: namespace fs = std::filesystem; shortens names. Unnamed namespace: namespace { /* internal linkage */ } makes identifiers private to translation unit (internal linkage). Advantages: organize large codebases, prevent name pollution, support versioning (different lib versions in different namespaces). Best practice: put library code in namespace, avoid using namespace MyLib; at global scope. Anonymous namespaces more preferred than static for internal linkage. C doesn't have namespaces (uses module/header structure instead). Understanding namespace scope crucial for managing large C++ projects and library integration.
239. What is function overloading in C++?
Show hintHide hint
Can you have multiple add() functions that work differently?
Show answerHide answer
Answer: B. Multiple functions with same name but different parameters
Function overloading: multiple functions with same name differentiated by parameter list (number, type, or order). Compiler generates unique internal names (name mangling) for each version. Examples: int add(int a, int b) { return a+b; } and double add(double a, double b) { return a+b; } and string add(string a, string b) { return a+b; }. Selection: compiler chooses based on argument types: add(3, 5) calls int version, add(3.5, 2.1) calls double version. Rules: (1) Parameter count must differ or parameter types different. (2) Return type alone insufficient (can't overload on return type only). (3) const qualifier on parameters: const int* vs int* treated as different. Parameter order matters: void foo(int, double) differs from void foo(double, int). Coercion: compiler tries implicit conversions if exact match not found. Ambiguity: foo(5, 5) could match foo(int, int) or foo(double, double) if implicit conversion possible - compiler rejects as ambiguous. Default parameters: foo(int a, int b = 0) with foo(int) allows calling with one argument. Advantages: same operation, intuitive interface (add works for int, double, string), cleaner code. Disadvantages: debugging harder (which version called?), compile-time complexity, risk of ambiguity. Prefix/postfix operators: operator++ can be overloaded as prefix vs postfix using dummy int parameter. Virtual functions: overloading differs from overriding (inheritance). Can combine overloading with inheritance. Modern practice: favor overloading for related operations, templates for generic code. Understanding overloading essential for C++ API design and avoiding errors.
240. What are inline functions in C++?
Show hintHide hint
Compiler optimization that replaces function call with function body.
Show answerHide answer
Answer: B. Functions expanding at call site to improve performance
Inline functions: compiler replaces function call with function body directly, eliminating function call overhead (parameter passing, stack frame creation, return). Declaration: inline return_type function_name(parameters) { body }; Implicit inline: member functions defined in class body automatically inline. Advantages: eliminates call overhead (beneficial for small functions called frequently), enables compiler optimizations, can be faster than macros (type-safe). Disadvantages: code size increase (body duplicated at each call site), compilation slower, not suitable for large functions, implementation visible to users (header files), can't recurse. When beneficial: small functions (1-3 lines) called frequently (loops, callbacks). When inefficient: large functions, recursive functions, functions called rarely. Compiler discretion: inline is hint, compiler may ignore for complex functions. Modern practice: compiler often makes inlining decisions better than hints. Rule of thumb: let compiler decide (don't use inline keyword unless profiling shows benefit). Template functions: implicitly inline (needed in header files). Lambda functions: automatically inline. Recursive inline: compiler typically expands limited times. Virtual functions: virtual prevents inlining (runtime dispatch). Debugging: inlined functions harder to debug (breakpoints, stepping). Performance profiling: measure before optimizing with inline. Example: inline int square(int x) { return x*x; } called 1000 times avoids 1000 function call overheads. Understanding inlining crucial for performance tuning without sacrificing code organization.
241. What are default arguments in C++ functions?
Show hintHide hint
void func(int x = 5) - what happens if you call func() without arguments?
Show answerHide answer
Answer: B. Parameter values used if argument not provided
Default arguments: parameter values used when argument not provided in function call. Declaration: int multiply(int a, int b = 2) { return a * b; }. Call: multiply(5) uses b=2, multiply(5, 3) uses b=3. Rules: (1) defaults must be rightmost parameters - int func(int a = 1, int b) invalid; (2) only in declaration, not definition (usually); (3) can be expression not just constant: int func(int a = getDefault()). Examples: cout << setprecision(6) uses default, file open with default permissions. Multiple defaults: int func(int a = 1, int b = 2, int c = 3) all have defaults, can omit from right. Partial defaults: int func(int a, int b = 2) requires first argument, second optional. Benefits: backward compatibility (add parameters with defaults to existing functions), reduce function overloading, cleaner API (optional parameters). Drawbacks: can make code less clear (hidden parameters), debugging harder (which version called?), difficult with function pointers. Overloading vs defaults: func(int) and func(int, int) as overloads vs func(int, int = 0) as defaults both valid, different trade-offs. Variadic functions: alternative to defaults for variable arguments. Template defaults: template<typename T = int> class MyClass. Constructor defaults: MyClass(int size = 10) { }. Common pattern: void init(string name = "", int value = 0, bool flag = false). Understanding defaults improves API design and reduces verbosity.
242. What does pass by reference mean in C++?
Show hintHide hint
int& ref vs int* ptr - what's the difference in usage?
Show answerHide answer
Answer: B. Parameter becomes alias to original variable
Pass by reference: parameter becomes alias (alternative name) to original variable, not separate copy. Declaration: void swap(int& a, int& b) { int t=a; a=b; b=t; }. Usage: int x=5, y=10; swap(x, y) modifies x and y directly. Differences from pointer: reference cannot be null, cannot rebind, syntactically cleaner (no dereferencing). Reference characteristics: (1) must be initialized at declaration. (2) bound to same variable throughout lifetime. (3) syntactically like original variable (no * or ->). (4) compiler implements via pointers internally. Const reference: const int& ref prevents modification through reference. Example: void print(const string& s) { cout << s; } avoids string copy. Return by reference: int& get_ref() { return value; }; must return valid reference (not local variable). Use: minimize copying for large objects. Advantages: cleaner syntax than pointers, efficient (no copy), prevents accidental null. Disadvantages: const reference can extend lifetime of temporaries (returns reference to temporary valid while reference exists). Reference vs pointer: both achieve same at assembly level, references safer (no null), pointers more flexible (rebindable). Array references: int (&arr)[10] reference to 10-element array. Function references: int (&func)() reference to function returning int. Forward reference: forward declare class for reference members. Common pattern: template<typename T> void swap(T& a, T& b) works with any type. Rvalue reference: int&& rvalue_ref moves semantics. Understanding references crucial for modern C++ and efficient coding.
243. What is a class in C++?
Show hintHide hint
Think of class as blueprint combining data and operations on that data.
Show answerHide answer
Answer: B. User-defined data type containing data members and member functions
Class: user-defined type bundling data (member variables) and functions (methods) operating on data, encapsulating state and behavior. Declaration: class ClassName { public: data members, methods; private: data members, methods; }. Object: instance of class, created on stack/heap. Example: class Student { private: int id; string name; public: void setId(int i) { id = i; } int getId() { return id; } }. Key differences from struct: default access private (struct default public). Encapsulation: hide implementation details, expose interface. Inheritance: class derived : public base { }; enables code reuse. Polymorphism: virtual functions enable runtime dispatch. Abstraction: present high-level interface, hide complexity. Composition: class contains other classes. Member initialization: in constructor. Static members: shared by all instances. Friend: external function accessing private data. Constructor: initializes object state. Destructor: cleans up resources. Access specifiers: public (anyone), protected (derived classes), private (only class). This pointer: refers to current object. Const member functions: const void display() { } don't modify state. Mutable: fields modified in const functions. Example uses: Point (x, y coordinates), Bank Account (balance, transactions), Game Character (health, inventory). Objects in memory: each instance has own member variables, shared method code. Understanding classes fundamental to OOP and modern C++ design.
244. What are access specifiers in C++ classes?
Show hintHide hint
public, private, protected - what do they control?
Show answerHide answer
Answer: B. Controls visibility and accessibility of class members
Access specifiers: control member visibility and accessibility. Three levels: (1) public: accessible from anywhere (outside class, derived classes). (2) private: accessible only within class (not derived classes or outside). (3) protected: accessible within class and derived classes, not outside. Default: class has private default (struct has public). Example: class MyClass { private: int secret; public: void setSecret(int s) { secret = s; } int getSecret() { return secret; } }; secret accessible only through public methods. Encapsulation: hide internal state (private), expose interface (public). Benefits: control access, validate data (setters can check), change implementation without breaking API. Derived classes: inherit all members, but private members inaccessible (even through inheritance), protected members accessible. Friend classes: friend class OtherClass allows OtherClass accessing private members (breaks encapsulation, use carefully). Friend functions: friend void func() accesses private. Const objects: only const member functions callable. Static: class-level members, shared by all instances. Example architecture: class BankAccount { private: double balance; public: void deposit(double amount) { if(amount > 0) balance += amount; } }. Getters/setters: data hiding pattern (getSalary(), setSalary(val)). Inheritance: class Derived : private Base (inherits all as private by default), : public Base (inherits public as public). Understanding access control essential for data protection and maintainability.
245. What are member functions in C++?
Show hintHide hint
Methods defined inside class definition - what do they do with data members?
Show answerHide answer
Answer: A. Functions that operate on class members
Member functions (methods): functions defined within class, operating on class data members. Declaration: class Circle { private: double radius; public: void setRadius(double r) { radius = r; } double getArea() { return 3.14 * radius * radius; } }. Implicit this pointer: member functions have hidden 'this' parameter (pointer to object). Example: setRadius(5) becomes setRadius(&object, 5) internally. Accessing members: direct access (radius = r) without this-> (implicit). Const member functions: void display() const { /* read-only */ } cannot modify members. Mutable members: modified even in const functions. Static member functions: static void staticFunc() { } no 'this' pointer, access only static members. Virtual functions: virtual void func() { } enabling polymorphism. Inline definition: defined in class body, implicitly inline. Separate definition: void MyClass::func() { } defined outside class. Example: class List { private: vector<int> data; public: void add(int val) { data.push_back(val); } int size() { return data.size(); } void display() { for(int x : data) cout << x; } }. Friend: non-member function accessing private data. Operator overloading: member functions for operators (+, [], (), etc.). Constructors/destructors: special member functions. Getters: return member values. Setters: modify members with validation. Callbacks: function pointers, functors, lambdas. Understanding member functions crucial for OOP design and encapsulation.
246. What are constructors in C++?
Show hintHide hint
Called automatically when object created - what does it do?
Show answerHide answer
Answer: B. Special functions initializing object state
Constructor: special member function automatically called when object created, initializing member variables. Characteristics: (1) Same name as class. (2) No return type. (3) Can be overloaded. (4) Automatically called (cannot call explicitly except with new). Types: Default constructor (no parameters): MyClass() { }. Parameterized constructor: MyClass(int id, string name) { this->id=id; this->name=name; }. Copy constructor: MyClass(const MyClass& obj) { /* copy members */ }. Move constructor: MyClass(MyClass&& obj) { /* move members */ }. Initialization list: MyClass(int x) : id(x), name("") { } initializes before body. Delegating: MyClass() : MyClass(0, "") { } calls another constructor. Example: class Person { private: string name; int age; public: Person() { name=""; age=0; } Person(string n, int a) { name=n; age=a; } Person(const Person& p) { name=p.name; age=p.age; } }. Default initialization: Person p creates object with default constructor. Explicit: explicit MyClass(int) prevents implicit conversion. Deleted: MyClass(const MyClass&) = delete; prevents copying. Default: MyClass(const MyClass&) = default; compiler-generated copy. Base class constructor: Derived() : Base(args) { }. Advantages: guaranteed initialization, can validate input. Disadvantages: complex with inheritance, rule of five (constructor, destructor, copy constructor, copy assignment, move constructor/assignment). Best practice: define all constructors explicitly or =default/=delete. Understanding constructors essential for object lifecycle management.
247. What are destructors in C++?
Show hintHide hint
Called automatically when object lifetime ends - releases allocated resources.
Show answerHide answer
Answer: B. Special functions cleaning up resources when object destroyed
Destructor: special member function automatically called when object destroyed, cleaning up resources. Characteristics: (1) Tilde (~) prefix: ~MyClass() { }. (2) No parameters, no return type. (3) Cannot be overloaded. (4) Automatically called (stack objects on scope exit, heap objects with delete). Purpose: release dynamically allocated memory, close files, release locks, cleanup resources. Example: class File { private: FILE* handle; public: File(string path) { handle=fopen(path.c_str(), "r"); } ~File() { if(handle) fclose(handle); } }. Virtual destructor: virtual ~MyClass() { } necessary for polymorphic classes (derived class cleanup called). No cleanup needed: if all members managed (string, vector), compiler-generated destructor sufficient. Delete: object *obj = new object(); delete obj; calls destructor before freeing memory. Smart pointers: unique_ptr, shared_ptr automatically call destructor (RAII pattern). Copy and swap: MyClass& operator=(const MyClass& other) { MyClass temp(other); swap(*this, temp); return *this; }. Exception safety: destructors shouldn't throw (undefined behavior). Resource acquisition is initialization (RAII): constructor acquires, destructor releases. Rule of five: if defining destructor, usually need copy constructor, copy assignment, move constructor, move assignment. Example: class Database { private: Connection* conn; public: ~Database() { if(conn) conn->close(); } }. Understanding destructors crucial for resource management and preventing leaks.
248. What is dynamic memory allocation for objects in C++?
Show hintHide hint
MyClass* obj = new MyClass() creates object where? How to destroy?
Show answerHide answer
Answer: B. Using new/delete operators to allocate/deallocate memory on heap
Dynamic allocation: creating objects on heap at runtime using new, deallocating with delete. Syntax: MyClass *ptr = new MyClass(); destroys with delete ptr; Stack vs Heap: stack (limited, automatic cleanup), heap (larger, manual management). Object creation: new MyClass() calls constructor, returns pointer. Example: class Point { public: Point(int x, int y) { /* init */ } }; Point *p = new Point(3, 4); creates object on heap. Deallocation: delete p; calls destructor, frees memory. Array allocation: MyClass *arr = new MyClass[10]; delete[] arr; (note: delete[] for arrays). Constructor called: new calls constructor for each element. Destructor called: delete/delete[] calls destructor before freeing. Null check: always verify new didn't fail (though modern C++ throws bad_alloc on failure). Memory leak: forgetting delete causes memory leak (allocated memory never freed). Dangling pointer: using pointer after delete causes undefined behavior. Smart pointers: unique_ptr<MyClass> auto-deletes when out of scope (preferred modern approach). Example: unique_ptr<MyClass> obj(new MyClass()); no explicit delete needed. Advantages dynamic: flexible size, allocate/deallocate as needed, build complex structures. Disadvantages: manual management error-prone, performance slower than stack, fragmentation risk. Exception safety: if exception thrown after new but before assignment, memory leaks. Solution: smart pointers. Variably-sized objects: arrays of user-determined size (not possible on stack with fixed size). Custom allocators: overload new/delete for specialized allocation. Understanding dynamic allocation essential for building flexible data structures.
249. What is the this pointer in C++?
Show hintHide hint
In member function, how do you refer to current object? Is it implicit or explicit?
Show answerHide answer
Answer: B. Pointer to current object within member function
This pointer: implicit pointer to object on which member function operates. Implicit: compiler adds automatically, usually invisible. Usage: accessing ambiguous members: class MyClass { int x; void setX(int x) { this->x = x; } }. Explicit use: returning self reference: MyClass& getThis() { return *this; }. Chaining: MyClass& setValue(int v) { value=v; return *this; } enables obj.setValue(5).display(). Accessing members: this->member equivalent to member in same context. Non-member functions: no 'this' (static member functions, free functions). Const member: void func() const { // this is const MyClass* this } - points to const object. Non-const member: void func() { // this is MyClass* this }. Using explicitly: method operators -> in recursive structures. Comparison: if(this == &obj) checks if operating on same object. Example: class List { void append(List& other) { if(this == &other) return; /* avoid self-append */ } }. Implementing swap: void swap(MyClass& other) { swap(*this, other); }. Self-assignment check: operator= check avoids issues. Address passing: methods receiving own object via this pointer. Memory: 'this' stored in register for efficiency, not additional memory per object. Cannot modify: 'this' is const pointer, cannot make point to different object. Smart use: returning *this in assignment operators, chaining operations, self-reference checks. Understanding 'this' crucial for method implementation and operator overloading.
250. What are static data members in C++?
Show hintHide hint
Data belonging to class, not individual objects - shared by all instances.
Show answerHide answer
Answer: B. Class-level variables shared by all instances
Static data members: variables shared by all class instances, storage at class level not object level. Declaration: class Counter { static int count; public: Counter() { count++; } }. Definition outside: int Counter::count = 0; (must be defined outside class). Access: Counter::count accesses from class, obj.count from object (not recommended). Characteristics: (1) Shared by all instances. (2) Initialized once. (3) Lifetime extends entire program. (4) Default-initialized to zero. Uses: counters (count instances), configuration (shared settings), caches. Example: class MyClass { private: static int instances; public: MyClass() { instances++; } static int getInstances() { return instances; } }. Static member function: static void staticFunc() { } no 'this', access only static members. Mutable static: static int value can be modified in const member functions if mutable. Thread safety: static initialization thread-safe (C++11), but access not thread-safe (need locks). Const static: static const int MAX = 100; compile-time constant. Constexpr: constexpr static int VALUE = 42; (C++17, can be used in compile-time expressions). Disadvantages: global state (complicates testing, hidden dependencies), thread-safety issues. Testing: difficult with static members (persist across tests). Workaround: reset in constructor/destructor or friend test classes. Design consideration: prefer instance members when possible, use static only when truly class-level. Singleton pattern: static instance of class. Understanding static members essential for resource management and class-level state.
251. What are constant member functions in C++?
Show hintHide hint
void func() const - what does const at end mean?
Show answerHide answer
Answer: B. Functions that don't modify object state
Const member functions: methods that don't modify object state, 'this' pointer becomes const pointer to const. Declaration: int getValue() const { return value; }. Guarantee: compiler prevents accidental modifications. Example: class Vector { private: double x, y; public: double length() const { return sqrt(x*x + y*y); } void scale(double factor) { x *= factor; y *= factor; } }; length() const, scale() non-const. Benefits: (1) Intent clarity (read-only operation). (2) Compiler enforcement. (3) Callable on const objects. (4) Callable on const references. Const objects: const Vector v(3, 4); can only call const methods. Const reference: void display(const Vector& v) can pass any Vector, calls const methods. Mutable members: mutable int cache_value can be modified in const methods (for caching). Example: class Square { private: double side; mutable double cached_area; public: double area() const { cached_area = side*side; return cached_area; } }. Overloading on const: can have both const and non-const versions. Example: class Container { public: int& operator[](int i) { return data[i]; } const int& operator[](int i) const { return data[i]; } }. Const correctness: best practice to mark all non-modifying functions const. Volatile: volatile methods for hardware variables. Thread-safety: const doesn't guarantee thread-safety (only single-thread). Bitwise vs logical: compiler enforces bitwise const (not logical const with mutable). Practice: use const liberally for safer, more maintainable code. Understanding const member functions crucial for API design and correctness.
252. What are friend functions and classes in C++?
Show hintHide hint
How can non-member function access private class data?
Show answerHide answer
Answer: B. External functions/classes granted access to private members
Friend: mechanism allowing non-member function or another class to access private/protected members. Friend function: friend ostream& operator<<(ostream& os, const MyClass& obj) { os << obj.private_data; return os; }. Usage: declared inside class, defined outside. Not member function: not inherited, no 'this' pointer. Example: class Complex { private: double real, imag; friend Complex add(Complex a, Complex b); }; add() can access real and imag. Friend class: friend class OtherClass allows OtherClass all access. Declaration: friend class OtherClass inside MyClass. Uses: (1) Operator overloading (<<, >>, stream operators). (2) Utility functions. (3) Related classes (iterator with container). Advantages: non-member function can access private (cleaner for operators). Disadvantages: breaks encapsulation, creates coupling. Bidirectional: friendship not inherited, one-way (A friend of B, doesn't make B friend of A). Scope: friend declared in class but not member, defined outside like free function. Best practice: minimize friends, prefer accessors when possible. Example: nested class (has natural access): class Outer { private: int data; class Inner { Outer& outer; }; }. Forward declaration: friend class Forward; (class Forward not yet defined). Iterator pattern: friend allows iterator accessing container's private members. Testing: friend often used for unit testing (test class as friend). Understanding friends crucial for operator overloading and library design.
253. Which access specifier is used to make the members of a class accessible only within the same class?
NEC model setShow hintHide hint
Private members cannot be accessed from outside the class or even from derived classes.
Show answerHide answer
Answer: B. private
The 'private' access specifier restricts access to class members strictly to within the same class only. Private members: (1) Cannot be accessed from outside the class, (2) Cannot be accessed from derived classes, (3) Cannot be accessed by friend functions (unless explicitly declared as friends), (4) Provide encapsulation and data hiding. Public members are accessible from anywhere. Protected members are accessible within the class and derived classes. The private specifier is fundamental to object-oriented programming's encapsulation principle - hiding internal implementation details. For example: class MyClass { private: int x; // Only accessible within MyClass }; Attempting to access private members from outside the class results in compilation errors. This enforces data abstraction and prevents unintended modifications to internal state.
254. How is a friend function declared inside a class?
NEC model setShow hintHide hint
The 'friend' keyword grants access to private/protected members.
Show answerHide answer
Answer: A. By using the keyword friend before the function declaration
A friend function is declared inside a class by using the keyword 'friend' before the function declaration. Friend function concept: (1) Non-member function declared as friend inside class, (2) Has access to private/protected members, (3) NOT a member function - No this pointer, (4) Breaks encapsulation (intentionally). Friend function declaration: friend void externalFunction(ClassName obj);, friend class OtherClass;. Characteristics: (1) Declared inside class with 'friend' keyword, (2) Implemented outside class - No scope resolution operator needed, (3) Can access private/protected members, (4) Not inherited - Friends of base not friends of derived. Difference from member functions: (1) Member functions - Have this pointer, part of class, (2) Friend functions - No this pointer, external to class, (3) Operator overloading - Both can be friends. Usage example: class MyClass { private: int value; friend void setMyClass(MyClass &obj, int val); }; void setMyClass(MyClass &obj, int val) { obj.value = val; // Allowed!}. When needed: (1) Operator overloading - <<, >> operators, (2) Binary operators - Need access to both objects, (3) Tight coupling desired - Controlled access, (4) Symmetric operations - Same access needed. Operator example: ostream& operator<<(ostream &out, MyClass obj) { return out << obj.value; }. Limitations: (1) Breaks encapsulation - Use carefully, (2) Not inherited - Must re-declare in subclass, (3) No virtual friends - Can't override, (4) Unidirectional - Class A makes B friend, B doesn't get A access. Modern practice: (1) Minimize friend declarations, (2) Prefer member functions when possible, (3) Friend classes - Tighter coupling alternative, (4) API design - Consider implications. This provides controlled access beyond standard encapsulation.
255. Which of the following statements is true about static functions?
Past questionShow hintHide hint
Static functions belong to the class, not to instances. Can you have multiple static functions with the same name?
Show answerHide answer
Answer: A. Static functions can be overloaded
Static functions can be overloaded. This is a fundamental C++ concept. Understanding Static Functions: (1) Static functions belong to the class, not to objects, (2) Called using ClassName::functionName(), (3) Can access only static data members, (4) Do not have 'this' pointer. Overloading Rules: (1) Overloading requires different parameter lists, (2) Same function name, different parameters allowed, (3) Works for both member and static functions, (4) Return type alone doesn't distinguish overloads. Static Function Overloading Example: class MyClass { public: static void display(int x); static void display(double x); static void display(int x, int y); }; All three are valid overloads of 'display'. Why Overloading Works for Static: (1) Compiler can distinguish by parameter types, (2) Does not violate static function properties, (3) No polymorphism issue, (4) Compile-time binding still applies. Static vs Non-Static Overloading: (1) Both can be overloaded in same class, (2) Static version called on class, (3) Non-static version called on object. Why Other Options Are Wrong: (1) Option B 'implicit' - Static functions are explicit, (2) Option C - Cannot override static functions in derived class (hiding, not overriding), (3) Option D - Contradicts correct answer. Common Misconceptions: (1) Static functions cannot be overloaded - FALSE, (2) Virtual static functions - Not possible (C++ rule), (3) Hiding vs Overriding - Static functions hide, not override. Practical Examples: (1) Math.max(int, int) vs Math.max(double, double), (2) Utility functions with type variations, (3) Factory methods with different parameters. This demonstrates static method design in C++.
256. Which access specifier allows members to be accessible within the same class and child classes?
Recalled from Jan 2026 examShow hintHide hint
This access specifier is more restrictive than public but allows access in derived classes. What is it?
Show answerHide answer
Answer: C. Protected
Protected is the access specifier that allows members to be accessible within the same class and child classes (derived classes). Members declared as protected cannot be accessed from outside the class or its derived classes, making them more restrictive than public but more permissive than private. This is crucial for inheritance because it allows base classes to provide implementation details to derived classes without exposing them to the outside world. Protected members are often used for implementation details that subclasses need to override or use.
257. Which object-oriented programming (OOP) concept involves bundling data and methods within a single class to protect them from outside interference?
Recalled from Jan 2026 examShow hintHide hint
Bundling data and methods together for protection. What is this concept?
Show answerHide answer
Answer: C. Encapsulation
Encapsulation is the OOP concept that involves bundling data and methods within a single class to protect them from outside interference. Encapsulation uses access specifiers (public, private, protected) to control what's accessible from outside the class. This hides internal implementation details and prevents unintended modification of object state. Encapsulation promotes data hiding and provides a controlled interface (public methods) for interacting with objects. Polymorphism deals with multiple forms. Inheritance deals with parent-child relationships. Abstraction deals with hiding complexity.
258. Which of the following statements is true about static functions in C++?
Recalled from Jan 2026 examShow hintHide hint
Static functions belong to the class, not instances. Can they be overloaded?
Show answerHide answer
Answer: B. Static functions cannot be overloaded
Static functions cannot be overloaded in C++. Since static functions belong to the class itself rather than instances, function resolution is based on the class and function name alone. Without instance information, the compiler cannot distinguish between overloaded static functions based on parameter types alone in all contexts. Non-static functions can be overloaded within a class hierarchy through polymorphism. Static functions cannot be virtual because they're not polymorphic. Static functions cannot access instance variables because they don't have an instance context.
259. In a structure, what is the default visibility of its members?
Show answerHide answer
Answer: B. Public
260. What is a namespace in C++?
Show answerHide answer
Answer: C. It is a mechanism for managing the scope of identifiers in large programs
261. Which keyword is used to define a namespace in C++?
Show answerHide answer
Answer: A. namespace
262. Which of the following statements is true regarding namespaces in C++?
Show answerHide answer
Answer: A. You can have multiple namespaces with the same name in the same program
263. What is the purpose of using the using keyword with namespaces in C++?
Show answerHide answer
Answer: B. To bring all the members of a namespace into the current scope
264. What is the scope resolution operator in C++?
Show answerHide answer
Answer: B. ::
265. Which of the following is true regarding the scope resolution operator in C++?
Show answerHide answer
Answer: A. It is used to access the members of a namespace
266. What is the purpose of the unnamed namespace in C++?
Show answerHide answer
Answer: B. To limit the visibility of a function or variable to a single source file
267. Which of the following is a benefit of using namespaces in C++?
Show answerHide answer
Answer: A. They prevent naming conflicts between classes
268. Which of the following is a disadvantage of using namespaces in C++?
Show answerHide answer
Answer: A. They can make the code more difficult to read and understand
269. Which of the following is true regarding the global namespace in C++?
Show answerHide answer
Answer: D. All of the above
270. What is a namespace in C++?
Show answerHide answer
Answer: A. A container that holds a group of related variables and functions
271. Which keyword is used to define a namespace in C++?
Show answerHide answer
Answer: B. namespace
272. Which of the following statements is true regarding namespaces in C++?
Show answerHide answer
Answer: D. Namespace members are accessed using the :: operator
273. What is the purpose of using a namespace in C++?
Show answerHide answer
Answer: A. To avoid naming conflicts between variables and functions
274. What is the default namespace in C++?
Show answerHide answer
Answer: A. std
275. Can a namespace be defined across multiple files in C++?
Show answerHide answer
Answer: B. Yes, by using the namespace keyword
276. Which of the following is a valid way to alias a namespace in C++?
Show answerHide answer
Answer: C. namespace B = A
277. Which of the following is an advantage of using namespaces in C++?
Show answerHide answer
Answer: B. They make it easier to reuse code
278. Which of the following is true regarding the scope of a namespace in C++?
Show answerHide answer
Answer: A. A namespace can be used anywhere in the program
279. Which of the following statements is true about function overloading in C++?
Show answerHide answer
Answer: B. Overloaded functions can differ in the number of parameters
280. Which of the following is not a valid way of differentiating between overloaded functions?
Show answerHide answer
Answer: C. Return type
281. Which of the following statements is true about function overloading in C++? (Repeated concept)
Show answerHide answer
Answer: B. Access levels do not affect function overloading
282. What is the benefit of function overloading in C++?
Show answerHide answer
Answer: C. It allows the same function name to be used for different operations
283. Which of the following is true about function overloading? (Repeated concept)
Show answerHide answer
Answer: D. None of the above
284. Which of the following is an example of function overloading in C++?
Show answerHide answer
Answer: D. All of the above
285. What is function overloading in C++?
Show answerHide answer
Answer: B. Defining a function with the same name but different parameters as an existing function
286. Which of the following is not a valid way to overload a function in C++?
Show answerHide answer
Answer: B. Changing the return type of the function
287. What is the purpose of function overloading in C++?
Show answerHide answer
Answer: D. To allow functions to be used with different sets of parameters
288. Which of the following is an example of function overloading in C++? (Repeated concept)
Show answerHide answer
Answer: D. All of the above
289. Can two functions in C++ have the same name and the same set of parameters?
Show answerHide answer
Answer: C. No, it is not allowed in C++
290. Which of the following is true about function overloading in C++? (Repeated concept)
Show answerHide answer
Answer: D. Overloaded functions must have different parameter types or different number of parameters
291. What is the benefit of using function overloading in C++?
Show answerHide answer
Answer: D. It allows you to create more versatile functions
292. Can you overload a member function in C++?
Show answerHide answer
Answer: A. Yes, you can overload both member and non-member functions in C++
293. Which of the following is an example of function overloading?
Show answerHide answer
Answer: A. int add(int x, int y) { return x + y; } int add(int x, int y, int z) { return x+y+z;}
294. What is an inline function in C++?
Show answerHide answer
Answer: B. A function that is defined with the inline keyword
295. What is the advantage of using an inline function?
Show answerHide answer
Answer: B. It reduces the function call overhead
296. Which keyword is used to declare an inline function in C++?
Show answerHide answer
Answer: B. inline
297. Can a function that returns void be inline in C++?
Show answerHide answer
Answer: A. Yes, any function can be declared inline
298. Which of the following statements is true about inline functions in C++?
Show answerHide answer
Answer: A. Inline functions cannot be recursive
299. How does the compiler treat inline functions in C++?
Show answerHide answer
Answer: B. It replaces the function call with the actual function code at the point of the call
300. Can a function that is defined in a separate source file be inline in C++?
Show answerHide answer
Answer: B. No, inline functions must be defined in the same source file as the caller
301. Which of the following is an example of an inline function in C++?
Show answerHide answer
Answer: D. class Rectangle { public: inline int area() { return width * height; } };
302. Which of the following is a disadvantage of using inline functions in C++?
Show answerHide answer
Answer: A. It can increase the size of the program
303. Which of the following is a good candidate for an inline function in C++?
Show answerHide answer
Answer: B. A function that is called frequently and has a short body
304. What is an inline function in C++? (Repeated concept)
Show answerHide answer
Answer: A. A function defined with the "inline" keyword, which is a suggestion to the compiler to perform inline expansion of the function
305. What is the advantage of using inline functions in C++? (Repeated concept)
Show answerHide answer
Answer: A. They are faster than regular functions
306. When should you use an inline function in C++?
Show answerHide answer
Answer: A. When the function is small and simple
307. What is the syntax for defining an inline function in C++?
Show answerHide answer
Answer: A. inline int function_name(int param1, int param2) {}
308. Can a member function of a class be inline in C++?
Show answerHide answer
Answer: C. Yes, as long as it is defined with the "inline" keyword and the function body is defined inside the class definition
309. What is the purpose of the "inline" keyword in C++?
Show answerHide answer
Answer: C. To suggest to the compiler to perform inline expansion of a function
310. Which of the following is a disadvantage of using inline functions in C++? (Repeated concept)
Show answerHide answer
Answer: A. They can increase the size of the executable code
311. Can a function defined in a header file be inline in C++?
Show answerHide answer
Answer: C. Yes, as long as it is defined with the "inline" keyword and the function body is defined inside the header file
312. What is a default argument in C++?
Show answerHide answer
Answer: C. An argument that is assigned a value if no other value is provided
313. Which of the following is true about default arguments?
Show answerHide answer
Answer: A. They must be specified in the function declaration and definition
314. Which of the following is an example of a function that uses a default argument?
Show answerHide answer
Answer: B. float divide(float a, float b, float c = 1.0)
315. What is the order in which arguments are passed to a function?
Show answerHide answer
Answer: A. Regular arguments first, followed by default arguments
316. Which of the following is true about default arguments in relation to function overloading?
Show answerHide answer
Answer: C. Default arguments are allowed, but only for one function in an overload set
317. What is the benefit of using default arguments?
Show answerHide answer
Answer: B. It allows for fewer function overloads
318. What happens if a default argument is specified in both the function declaration and definition?
Show answerHide answer
Answer: A. The code will not compile
319. What are default arguments in C++? (Repeated concept)
Show answerHide answer
Answer: A. Arguments that are automatically initialized with a default value.
320. Where should default arguments be specified in a function declaration?
Show answerHide answer
Answer: B. After the function name.
321. What is the purpose of default arguments? (Repeated concept)
Show answerHide answer
Answer: D. To provide a default value for a parameter if one is not specified.
322. When are default arguments evaluated?
Show answerHide answer
Answer: A. At runtime.
323. What happens if a default argument is specified in both the function declaration and the function definition? (Repeated concept)
Show answerHide answer
Answer: A. The program will not compile.
324. What is the syntax for specifying a default argument?
Show answerHide answer
Answer: A. argumentType argumentName = defaultValue
325. Which of the following is true about classes in C++?
Show answerHide answer
Answer: A. A class is a blueprint for objects
326. Which of the following keywords is used to create an object of a class?
Show answerHide answer
Answer: A. new
327. Which of the following access specifiers is used to make class members accessible only within the same class?
Show answerHide answer
Answer: B. private
328. Which of the following is a constructor?
Show answerHide answer
Answer: A. A function that is used to create an object of a class
329. What is encapsulation in C++?
Show answerHide answer
Answer: A. Combining data members and member functions in a single unit
330. What is a class in C++?
Show answerHide answer
Answer: A. A user-defined data type
331. Which of the following is true about a static member of a class?
Show answerHide answer
Answer: A. It is shared by all objects of the class
332. Which of the following is used to create a copy of an object in C++?
Show answerHide answer
Answer: C. Object copying
333. Which of the following is used to initialize the data members of an object of a class?
Show answerHide answer
Answer: A. Constructors
334. Which of the following is true about friend functions in C++?
Show answerHide answer
Answer: B. Friend functions can access private and protected members of a class
335. What is an object in C++?
Show answerHide answer
Answer: A. An instance of a class
336. Which of the following access specifiers in C++ allows the member to be accessed by any function or class in the program?
Show answerHide answer
Answer: C. Public
337. Which access specifier in C++ allows a member function or variable to be accessed only by the same class and its friends?
Show answerHide answer
Answer: A. Private
338. Which access specifier in C++ allows a member function or variable to be accessed by the same class, its derived classes, and its friends?
Show answerHide answer
Answer: C. Protected
339. Which of the following is true about access specifiers in C++?
Show answerHide answer
Answer: A. They determine the visibility of a member outside of the class.
340. Which of the following access specifiers is used to hide the implementation details of a class from the user?
Show answerHide answer
Answer: A. Private
341. Which access specifier in C++ allows a member function or variable to be accessed by any class or function that is declared as a friend of the class?
Show answerHide answer
Answer: D. Friend
342. Which access specifier in C++ allows a member function or variable to be accessed by the same class and its derived classes?
Show answerHide answer
Answer: C. Protected
343. Which access specifier in C++ allows a member function or variable to be accessed by any function or class within the same namespace?
Show answerHide answer
Answer: B. Public
344. Which of the following access specifiers in C++ is used to prevent a member from being accessed outside of the class definition?
Show answerHide answer
Answer: B. private
345. Which access specifier allows access to a class member only within the class definition?
Show answerHide answer
Answer: B. private
346. Which access specifier allows access to a class member from any function outside the class definition?
Show answerHide answer
Answer: A. public
347. Which access specifier allows access to a class member from a derived class?
Show answerHide answer
Answer: C. protected
348. Which access specifier allows a member function to access all members of a class?
Show answerHide answer
Answer: B. private
349. What is the default access specifier for a class in C++?
Show answerHide answer
Answer: B. private
350. Which access specifier allows a friend function to access all members of a class?
Show answerHide answer
Answer: D. friend
351. Which access specifier allows access to a class member from any class?
Show answerHide answer
Answer: A. public
352. Which access specifier should be used for class members that need to be accessed by functions outside the class definition?
Show answerHide answer
Answer: A. public
353. Which access specifier should be used for class members that should only be accessed within the class definition?
Show answerHide answer
Answer: B. private
354. What is the dot operator used for in C++?
Show answerHide answer
Answer: B. To access a member of an object
355. Which of the following is an example of an object?
Show answerHide answer
Answer: C. MyClass obj;
356. Which of the following operators is used to access a member of an object?
Show answerHide answer
Answer: A. .
357. Which of the following is used to initialize an object?
Show answerHide answer
Answer: A. The constructor
358. Which of the following access specifiers allows a member to be accessed from any function?
Show answerHide answer
Answer: A. Public
359. What is the keyword used to declare a class in C++?
Show answerHide answer
Answer: A. class
360. Which of the following is used to destroy an object?
Show answerHide answer
Answer: B. The destructor
361. Which of the following is true about an object in C++?
Show answerHide answer
Answer: A. It is an instance of a class
362. What is the difference between the dot operator (.) and the arrow operator (->) in C++?
Show answerHide answer
Answer: C. The dot operator is used to access non-static members, while the arrow operator is used with pointers to access non-static members.
363. Which operator is used to access the members of an object in C++?
Show answerHide answer
Answer: A. .
364. Which keyword is used to define a member function outside the class definition in C++?
Show answerHide answer
Answer: D. none of the above
365. Which of the following is true about object-oriented programming in C++?
Show answerHide answer
Answer: B. Objects encapsulate data and behavior
366. Which of the following is true about a member function in C++?
Show answerHide answer
Answer: A. It can be defined inside or outside the class definition
367. Which keyword is used to access the data members of an object inside a member function in C++?
Show answerHide answer
Answer: D. this
368. Which of the following is true about object creation in C++?
Show answerHide answer
Answer: C. It is done using the class constructor
369. Which of the following is true about constructors in C++?
Show answerHide answer
Answer: B. They are used to initialize the data members of an object
370. Which of the following is true about destructors in C++?
Show answerHide answer
Answer: C. They are used to deallocate memory for objects
371. Which of the following is true about static member functions in C++?
Show answerHide answer
Answer: A. They can access only static data members of a class
372. Which of the following is true about friend functions in C++?
Show answerHide answer
Answer: B. They can access private and protected members of a class
373. What is a member function in C++?
Show answerHide answer
Answer: B. A function that belongs to a class
374. How are member functions defined in C++?
Show answerHide answer
Answer: C. Both A and B
375. Which keyword is used to define a member function outside of a class in C++?
Show answerHide answer
Answer: D. none of the above
376. Which of the following is a valid syntax for defining a member function outside of a class in C++?
Show answerHide answer
Answer: A. void MyClass::myFunction() {}
377. Which of the following is true about member functions in C++?
Show answerHide answer
Answer: A. They have access to the private data members of a class
378. What is the implicit parameter in a member function in C++?
Show answerHide answer
Answer: A. A pointer to the object that called the function
379. Which keyword is used to access the implicit parameter in a member function in C++?
Show answerHide answer
Answer: A. this
380. Which of the following is true about the this pointer in C++?
Show answerHide answer
Answer: B. It points to the object that called the member function
381. Which of the following is true about inline member functions in C++?
Show answerHide answer
Answer: C. They are used for small functions that are called frequently
382. Which of the following is true about const member functions in C++?
Show answerHide answer
Answer: A. They cannot modify the data members of a class
383. What is a member function in C++? (Repeated Question)
Show answerHide answer
Answer: A. A function that is defined inside a class definition
384. How is a member function defined inside a class definition in C++?
Show answerHide answer
Answer: D. using the function name and parameter list
385. What is the purpose of the "this" pointer in C++?
Show answerHide answer
Answer: A. It points to the object on which the member function is called
386. How is a member function defined outside a class definition in C++?
Show answerHide answer
Answer: B. using the scope resolution operator and the class name
387. What is the syntax for calling a member function of an object in C++?
Show answerHide answer
Answer: C. both A and B
388. What is the default access specifier for a member function in C++?
Show answerHide answer
Answer: B. private
389. Can a member function be overloaded in C++?
Show answerHide answer
Answer: A. Yes
390. Can a member function be declared inside a class definition and defined outside the class definition in C++?
Show answerHide answer
Answer: A. Yes
391. Can a member function access the private data members of a class in C++?
Show answerHide answer
Answer: A. Yes
392. What is the purpose of the const keyword in a member function declaration in C++?
Show answerHide answer
Answer: C. It indicates that the function does not modify the object on which it is called
393. What is a constructor in C++?
Show answerHide answer
Answer: B. A function that is used to initialize the data members of an object
394. What is the name of the constructor function in C++?
Show answerHide answer
Answer: C. the same as the class name
395. How many constructors can a class have in C++?
Show answerHide answer
Answer: B. More than one
396. Which type of constructor is called automatically when an object is created in C++?
Show answerHide answer
Answer: C. Default constructor
397. What is the purpose of the copy constructor in C++?
Show answerHide answer
Answer: A. It is used to create a copy of an existing object
398. Can a constructor be declared as private in C++?
Show answerHide answer
Answer: A. Yes
399. Which of the following is true about the default constructor in C++?
Show answerHide answer
Answer: D. All of the above
400. Which of the following is true about the parameterized constructor in C++?
Show answerHide answer
Answer: C. It takes one or more arguments
401. What is the syntax for calling a constructor in C++?
Show answerHide answer
Answer: C. class_name object_name(argument_list)
402. Which of the following is true about the destructor in C++?
Show answerHide answer
Answer: B. It is used to deallocate memory for an object
403. What is the this pointer in C++?
Show answerHide answer
Answer: A. A pointer to the current object
404. What is the purpose of the this pointer in C++?
Show answerHide answer
Answer: A. To refer to the object's own data members
405. What is the syntax for using the this pointer in C++?
Show answerHide answer
Answer: C. Both A and B
406. Can the this pointer be modified in C++?
Show answerHide answer
Answer: B. No, it is a constant pointer
407. What is the data type of the this pointer in C++?
Show answerHide answer
Answer: A. Class type pointer
408. What happens if a member function does not use the this pointer in C++?
Show answerHide answer
Answer: D. None of the above
409. How is the this pointer passed to a member function in C++?
Show answerHide answer
Answer: A. It is implicitly passed to the function
410. What is the size of the this pointer in C++?
Show answerHide answer
Answer: C. It depends on the size of the object
411. Can the this pointer be used in static member functions in C++?
Show answerHide answer
Answer: A. No, the this pointer is not applicable to static member functions
412. In which operator overload function can the this pointer be used in C++?
Show answerHide answer
Answer: C. Both A and B
413. What is this pointer in C++?
Show answerHide answer
Answer: A. It is a pointer to the current object
414. In which part of a C++ class is this pointer implicitly passed?
Show answerHide answer
Answer: D. All of the above
415. What is the type of this pointer in C++?
Show answerHide answer
Answer: C. ClassName
416. Which of the following is a valid use of this pointer in C++?
Show answerHide answer
Answer: D. All of the above
417. What is the purpose of this pointer in C++?
Show answerHide answer
Answer: A. To resolve naming conflicts between member variables and parameters of a function
418. Which of the following statements is true about this pointer in C++?
Show answerHide answer
Answer: B. It cannot be modified by the programmer
419. What happens if this pointer is dereferenced when it is null?
Show answerHide answer
Answer: C. Undefined behavior occurs
420. What is the use of this pointer in operator overloading in C++?
Show answerHide answer
Answer: A. To overload the -> operator
421. What is the output of the following code?
Show answerHide answer
Answer: B. The address of obj1 and obj2 are different
422. What is a static data member in C++?
Show answerHide answer
Answer: B. A data member that is shared among all instances of a class
423. How is a static data member declared in C++?
Show answerHide answer
Answer: A. Using the keyword static before the data type
424. Which of the following statements is true about static data members in C++?
Show answerHide answer
Answer: B. They are initialized to 0 by default
425. How is a static function declared in C++?
Show answerHide answer
Answer: A. Using the keyword static before the return type
426. Which of the following statements is true about static functions in C++?
Show answerHide answer
Answer: A. They can access only static data members of the class
427. Can a static function in C++ access non-static data members of the class?
Show answerHide answer
Answer: C. No, static functions cannot access non-static data members
428. Which of the following statements is true about static data members in C++?
Show answerHide answer
Answer: C. They can be initialized only outside the class definition
429. Which of the following statements is true about static functions in C++?
Show answerHide answer
Answer: A. They cannot access non-static data members
430. Which of the following statements is true about static data members in C++?
Show answerHide answer
Answer: D. All of the above are true
431. What is the output of the following code? (Code involves MyClass::count++, incrementCount called twice)
Show answerHide answer
Answer: A. Count: 2
432. What is a static data member in C++?
Show answerHide answer
Answer: B. A data member that belongs to the class and not to any instance of the class
433. How is a static data member declared In C++?
Show answerHide answer
Answer: B. With the keyword 'static' and the data type of the member
434. Which of the following statements is true about static data members in C++?
Show answerHide answer
Answer: A. They are initialized to zero by default
435. What is a static function in C++?
Show answerHide answer
Answer: B. A function that belongs to the class and not to any instance of the class
436. How is a static function declared in C++?
Show answerHide answer
Answer: A. With the keyword 'static' and the return type of the function
437. Which of the following statements is true about static functions in C++?
Show answerHide answer
Answer: B. They cannot be virtual
438. What is the purpose of static data members and static functions in C++?
Show answerHide answer
Answer: A. To save memory by sharing data across all instances of the class
439. Which of the following statements is true about the scope of a static data member in C++?
Show answerHide answer
Answer: A. It has class scope and can be accessed using the class name and the scope resolution operator (::)
440. Which of the following statements is true about the initialization of a static data member in C++?
Show answerHide answer
Answer: B. It must be initialized outside the class declaration using an assignment statement
441. What is a constant member function in C++?
Show answerHide answer
Answer: A. A member function that cannot modify any data members of the class
442. How is a constant member function declared in C++?
Show answerHide answer
Answer: A. Using the keyword const after the function declaration
443. Which of the following statements is true about constant member functions in C++?
Show answerHide answer
Answer: C. They can be called by both constant and non-constant objects of the class
444. Can a constant member function modify a static data member of the class?
Show answerHide answer
Answer: D. Yes, because static members are not part of the object's state
445. Which of the following statements is true about constant objects in C++?
Show answerHide answer
Answer: A. They cannot modify any data members of the class
446. How is a constant object declared in C++?
Show answerHide answer
Answer: A. Using the keyword const before the object name
447. Which of the following statements is true about constant member functions in C++? (Overloading)
Show answerHide answer
Answer: A. They can be overloaded with non-constant member functions of the same name
448. What is the output of the following code? (const MyClass obj = {5}; obj.value = 10;)
Show answerHide answer
Answer: A. 5 followed by a compilation error
449. What is a constant member function in C++?
Show answerHide answer
Answer: A. A member function that cannot be modified
450. How is a constant member function declared in C++?
Show answerHide answer
Answer: A. Using the keyword const after the function name
451. Which of the following statements is true about constant objects in C++?
Show answerHide answer
Answer: A. They cannot modify the data members of the class
452. Can a non-constant member function be called on a constant object in C++?
Show answerHide answer
Answer: B. No, a non-constant member function cannot be called on a constant object
453. Which of the following statements is true about constant objects in C++?
Show answerHide answer
Answer: C. They can be created using the const keyword before the object name
454. Which of the following statements is true about constant objects in C++?
Show answerHide answer
Answer: B. They cannot call non-constant member functions of the class
455. Which of the following statements is true about constant objects in C++?
Show answerHide answer
Answer: A. They can access only constant member functions of the class
456. Which of the following statements is true about constant member functions in C++? (Duplicate logic)
Show answerHide answer
Answer: A. They cannot modify the data members of the class
457. What is the output of the following code? (const MyClass obj = {10}; obj.printValue();)
Show answerHide answer
Answer: A. Value: 10
3.4 Features of object-oriented programming
21 questions · ACtE0304
458. If derived class has constructor, which is called first?
Aasadh 2081 examShow hintHide hint
Initialize base before derived.
Show answerHide answer
Answer: B. Base constructor first
Base class constructor is called first to initialize base class members before derived class constructor.
459. Which operators can be overloaded in C++?
Show hintHide hint
Most operators can be overloaded in C++.
Show answerHide answer
Answer: D. All of the above
All arithmetic, comparison, and logical operators can be overloaded in C++, except for ::, ., .*, and ?:
460. What is Inheritance in OOP?
Show hintHide hint
Creating new classes based on existing ones.
Show answerHide answer
Answer: B. Deriving new classes from existing
Inheritance allows creating new classes from existing classes, inheriting properties and methods.
461. What is single-level inheritance?
Show hintHide hint
One parent, one child.
Show answerHide answer
Answer: B. Class from single base
Single-level inheritance occurs when a derived class inherits from exactly one base class.
462. What must be overloaded as member function in C++?
Show hintHide hint
Certain operators have special requirements.
Show answerHide answer
Answer: D. All of the above
=, [], and () operators must be overloaded as member functions, not global functions.
463. What is operator overloading in C++?
Show hintHide hint
Complex c1 + c2 - how does compiler know what + means for Complex?
Show answerHide answer
Answer: B. Defining custom behavior for operators with objects
Operator overloading: defining custom behavior for C++ operators when applied to user-defined types. Syntax: ReturnType operator@(parameters) { }. Examples: Complex operator+(const Complex& a, const Complex& b) { return Complex(a.real+b.real, a.imag+b.imag); }. Member function: Complex operator+(const Complex& other) const { return Complex(real+other.real, imag+other.imag); }. Non-member: friend Complex operator+(const Complex& a, const Complex& b). Overloadable: arithmetic (+,-,*,/,%), comparison (==,!=,<,>,<=,>=), logical (&&,||,!), bitwise (&,|,^,~,<<,>>), assignment (=,+=,-=,*=,/=,%=), subscript ([]), function call (()), member access (->), increment/decrement (++,--), smart pointer (* and ->). Cannot overload: scope resolution (::), member selection (.), pointer-to-member (.*), ternary (?:), sizeof, typeid. Member-only operators: assignment (=), subscript ([]), function call (()), member access (->). Unary vs binary: prefix/postfix increment differentiated by dummy int parameter. Example: MyClass& operator++() { /* prefix */ } vs MyClass operator++(int) { /* postfix */ }. Return types: arithmetic return by value, assignment return by reference (&). Const correctness: operator+(const MyClass&) const. Chaining: assignment returns reference enabling a=b=c. Implicit conversion: operator int() { return value; } converts object to int. Conversion constructor: MyClass(int) { } converts int to MyClass. Advantages: intuitive syntax (obj1 + obj2 vs obj1.add(obj2)), natural expression. Disadvantages: can confuse (+ might not mean traditional addition), complicates implementation. Best practice: maintain expected semantics, avoid surprising behavior. Example: string concatenation with +, vector index with []. Understanding operator overloading essential for creating natural-feeling APIs.
464. What is data conversion (type conversion) in C++?
Show hintHide hint
int i = 5.5; - automatic conversion from double to int, or cast for control.
Show answerHide answer
Answer: B. Implicit or explicit conversion between types
Data conversion: changing one type to another. Implicit (automatic): int x = 5.5; converts double to int (loses precision). Explicit (casting): (int)5.5, int(5.5) (C-style), static_cast<int>(5.5) (C++ style). C++ casts: (1) static_cast<T>(value) type-safe conversion (int from double, base to derived). (2) dynamic_cast<T*>(ptr) safe polymorphic conversion (returns null if invalid). (3) reinterpret_cast<T*>(ptr) unsafe, bitwise reinterpretation (pointer to int). (4) const_cast<T&>(value) adds/removes const. Implicit conversion rules: arithmetic promotion (int to double), pointer conversion (derived* to base*), user-defined conversion (conversion constructor, conversion operator). Conversion constructor: class MyClass { MyClass(int x) { } }; int i=5; MyClass m = i; implicit conversion via constructor. Conversion operator: operator int() { return value; }; int i = obj; implicit conversion via operator. Narrowing: converting larger type to smaller (double to int) loses data - modern C++ warns/errors in some contexts. Example: std::vector<int> v = {1, 2, 3.5}; error (3.5 narrowing to 3). Const conversion: const_cast<string&>(const_str) removes const. Pointer conversion: static_cast<Base*>(derived_ptr) safe, dynamic_cast<Derived*>(base_ptr) safe with RTTI. String conversions: stoi(), stof(), to_string() in modern C++. Best practice: explicit casts for clarity, avoid unsafe reinterpret_cast, use static_cast for type-safe conversions. Understanding conversions crucial for type safety and preventing errors.
465. What is inheritance in C++ - specifically single inheritance?
Show hintHide hint
class Derived : public Base { } - one parent, one child.
Show answerHide answer
Answer: B. Single derived class from single base class
Single inheritance: derived class inherits from one base class. Syntax: class Derived : public Base { }. Access: public (inherits as public), private (inherits as private), protected (inherits as protected). Characteristics: (1) Derived is-a Base relationship. (2) Inherits all non-private members. (3) Can override virtual functions. (4) Constructor chains. Example: class Vehicle { protected: string make; public: virtual void drive() { } }; class Car : public Vehicle { public: void drive() override { cout << "Driving car"; } }. Public inheritance: public members stay public, protected stay protected. Private inheritance: public/protected become private (rarely used). Protected inheritance: public become protected, protected stay protected. Method override: derived defines function with same signature as base. Virtual call: Vehicle *v = new Car(); v->drive() calls Car::drive(). Member access: Car can access public/protected Vehicle members. Hidden: if derived defines non-virtual function with same name as base, hides base version. Constructor: derived constructor must call base constructor (explicitly or implicitly). Initialization: Car() : Vehicle(args) { } initializes base first. Disadvantage single inheritance: less flexible than multiple inheritance. Code reuse: inherit common functionality from base. Polymorphism: base pointer/reference points to derived object. Diamond problem: avoided (only one base). Best practice: public inheritance for is-a relationships, prefer composition when not true is-a. Understanding single inheritance crucial for OOP and code reuse.
466. What is multiple inheritance in C++?
Show hintHide hint
class Derived : public Base1, public Base2 { } - two parents.
Show answerHide answer
Answer: A. One class inheriting from multiple base classes
Multiple inheritance: derived class inherits from multiple base classes. Syntax: class Derived : public Base1, public Base2 { }. Mix access: class Derived : public A, private B, protected C { }. Uses: combining unrelated features from multiple bases. Example: class Employee { virtual void work() { } }; class Manager { virtual void manage() { } }; class ProjectManager : public Employee, public Manager { void work() override { } void manage() override { } }. Diamond problem: if both bases inherit from common ancestor. Example: class A { }; class B : public A { }; class C : public A { }; class D : public B, public C { }; D has two copies of A (ambiguous). Solution 1 - Virtual inheritance: class B : virtual public A, class C : virtual public A creates single A. Virtual base: D has one A instance, accessed via B and C. Initialization: D() : B(args), C(args), A(args) { } must initialize virtual base explicitly. Ambiguity resolution: B::func() or C::func() if both define same. Complexity: multiple inheritance increases complexity, harder to understand. Best practice: avoid unless necessary, prefer composition (has-a over is-a). Interface classes: pure virtual (resembles multiple inheritance). Mixins: small classes with specific functionality (thread-safe, comparable). Modern C++: prefer composition and single inheritance. Testing: harder with multiple inheritance (more dependencies). Use case: practical multiple inheritance uncommon in modern code. Understanding multiple inheritance important for legacy code and advanced patterns.
467. What is multilevel inheritance in C++?
Show hintHide hint
class C : public B where B : public A - three levels.
Show answerHide answer
Answer: B. Multiple inheritance levels (A->B->C)
Multilevel inheritance: inheritance chain where derived class becomes base for another. Example: class Animal { }; class Mammal : public Animal { }; class Dog : public Mammal { }. Dog inherits from Mammal, which inherits from Animal. Inheritance chain: Dog is-a Mammal is-a Animal. Member access: Dog can access public/protected members of both Mammal and Animal. Constructor: Dog() : Mammal() { } or Dog() : Mammal(), Animal() { } must call constructors in order (base first). Method override: each level can override or introduce methods. Virtual functions: enable polymorphic behavior across levels. Example: class Shape { virtual void draw() { } }; class 2DShape : public Shape { }; class Circle : public 2DShape { void draw() override { } }. Ambiguity: no diamond problem with multilevel (linear chain). Scope: searching for member starts at current class, then parent, then grandparent. Hidden: non-virtual methods hidden if overridden at any level. Complexity grows: deeper inheritance more complex, harder to understand. Best practice: limit depth (usually 3 levels max). Code reuse: inherit behavior progressively (general -> specific -> most specific). Polymorphism: common use case for heterogeneous collections (vector<Shape*>). Maintenance: changes to base affect all derived (for better or worse). Understanding multilevel inheritance important for hierarchical design.
468. What is hybrid inheritance in C++?
Show hintHide hint
Mix of single, multiple, and multilevel inheritance in same hierarchy.
Show answerHide answer
Answer: A. Combining different inheritance types
Hybrid inheritance: combining multiple, single, and/or multilevel inheritance in complex hierarchy. Example structure: class A { }; class B : public A { }; class C : public A { }; class D : public B, public C { }; (multilevel + multiple + potential diamond). Diamond problem possible: if multiple paths lead to common base, virtual inheritance resolves. Real example: Graphics system - Shape (base), RectangleBase : public Shape, FillableBase : public Shape, FilledRectangle : public RectangleBase, public FillableBase. Complexity: increases significantly, harder to understand relationships. Benefits: model complex real-world hierarchies (e.g., objects with multiple capabilities). Challenges: ambiguity, virtual base initialization, maintenance. Virtual inheritance: class RectangleBase : virtual public Shape resolves diamond. Initialization order: virtual bases initialized before non-virtual. Methods: resolving which method to call requires careful analysis. Best practice: minimize, document clearly, consider composition instead. Example resolution: FilledRectangle calls both draw() from shape and fill() from fillable. Debugging: complex diamond problems hard to debug. Alternative: composition - FilledRectangle has Shape, Fill components instead. Modern design: hybrid inheritance rare in modern code, prefer composition. Understanding hybrid inheritance important for working with legacy systems.
469. What is multipath inheritance in C++?
Show hintHide hint
Diamond problem - multiple paths to same base class.
Show answerHide answer
Answer: A. Single class accessed through multiple paths
Multipath inheritance (diamond inheritance): derived class reachable through multiple inheritance paths. Classic diamond: A is base, B inherits A, C inherits A, D inherits B and C. D has two paths to A (D->B->A and D->C->A). Problem without virtual: A instantiated twice, ambiguous member access, wasted memory. Without virtual base: D has two A sub-objects (one via B, one via C). Accessing: member of A ambiguous - d.member? comes from B's A or C's A? Solution: virtual inheritance. class B : virtual public A makes A virtual base. class C : virtual public A shared copy of A. With virtual: D has single A instance. Initialization: D() : B(), C(), A() explicitly initializes virtual base. Member access: d.member unambiguous. Virtual function calls resolved correctly. Example: Unix file system (File), Symbolic file (inherits File), Hard link (inherits File), Union (inherits both) - same file accessed through two paths. Real-world example: Multiple interface implementation. Cost: virtual inheritance adds indirection (pointer to virtual base), slightly slower access. Best practice: document virtual inheritance clearly, test thoroughly. Ambiguity without virtual: D d; d.member error (ambiguous). With virtual: works correctly. Avoid unless necessary: increases complexity. Alternative: use interfaces/mixins. Understanding multipath inheritance crucial for working with complex diamond hierarchies.
470. What are constructors and destructors in inheritance?
Show hintHide hint
When Derived created, does Base also initialize? Destruction order?
Show answerHide answer
Answer: B. Base and derived constructors both called, destructors in reverse order
Constructor/destructor in inheritance: automatic chain calling, specific order. Constructor order: Base first, then Derived. Example: class Base { public: Base() { cout << "Base"; } }; class Derived : public Base { public: Derived() : Base() { cout << "Derived"; } }; Derived d; outputs "BaseDerived". Destructor order: Derived first, then Base (reverse of construction). ~Derived() called first, then ~Base() automatically. Destructor chain: ~Derived() { cout << "~Derived"; } calls ~Base() implicitly. Purpose: base resource cleanup after derived cleanup. Virtual destructor: important for polymorphism. Base *b = new Derived(); delete b; without virtual ~Base(), calls only ~Base(). With virtual: calls ~Derived() then ~Base(). Initialization list: Derived(int x) : Base(x), member(x) { }. Explicit base call: must chain if base has no default constructor. Constructor inheritance (C++11): using Base::Base; inherits base constructors. Delegating constructor: Derived() : Derived(0) { } calls another derived constructor. Example multilevel: class A { }; class B : public A { }; class C : public B { }; creating C calls A(), then B(), then C(). Destruction: ~C(), then ~B(), then ~A(). Virtual base: virtual base initialized before non-virtual bases. Parameterized base: must explicitly initialize. Exception safety: if derived constructor throws before base initialization, undefined. Best practice: explicit constructor chains, virtual destructors in polymorphic classes. Understanding constructor/destructor order crucial for resource management in inheritance.
471. What is operator overloading in C++?
NEC model setShow hintHide hint
Overloading modifies how an existing operator works with different data types.
Show answerHide answer
Answer: C. Changing the behaviour of an existing operator
Operator overloading in C++ is the ability to redefine how existing operators (+, -, *, /, ==, etc.) work with user-defined types (classes). You cannot define entirely new operators (option 1 and 4 are incorrect). You don't simply override existing operators without a context (that's not what overloading means). Instead, operator overloading allows you to change the behavior of an existing operator to work with your custom classes. For example: class Complex { public: Complex operator+(const Complex& other) { ... } }; This redefines the '+' operator for Complex numbers. Benefits of operator overloading: (1) Makes code more intuitive and readable, (2) Allows natural syntax for custom types, (3) Maintains consistency with built-in types. Restrictions: Cannot overload (::, ., .*, ?:), must overload as member function (=, [], (), ->), cannot change operator precedence or associativity.
472. What happens when a derived class overrides a base class method?
NEC model setShow hintHide hint
Method overriding means derived version takes precedence over base version.
Show answerHide answer
Answer: B. Derived class method replaces base class method
When a derived class overrides a base class method, the derived class method replaces base class method in normal polymorphic behavior. Method overriding mechanism: (1) Derived class defines method with same signature as base, (2) When called on derived object - Derived version executes, (3) Allows customization - Different behavior in derived class, (4) Fundamental to polymorphism. How overriding works: (1) Base class defines virtual method, (2) Derived class redefines with same signature, (3) Polymorphic call through base pointer/reference - Calls derived version, (4) Determined at runtime - Dynamic binding. Example: class Base { virtual void func() { cout << "Base"; } }; class Derived : public Base { void func() { cout << "Derived"; } }; Base *ptr = new Derived(); ptr->func(); // Outputs "Derived". Access mechanisms: (1) Polymorphic (through base ptr/ref) - Calls derived version, (2) Direct - obj.func() calls derived if obj is derived type, (3) Explicit base call - Base::func() from derived class. Virtual requirement: (1) Base method must be virtual - To enable overriding, (2) Non-virtual - Compile-time binding, base version called, (3) override keyword - C++11+ marks intent. Different from overloading: (1) Overloading - Same name, different parameters, (2) Overriding - Same name, same parameters, inheritance. Special methods: (1) Destructors - Should be virtual if inheritance used, (2) Constructors - Cannot be virtual, each class has own, (3) Operators - Can be overridden. Both running - No, one or the other. Errors - No, valid OOP pattern. This is core polymorphism concept.
473. When a derived class inherits from a base class, which constructor is executed first?
Recalled from Jan 2026 examShow hintHide hint
Constructor execution follows a specific order in inheritance. What is the sequence?
Show answerHide answer
Answer: B. Base class constructor, then derived class constructor
When a derived class inherits from a base class, the base class constructor is executed first, then the derived class constructor. This order ensures that the base class object is properly initialized before the derived class initializes its additional members. If the base class constructor isn't called explicitly, the compiler calls a default or implicit constructor. This initialization order is important because the derived class might depend on proper initialization of inherited members. The reverse order (destructors) applies in reverse - derived class destructor first, then base class destructor.
474. What is the main advantage of hybrid inheritance?
Recalled from Jan 2026 examShow hintHide hint
Hybrid inheritance combines multiple inheritance types. What's the primary benefit?
Show answerHide answer
Answer: A. Code reusability
The main advantage of hybrid inheritance is code reusability. Hybrid inheritance combines multiple inheritance types (single, multilevel, multiple, hierarchical) to leverage features from multiple base classes. This allows a derived class to inherit code and functionality from multiple sources, reducing code duplication and promoting modularity. With proper design using hybrid inheritance, developers can build complex class hierarchies that maximize code reuse. While hybrid inheritance is powerful, it can introduce complexity (diamond problem) if not carefully designed. Languages like C++ support hybrid inheritance; some languages like Java restrict it to avoid these complications.
475. Which operator cannot be overloaded in C++?
Show answerHide answer
Answer: B. :: and ->
476. Which of the following operators can be overloaded in C++?
Show answerHide answer
Answer: D. All of the above
477. Which access specifier allows a derived class to access the protected members of its base class?
Show answerHide answer
Answer: C. protected
478. Which of the following operators can be overloaded to provide custom member access behavior?
Show answerHide answer
Answer: B. ->
3.5 Pure virtual functions and file handling
10 questions · ACtE0305
479. Virtual functions are accessed through?
Show hintHide hint
Polymorphism works through pointers/references.
Show answerHide answer
Answer: D. Object pointers
Virtual functions are accessed through object pointers or references to enable polymorphic behavior.
480. What is purpose of 'override' keyword in C++?
Show hintHide hint
Ensures correct virtual function overriding.
Show answerHide answer
Answer: B. Indicate function is override of virtual function
'override' keyword explicitly declares that a function overrides a virtual base class function, catching errors at compile time.
481. What OOP concept allows different classes to be treated as common base?
Show hintHide hint
Many forms, one interface.
Show answerHide answer
Answer: C. Polymorphism
Polymorphism allows objects of different classes to be treated through common base class interface.
482. What are virtual functions in C++?
Show hintHide hint
virtual void func() enables derived override, correct version called at runtime.
Show answerHide answer
Answer: B. Functions supporting runtime polymorphism through dynamic dispatch
Virtual functions: enable runtime polymorphism, correct derived version called through base pointer/reference. Declaration: virtual void func() { }. Override: derived redefines with same signature. Dynamic dispatch: selecting method based on actual object type, not pointer type. Example: class Shape { virtual void draw() { } }; class Circle : public Shape { void draw() override { cout << "Circle"; } }; Shape *s = new Circle(); s->draw() calls Circle::draw(), not Shape::draw(). V-table: compiler creates virtual method table for each class. Virtual call: looks up v-table entry, calls appropriate function. Cost: pointer dereference (slight performance hit). Non-virtual: call resolved at compile time (fast). Pure virtual: virtual void func() = 0; abstract function. Abstract class: cannot instantiate, must override pure virtuals in derived. Final (C++11): virtual void func() final; prevents further overriding. Override (C++11): void func() override; ensures overriding virtual function (compiler error if not). Example: class Animal { virtual void sound() { } }; class Dog : public Animal { void sound() override { cout << "Woof"; } }. Polymorphic call: vector<Animal*> animals; for(auto a : animals) a->sound() calls appropriate version. Without virtual: all calls resolve to Shape::draw() (no polymorphism). Inheritance hierarchy: virtual defined at any level works through whole hierarchy. Base class pointer: can point to any derived object, virtual ensures correct behavior. Virtual destructor: essential for polymorphism (discussed separately). Understanding virtual functions fundamental to OOP and polymorphism.
483. What is dynamic binding in C++?
Show hintHide hint
vs static binding (compile-time), dynamic binding checks actual object type.
Show answerHide answer
Answer: B. Resolving virtual function calls at runtime based on actual object type
Dynamic binding: runtime resolution of method calls based on actual object type, not apparent type. Enabled by: virtual functions + polymorphism. Static binding: compile-time resolution (normal functions). Example: class Animal { public: virtual void speak() { } }; class Dog : public Animal { public: void speak() { cout << "Woof"; } }; Animal *a = new Dog(); a->speak() uses dynamic binding, calls Dog::speak(). Without virtual: static binding, calls Animal::speak(). How it works: (1) Base pointer/reference holds derived object. (2) Virtual function call. (3) Compiler generates code to look up v-table at runtime. (4) Finds correct function for actual type. (5) Calls derived implementation. V-table lookup: small overhead (pointer dereference, array lookup). Multiple dispatch: single dispatch (C++) vs multiple dispatch (Visitor pattern). Performance: slightly slower than static (1-3% typically). Optimization: compiler may devirtualize if type known. Example without dynamic binding: Shape *s = new Circle(); if(typeid(*s)==typeid(Circle)) ((Circle*)s)->draw() - ugly and slow. With dynamic binding: s->draw() - clean and still polymorphic. Polymorphic collections: vector<Shape*> shapes; shapes.push_back(new Circle()); shapes.push_back(new Square()); for(auto s : shapes) s->draw() works correctly. Design pattern: enables extensible code (new derived classes without changing code using base). Cost-benefit: small performance cost for huge design flexibility. Understanding dynamic binding crucial for polymorphic design.
484. What is the difference between ifstream and ofstream in C++?
NEC model setShow hintHide hint
'i' = input, 'o' = output. The prefix clearly indicates the direction of data flow.
Show answerHide answer
Answer: A. ifstream is used for input, while ofstream is used for output
In C++, ifstream and ofstream are file stream classes from the <fstream> library: (1) ifstream (input file stream) - Used for reading data from files. Opens files in input mode by default. (2) ofstream (output file stream) - Used for writing data to files. Opens files in output mode by default. Additional file stream classes: (3) fstream - Can be used for both input and output operations, requiring explicit specification of mode. Usage examples: ifstream infile("input.txt"); // Opens for reading, ofstream outfile("output.txt"); // Opens for writing. These classes inherit from basic_istream and basic_ostream respectively. They automatically handle file opening and closing (destructor closes file). They support operators (>> for input, << for output) making file I/O similar to console I/O. Using the appropriate stream class improves code clarity and prevents accidental operations on files.
485. How do you declare a virtual function in C++?
NEC model setShow hintHide hint
Virtual keyword comes before the return type. What's the correct syntax?
Show answerHide answer
Answer: A. virtual void func();
Virtual functions are declared using the 'virtual' keyword before the return type: 'virtual void func();'. The virtual keyword enables dynamic (runtime) polymorphism. When a virtual function is called through a pointer or reference, the appropriate overridden version in the derived class is executed. Virtual functions must be member functions and cannot be static or friends. They are fundamental to implementing polymorphic behavior in C++.
486. Which file stream flag in C++ is used to position the file pointer at the start of the file?
Recalled from Jan 2026 examShow hintHide hint
File seeking position flags. What flag positions at the beginning?
Show answerHide answer
Answer: B. ios::beg
The ios::beg file stream flag in C++ is used to position the file pointer at the start of the file. This flag is used with the seek() function: file.seekg(0, ios::beg) positions the pointer at the file's beginning. ios::end positions at the end. ios::cur positions relative to current location. These flags are fundamental to file I/O operations for random access. They work with both input (seekg) and output (seekp) operations.
487. Which C++ header file must be included to use the ifstream class for file input?
Recalled from Jan 2026 examShow hintHide hint
File stream classes (ifstream, ofstream, fstream) are in which header?
Show answerHide answer
Answer: B. <fstream>
The <fstream> header file must be included to use the ifstream class for file input in C++. fstream stands for file stream and contains the file stream classes: ifstream (input), ofstream (output), and fstream (both). iostream contains console I/O classes (cin, cout). stdio.h is C-style file I/O. iomanip provides formatting manipulators. Including <fstream> provides all necessary file I/O functionality.
488. Can a virtual function be inline in C++?
Show answerHide answer
Answer: B. No, virtual functions cannot be inline in C++
3.6 Generic programming and exception handling
16 questions · ACtE0306
489. How is exception handling implemented in C++?
Show hintHide hint
Typical exception handling structure.
Show answerHide answer
Answer: B. Using try-catch block
C++ exception handling uses try-catch-throw mechanism where try contains code that might throw, catch handles thrown exceptions.
490. What is throw keyword in C++?
Show hintHide hint
Initiates exception handling.
Show answerHide answer
Answer: B. Throws exceptions
throw keyword throws an exception, transferring control to nearest catch block.
491. What is exception handling in C++ - try, catch, throw?
Show hintHide hint
try block executes, throw propagates error, catch handles.
Show answerHide answer
Answer: B. Mechanism for managing errors and abnormal conditions
Exception handling: mechanism to gracefully handle errors and exceptional conditions. Three components: (1) Try: wraps code that might throw. (2) Catch: handles thrown exception. (3) Throw: signals error, passes control to catch. Syntax: try { /* code */ } catch(ExceptionType e) { /* handle */ }. Example: try { int x = stoi("abc"); } catch(invalid_argument e) { cout << "Invalid"; }. Multiple catch: try { /* code */ } catch(DivideByZero e) { } catch(OutOfRange e) { }. Catch-all: catch(...) { } catches any exception. Throw: throw std::runtime_error("Error message"); creates and throws exception object. Exception propagation: unhandled exception propagates up call stack. Example: void func() { throw runtime_error("Error"); } main calls func, error propagates. Standard exceptions: runtime_error, invalid_argument, out_of_range, bad_alloc, etc. Custom exceptions: class MyException : public std::exception { }. What throws: throw MyException("Custom error"). Cleanup: destructors called during unwinding (RAII cleanup). Const &: catch(const std::exception& e) preferred (polymorphic handling). STL containers: throw out_of_range, bad_alloc. Re-throw: catch { /* handle */ throw; } re-throws original exception. Nested try-catch: try inside catch block. Exception safety: noexcept void func() noexcept; specifies no exceptions. Benefits: error handling decoupled from normal flow, clear error codes (exception type). Disadvantages: overhead (performance), complex control flow. Best practice: throw early (detect errors quickly), catch specific exceptions, clean up in destructors. Understanding exception handling essential for robust error management.
492. What are function templates in C++?
Show hintHide hint
template<typename T> T max(T a, T b) - one function for all types.
Show answerHide answer
Answer: B. Generic functions working with multiple types
Function templates: generic functions accepting type parameters, one template generates multiple concrete functions. Syntax: template<typename T> T func(T a, T b) { /* implementation */ }. Usage: int x = max(5, 3); double y = max(3.5, 2.1); string z = max("abc", "xyz"); one template, three specializations generated. Type deduction: compiler deduces T from arguments (or explicitly max<int>(5, 3)). Multiple type parameters: template<typename T, typename U> T func(T a, U b) { }. Non-type parameters: template<int N> void func() { }; fixed N at compile-time. Default type parameters: template<typename T = int> T func() { }. Constraints: template applies to all types unless constrained. Specialization: explicit specialization for specific type. Example: template<> string func<string>(string a, string b) { special handling }. Advantages: code reuse across types, type-safe, compiler optimizations. Disadvantages: compilation slower (instantiation), error messages complex, larger executable. Instantiation: compiler creates function for each type used. Example: max template instantiated for int, double, string separately. Performance: no runtime overhead (generated at compile-time). SFINAE: substitution failure is not an error (advanced). Concepts (C++20): specify type requirements. Example swap template: template<typename T> void swap(T& a, T& b) { T t=a; a=b; b=t; }. STL: all STL algorithms templates (sort, find, transform). Understanding function templates essential for generic programming.
493. What are class templates in C++?
Show hintHide hint
template<typename T> class Container { T data; }; Container<int>, Container<string>, etc.
Show answerHide answer
Answer: B. Generic classes accepting type parameters
Class templates: generic classes accepting type parameters, creating type-specific classes. Syntax: template<typename T> class MyClass { private: T data; public: void set(T val) { data = val; } T get() { return data; } }. Usage: MyClass<int> intObj; MyClass<string> strObj; MyClass<double> doubleObj. Instantiation: compiler generates three different classes (MyClass<int>, MyClass<string>, etc.). Member functions: all members work with type T. Multiple type parameters: template<typename T, typename U> class Pair { T first; U second; }. Static members: each instantiation has own static member. Example: vector, list, map, set are class templates. Specialization: explicit specialization for specific type. Example: template<> class MyClass<string> { special implementation }. Partial specialization: template<typename T> class MyClass<T*> { /* pointer specialization */ }. Inheritance: class Derived : public MyClass<int> { }. Constraints: template<typename T> requires Addable<T> class MyClass (C++20). Advantages: strong type safety, no void pointer casts, flexibility. Disadvantages: code bloat (separate code for each type), longer compilation, complex error messages. STL containers: vector<T>, list<T>, set<T>, map<K,V> are class templates. Default type: template<typename T = int> class MyClass. Non-type parameters: template<typename T, int N> class Array { T data[N]; }. Understanding class templates fundamental to modern C++ and generic containers.
494. What is the Standard Template Library (STL) in C++?
Show hintHide hint
vector, list, map, sort, find, for_each - these are STL components.
Show answerHide answer
Answer: B. Collection of generic containers, algorithms, and iterators
STL: provides generic, reusable components. Three main parts: (1) Containers: data structures (vector, list, deque, set, map, etc.). (2) Algorithms: operations on containers (sort, find, transform, etc.). (3) Iterators: generalized pointers for container traversal. Containers: sequential (vector, list, deque), associative (set, map, multiset, multimap), unordered (unordered_set, unordered_map). Algorithms: sorting (sort, stable_sort), searching (find, binary_search, lower_bound), modification (transform, copy), numeric (accumulate, inner_product). Iterators: input, output, forward, bidirectional, random access. Example: vector<int> v = {3,1,4,1,5}; sort(v.begin(), v.end()); find(v.begin(), v.end(), 4). Advantages: proven, optimized implementations, consistency across containers, flexibility. Iterator abstraction: algorithms work with any container. Example: sort works on vector, deque, arrays (with different iterators). Functional objects: std::less, std::greater for custom comparison. Lambda expressions: algorithm callbacks. Example: sort(v.begin(), v.end(), [](int a, int b) { return a > b; }) sorts descending. Performance: optimized implementations (O(n log n) sort), cache-friendly. Containers: O(1) or O(log n) operations. Learning curve: steep for complex usage, but mastering STL essential for modern C++. Understanding STL fundamental to effective C++ programming.
495. What are iterators in STL?
Show hintHide hint
v.begin(), v.end(), ++it, *it - iterator operations.
Show answerHide answer
Answer: B. Generalized pointers for container traversal
Iterators: generalized pointers allowing access and traversal of container elements. Categories: (1) Input: read-only, single-pass. (2) Output: write-only, single-pass. (3) Forward: read-write, single-pass. (4) Bidirectional: read-write, bidirectional (++, --). (5) Random access: read-write, random (+=, -=, [i]). Operations: *it (dereference), ++it (increment), it->member (member access). Example: vector<int> v = {1,2,3}; for(auto it = v.begin(); it != v.end(); ++it) cout << *it;. Range-based for: for(int x : v) simpler, equivalent. Type: vector<int>::iterator, list<int>::iterator (different types). Const iterator: const_iterator read-only, reverse_iterator backwards. Algorithms: work with iterators. Example: find(v.begin(), v.end(), 2) finds element 2. Distance: distance(it1, it2) steps between iterators (random access O(1), bidirectional O(n)). Advance: advance(it, n) moves iterator n positions. Invalid iterators: after erase, capacity change invalidates (container dependent). Performance: O(1) dereference, O(1) increment (forward+). Container choice affects iterator type. Example: vector (random), list (bidirectional), set (bidirectional). Advantages: algorithm abstraction (same algorithm works on any container), clean syntax. Disadvantages: confusing at first, need to understand category constraints. Invalidation rules: erase invalidates following iterators in vector, all in list. Understanding iterators essential for STL and generic algorithms.
496. What is the difference between containers in STL?
Show hintHide hint
vector vs list vs set - what are tradeoffs?
Show answerHide answer
Answer: B. Different data structures optimized for different use cases
STL Containers: different data structures, different performance characteristics. vector<T>: dynamic array, O(1) random access, O(1) push_back, O(n) insert/erase middle. Use: fast access, append. list<T>: doubly-linked list, O(n) access, O(1) insert/erase anywhere, bidirectional. Use: frequent insertion/deletion. deque<T>: double-ended queue, O(1) access/push_pop front-back, O(n) insert/erase middle. Use: queues. set<T>: ordered tree, O(log n) operations, unique elements. Use: sorted unique collection. map<K,V>: ordered tree, O(log n) lookup/insert/erase, key-value pairs. Use: associative array. unordered_set<T>: hash table, O(1) average operations, unordered. Use: fast unique lookup. unordered_map<K,V>: hash table, O(1) average lookup. Use: fast dictionary. multiset<T>/multimap<K,V>: allow duplicates. priority_queue<T>: heap, O(1) top, O(log n) push/pop. Use: priority queues. Stack (LIFO): vector/deque/list adapter, LIFO access. Queue (FIFO): vector/deque/list adapter, FIFO access. Choice criteria: (1) Access pattern (random vs sequential). (2) Insertion/deletion (frequent?). (3) Search (ordered vs fast). (4) Memory (linked lists use more). Example: log file processing (vector append), network packet processing (queue), priority events (priority_queue), cache (unordered_map). Performance comparison: access time, insertion time, deletion time, memory overhead. Selecting container crucial for application performance. Understanding container tradeoffs essential for algorithm optimization.
497. What are STL algorithms?
Show hintHide hint
sort, find, transform, copy - operations on containers.
Show answerHide answer
Answer: B. Generic functions operating on containers via iterators
STL algorithms: generic functions performing operations on container ranges via iterators. Categories: (1) Sorting: sort(), stable_sort(), partial_sort(), nth_element(). (2) Searching: find(), binary_search(), find_if(), lower_bound(), upper_bound(). (3) Mutation: transform(), fill(), replace(), shuffle(). (4) Removal: remove(), unique(). (5) Numeric: accumulate(), inner_product(), partial_sum(). (6) Iteration: for_each(), transform(). Examples: vector<int> v = {3,1,4,1,5,9}; sort(v.begin(), v.end()). auto it = find(v.begin(), v.end(), 4); transform(v.begin(), v.end(), v.begin(), [](int x) { return x*2; }). Advantages: (1) Container-independent (work with any container). (2) Efficient implementations. (3) Consistent interface. (4) Composable. Predicates: custom comparison/condition. Example: sort(v.begin(), v.end(), greater<int>()) descending. Lambda expressions: inline predicates. Example: find_if(v.begin(), v.end(), [](int x) { return x > 3; }). Non-modifying: find, count, search. Modifying: sort, reverse, rotate, shuffle. Performance: sort O(n log n), find O(n), binary_search O(log n). Ranges (C++20): easier syntax, same algorithms. Understanding algorithms enables powerful generic code. Writing efficient algorithms crucial for performance.
498. What is multiple exception handling in C++?
Show hintHide hint
try { } catch(TypeA) { } catch(TypeB) { } catch(...) { }
Show answerHide answer
Answer: B. Catching different exception types in separate catch blocks
Multiple exception handling: try block with multiple catch blocks for different exception types. Syntax: try { /* code */ } catch(ExceptionType1 e) { /* handle type 1 */ } catch(ExceptionType2 e) { /* handle type 2 */ } catch(...) { /* handle any */ }. Order matters: catch blocks checked in order, first matching catches. Example: try { int x = stoi("abc"); int y = 10/0; } catch(invalid_argument& e) { cout << "Invalid arg: " << e.what(); } catch(exception& e) { cout << "General error: " << e.what(); }. Specific to general: more specific exceptions first (derived class before base). Exception hierarchy: std::exception base, runtime_error, invalid_argument, out_of_range derived. Polymorphic catch: catch(const std::exception& e) catches any standard exception. What(): get error message string. Custom exceptions: class MyError : public std::exception { public: const char* what() const override { return "My error"; } }. Multiple sources: different operations throw different exceptions. Example: parsing code - invalid_argument, encoding error, file read - io_error. Catch-all: catch(...) { } last resort, catches anything (even non-standard). Re-throw: catch(MyException& e) { log(e); throw; } re-throws original. Chaining: catch one exception type, throw another. Example: catch(FileNotFound& e) { throw ProcessingError(e); }. Exception safety: strong guarantee (all-or-nothing), basic guarantee (some recovery). Best practice: specific catches first, catch-all last or omit, throw appropriate types. Understanding multiple exception handling essential for robust error management.
499. What is a class template in C++?
NEC model setShow hintHide hint
Templates enable generic programming. A template class can work with any data type.
Show answerHide answer
Answer: A. A class that can be used to create objects of different types
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 data type is parameterized. Key concepts: (1) Templates use template parameters (usually template<typename T>), (2) You can use the parameter T as any data type within the class, (3) Instantiation creates specific classes for each data type used. Example: template<typename T> class Stack { private: T data[100]; }; This creates a Stack that works with any type. Usage: Stack<int> intStack; Stack<double> doubleStack; Both are created from the same template. Benefits: (1) Code reusability across different data types, (2) Type safety (templates are type-checked at compile time), (3) No runtime overhead. Class templates are fundamental to the Standard Template Library (STL) which provides containers like vector, list, map using templates. This differs from function templates (which template functions) or variable templates (C++14).
500. What happens if an exception is thrown but not caught?
NEC model setShow hintHide hint
Unhandled exceptions cause the program to stop. What happens to the program?
Show answerHide answer
Answer: C. Program crashes or terminates
If an exception is thrown but not caught by any try-catch block, the program terminates or crashes. The exception propagates up the call stack looking for a handler. If no handler is found, the program crashes with an error. In some systems, an uncaught exception handler might log the error before terminating. Proper exception handling requires using try-catch blocks to gracefully handle errors and prevent program termination.
501. What is an exception in object-oriented programming?
Recalled from Jan 2026 examShow hintHide hint
Exceptions are abnormal conditions during program execution. What are they?
Show answerHide answer
Answer: A. A special function
An exception in object-oriented programming is a special function or mechanism that handles abnormal conditions during program execution. When an error or exceptional situation occurs, an exception is thrown, interrupting normal program flow. The program then jumps to exception handlers (catch blocks) that deal with the problem. Exceptions allow graceful error handling instead of program crashes. They're not a type of inheritance, method, or regular class, but rather a control flow mechanism. Exception handling improves program robustness and maintainability by separating error handling code from normal logic.
502. In the Standard Template Library (STL), what do containers primarily hold?
Recalled from Jan 2026 examShow hintHide hint
STL containers are data structures. What do they store and manage?
Show answerHide answer
Answer: B. Data elements and their organization
In the Standard Template Library (STL), containers primarily hold data elements and their organization. Containers are template classes that manage collections of data with different organizational structures (vector, list, queue, stack, map, etc.). Each container type organizes data differently to optimize specific operations. Containers provide iterators for traversing elements and algorithms operate on container data through iterators. Functions and algorithms are separate STL components. Iterators are access mechanisms, not what containers hold. Memory addresses are implementation details, not the primary purpose.
503. Which of the following is true about default arguments and templates?
Show answerHide answer
Answer: C. Default arguments can be used in templates for any number of parameters
504. Containers are contained within?
Past questionShow hintHide hint
Containers can be nested inside other containers. What holds multiple items?
Show answerHide answer
Answer: C. Containers
Containers are contained within Containers (nested containers). Container Concept: (1) Data structures that hold multiple items, (2) Examples: arrays, lists, maps, sets, (3) Can contain primitive types or other containers. Nesting in Containers: (1) Containers can hold other containers, (2) Example: vector of vectors (2D array), (3) Example: map of lists (key→list), (4) Unlimited nesting levels possible. Nested Container Examples: (1) Vector<Vector<int>> - 2D matrix, (2) Map<String, List<String>> - Each key maps to list, (3) Set<Vector<int>> - Set of vectors, (4) List<Map<int, String>> - List of maps. C++ STL Containers: (1) Sequence containers - vector, list, deque, (2) Associative - map, set, multimap, (3) Unordered - unordered_map, unordered_set. Why Nesting Matters: (1) Represents hierarchical data, (2) Models real-world structures, (3) Solves complex problems, (4) Enables powerful algorithms. Other Options Explanation: (1) Function - Functions are not containers for other functions (in standard sense), (2) String - String contains characters, not containers, (3) Elements - Elements are items in containers, not containers themselves. Practical Applications: (1) File systems - Directories within directories, (2) XML/JSON - Nested structures, (3) Graphs - Containers of nodes/edges, (4) Game development - Nested game objects. Memory Considerations: (1) Nested containers use more memory, (2) Deep nesting can cause stack overflow, (3) Performance implications with large data. This demonstrates data structure composition.