Getting ready for the final term of CS201 (Introduction to Programming)? Here is everything in one place: solved MCQs, subjective questions with answers and short notes and key terms, gathered from past papers and files shared by students. No duplicates and all the answers are checked and verified. Use the tabs above to switch between Objective, Subjective and Short Notes & Key Terms, and tap Show answer only after you have tried the question yourself. Best of luck with your exam!
Part 1: Objective (MCQs)
Q1. A matrix is commonly represented in C++ as which of the following?
- Single-dimensional array
- Multidimensional array
- Vector product
- Scalar product
Show answer
Answer: (b) Multidimensional array
Handout reference: Lecture 12, p. 120
Q2. Which of the following correctly declares main() with conventional command-line parameters?
- float argc, char **argv
- int argc, char **argv
- int *argc, char *argv
- int argc, float **argv
Show answer
Answer: (b) int argc, char **argv
Handout reference: Lecture 16, p. 177
Q3. In pass-by-reference, what is passed so the function can modify the original variable?
- Only a copy of its value
- Access to the original variable through a reference
- A new independent local copy
- A textual representation of the variable
Show answer
Answer: (b) Access to the original variable through a reference
Handout reference: Lecture 10, p. 94
Q4. Both endl and flush are examples of which of the following?
- Functions unrelated to streams
- Arithmetic operators
- Stream manipulators
- Data objects
Show answer
Answer: (c) Stream manipulators
Handout reference: Lecture 36, p. 432
Q5. What are the first and second parameters of an overloaded stream-insertion operator?
- Input stream, class object
- Class object, output stream
- Output stream, class object
- Class object, input stream
Show answer
Answer: (c) Output stream, class object
Handout reference: Lecture 37, p. 445
Q6. How must the first parameter of an overloaded stream-insertion (<<) operator be passed?
- By value
- By reference
- By either value or reference
- As an object of the user-defined class
Show answer
Answer: (b) By reference
Handout reference: Lecture 37, p. 445
Q7. What is an appropriate data type for storing the number of rows and columns in a matrix?
- float
- string
- int
- char
Show answer
Answer: (c) int
Handout reference: Lecture 43, p. 521
Q8. What does ANSI stand for?
- American Neutral Standards Institute
- Australian National Standards Institute
- Asian National Standards Institute
- American National Standards Institute
Show answer
Answer: (d) American National Standards Institute
Handout reference: Lecture 2, p. 11
Q9. The member-initializer list initializes contained class objects at which stage?
- Run time after all constructors finish
- Debugging time
- Construction time
- Compilation time
Show answer
Answer: (c) Construction time
Handout reference: Lecture 40, p. 482
Q10. In a C++ member-initializer list, data members are initialized in which order?
- Left to right as written in the initializer list
- Right to left in the initializer list
- The order of their declarations in the class
- There is no defined order
Show answer
Answer: (c) The order of their declarations in the class
Handout reference: Lecture 40, p. 482
Q11. Which function is NOT an input-stream member function?
- getline()
- peek()
- unget()
- write()
Show answer
Answer: (d) write()
Handout reference: Lecture 35, p. 428
Q12. When an object is a data member of another class, whose constructor is called first?
- The enclosing class constructor
- The contained object constructor
- Both constructors simultaneously
- Only the destructor
Show answer
Answer: (b) The contained object constructor
Handout reference: Lecture 40, p. 481
Q13. In what order are destructors called relative to constructor calls?
- The same construction order
- Reverse construction order
- An unspecified independent order
- The same order as variable declarations
Show answer
Answer: (b) Reverse construction order
Handout reference: Lecture 40, p. 480
Q14. The void* parameter of an overloaded operator delete function identifies what?
- The memory block to be deallocated
- All objects of the class
- An unused argument
- Nothing
Show answer
Answer: (a) The memory block to be deallocated
Handout reference: Lecture 34, p. 412
Q15. What pointer type is returned by C allocation functions such as malloc()?
- int*
- double*
- void*
- char*
Show answer
Answer: (c) void*
Handout reference: Lecture 28, p. 329
Q16. C++ new and delete can be used with which categories of data types?
- Loops only
- Structures and pointers only
- Class and primitive data types
- Constants only
Show answer
Answer: (c) Class and primitive data types
Handout reference: Lecture 28, p. 331
Q17. A friend function of a C++ class is which of the following?
- A private member function
- A non-member function
- A public member function
- An ordinary member function
Show answer
Answer: (b) A non-member function
Handout reference: Lecture 31, p. 373
Q18. What does the declaration Date operator++(int); inside class Date represent?
- A member postfix-increment operator
- A member prefix-increment operator
- A non-member postfix-increment operator
- A non-member prefix-increment operator
Show answer
Answer: (a) A member postfix-increment operator
Handout reference: Lecture 32, p. 388
Q19. Which kind of statement repeats an action while a condition remains true?
- Repetition statement
- Control declaration
- Conditional expression
- Assignment statement
Show answer
Answer: (a) Repetition statement
Handout reference: Lecture 6, p. 45
Q20. The ++ and -- operators increase or decrease an integer variable by how much?
- 3
- 2
- 1
- 4
Show answer
Answer: (c) 1
Handout reference: Lecture 7, p. 62
Q21. Which memory region is generally used by dynamic memory allocation?
- Stack
- Heap
- System cache
- Secondary storage
Show answer
Answer: (b) Heap
Handout reference: Lecture 24, p. 278
Q22. Which execution model processes statements until encountering an error in the statement being executed?
- Interpreter
- Compiler
- Linker
- Debugger
Show answer
Answer: (a) Interpreter
Handout reference: Lecture 2, p. 11
Q23. What is the return type of a function that returns no value?
- float
- int
- void
- double
Show answer
Answer: (c) void
Handout reference: Lecture 9, p. 78
Q24. Which is NOT a standard base-format flag or manipulator used to select decimal, octal, or hexadecimal output?
- oct
- hex
- dec
- bin
Show answer
Answer: (d) bin
Handout reference: Lecture 36, p. 439
Q25. What is the normal return type of an overloaded operator<< for output streams?
- The user-defined class
- std::ostream&
- std::istream&
- void
Show answer
Answer: (b) std::ostream&
Handout reference: Lecture 37, p. 445
Q26. An overloaded assignment operator (=) of a class must be which type of function?
- Friend function
- Non-member friend
- Non-member function
- Member function
Show answer
Answer: (d) Member function
Handout reference: Lecture 31, p. 373
Q27. What does cin.get() normally do when used with standard input?
- Read a string from the keyboard
- Read one character from the keyboard
- Read a string from a file
- Read a character from an arbitrary file
Show answer
Answer: (b) Read one character from the keyboard
Handout reference: Lecture 35, p. 428
Q28. At link time, library functions are ordinarily available in which form?
- Compiled object code
- Plain source text only
- Uncompiled source comments
- User interface code
Show answer
Answer: (a) Compiled object code
Handout reference: Lecture 23, p. 268
Q29. Which is the general declaration syntax for an overloaded operator function?
- return-type operator-symbol(parameter-list);
- operator return-type operator-symbol(parameter-list);
- return-type operator operator-symbol(parameter-list);
- return-type operator-symbol operator(parameter-list);
Show answer
Answer: (c) return-type operator operator-symbol(parameter-list);
Handout reference: Lecture 31, p. 369
Q30. Given class M { public: M operator+(const M&); };, the + operator is implemented as what?
- Member function
- Non-member function
- Friend function
- Virtual function
Show answer
Answer: (a) Member function
Handout reference: Lecture 31, p. 373
Q31. When is the expression exp1 && exp2 true?
- Only when both expressions are true
- Only when both are false
- When only exp1 is true
- When only exp2 is true
Show answer
Answer: (a) Only when both expressions are true
Handout reference: Lecture 5, p. 39
Q32. In top-down programming, decomposition into functions is associated with what approach?
- Object-oriented only
- Structured programming
- Assembly programming
- High-level language syntax only
Show answer
Answer: (b) Structured programming
Handout reference: Lecture 25, p. 291
Q33. A loop is also called what kind of control structure?
- Decision
- Repetition
- Sequential
- Hierarchical
Show answer
Answer: (b) Repetition
Handout reference: Lecture 6, p. 44
Q34. Which punctuation marks enclose a C++ character literal?
- Parentheses
- Single quotation marks
- Double quotation marks
- Curly braces
Show answer
Answer: (b) Single quotation marks
Handout reference: Lecture 3, p. 20
Q35. Which type stores a character such as a, b, or c?
- int
- double
- char
- float
Show answer
Answer: (c) char
Handout reference: Lecture 3, p. 20
Q36. What is the meaning of x += y;?
- Add y to x and store the result in x
- Add x to y and store in y
- Add x to itself
- Add y to itself and store in x
Show answer
Answer: (a) Add y to x and store the result in x
Handout reference: Lecture 7, p. 63
Q37. A variable declared inside a code block is normally a ______ variable for that block.
- Global
- Static
- Local
- Inner
Show answer
Answer: (c) Local
Handout reference: Lecture 10, p. 89
Q38. Allowing an outside function to declare itself a friend of a class would violate which principle?
- Data accessing
- Encapsulation and data hiding
- Public interfaces
- Function overloading
Show answer
Answer: (b) Encapsulation and data hiding
Handout reference: Lecture 29, p. 344
Q39. In older C++ stream classes, width(), fill(), and precision() are member functions provided through which stream header?
- conio.h
- iomanip.h
- iostream.h
- stdlib.h
Show answer
Answer: (c) iostream.h
Handout reference: Lecture 36, p. 438
Q40. The width() formatting member function can be called on which stream objects?
- cin only
- cout only
- Both cin and cout
- User-defined classes only
Show answer
Answer: (c) Both cin and cout
Handout reference: Lecture 36, p. 438
Q41. Which statement about static data members is true?
- They can never be public or private
- They must be private
- They must be public
- They may be declared public or private
Show answer
Answer: (d) They may be declared public or private
Handout reference: Lecture 38, p. 465
Q42. Which is a valid declaration of an overloaded operator new?
- void* new operator(size_t size);
- void* new(size_t size);
- operator new/(size_t size);
- void* operator new(size_t size);
Show answer
Answer: (d) void* operator new(size_t size);
Handout reference: Lecture 34, p. 414
Q43. Which is the correct preprocessor macro definition for PI?
- #undef PI 3.1415926
- #define PI 3.1415926
- #define PI = 3.1415926
- #ifdef PI = 3.1415926
Show answer
Answer: (b) #define PI 3.1415926
Handout reference: Lecture 23, p. 269
Q44. Which value is returned by the destructor of a class?
- A pointer to the class
- An object of the class
- A status code determining whether the class was destructed correctly
- Destructors do not return a value
Show answer
Answer: (d) Destructors do not return a value
Handout reference: Lecture 27, p. 321
Q45. Automatic variable are created on ________
- Heap
- Free store
- static storage
- stack
Show answer
Answer: (d) stack
Handout reference: Lecture 38, p. 459
Q46. In a flowchart, which symbol represents the flow of control?
- Rectangle
- Circle
- Diamond
- Arrow
Show answer
Answer: (d) Arrow
Handout reference: Lecture 5, p. 34
Q47. What is the first step in developing a computer program?
- Linking
- Debugging
- Analysis
- Loading
Show answer
Answer: (c) Analysis
Handout reference: Lecture 1, p. 6
Q48. Dereferencing operator is represented by
- *
- +
- -
- None of above
Show answer
Answer: (a) *
Handout reference: Lecture 14, p. 146
Q49. There are mainly -------------------- types of software
- Two
- Three
- Four
- Five
Show answer
Answer: (a) Two
Handout reference: Lecture 2, p. 8
Q50. When a pointer is incremented, it actually jumps the number of memory addresses
- According to data type
- 1 byte exactly
- 1 bit exactly
- A pointer variable cannot be incremented
Show answer
Answer: (a) According to data type
Handout reference: Lecture 15, p. 159
Q51. When an array is passed to a function then default way of passing this array is,
- By data
- By reference
- By value
- By data type
Show answer
Answer: (b) By reference
Handout reference: Lecture 12, p. 119
Q52. Skill(s) that is/are needed by programmers _______________________
- Paying attention to detail
- Think about the reusability
- Think about user interface
- All of the given options
Show answer
Answer: (d) All of the given options
Handout reference: Lecture 1, p. 3
Q53. UNIX has been developed in ________ language
- JAVA
- B
- C
- FORTRAN
Show answer
Answer: (c) C
Handout reference: Lecture 2, p. 11
Q54. Pointers store the ____________________
- value of a variable
- memory address
- characters
- None of the given
Show answer
Answer: (b) memory address
Handout reference: Lecture 14, p. 145
Q55. In C/C++ the string constant is enclosed ……………
- In curly braces
- In small braces
- In single quotes
- In double quotes
Show answer
Answer: (d) In double quotes
Handout reference: Lecture 12, p. 113
Q56. In Flow chart process is represented by
- Rectangle
- Arrow symbol
- Oval
- Circle
Show answer
Answer: (a) Rectangle
Handout reference: Lecture 5, p. 34
Q57. If the break statement is missed in switch statement then
- The compiler will give error
- This may cause a logical error
- No effect on program
- Program stops its execution
Show answer
Answer: (b) This may cause a logical error
Handout reference: Lecture 8, p. 68
Q58. How many total elements must be in two-dimensional array of 3 rows and 2 columns?
- 4
- 5
- 6
- 7
Show answer
Answer: (c) 6
Handout reference: Lecture 16, p. 172
Q59. Which of the following is the correct statement for the following declaration?const int *ptr;
- ptr is a constant pointer
- ptr is constant integer pointer
- ptr is a constant pointer to int
- ptr is a pointer to const int
Show answer
Answer: (d) ptr is a pointer to const int
Why: const int *ptr declares a pointer to a constant int.
Handout reference: Lecture 14, p. 144
Q60. Syntax of union is identical to ______
- Structure
- Class
- Function
- None of the given options
Show answer
Answer: (a) Structure
Handout reference: Lecture 20, p. 241
Q61. A character is stored in memory in
- byte
- integer
- string
- None of above
Show answer
Answer: (a) byte
Handout reference: Lecture 17, p. 186
Q62. _________ contain functions for manipulation of character data
- Ctype.h
- Iostream.h
- String.h
- None of the above
Show answer
Answer: (a) Ctype.h
Handout reference: Lecture 17, p. 187
Q63. In functions that return reference, use __________variables
- Local
- Global
- Global or static
- None of the given option
Show answer
Answer: (c) Global or static
Handout reference: Lecture 30, p. 364
Q64. What is the sequence of event(s) when allocating memory using new operator?
- Only block of memory is allocated for objects
- Only constructor is called for objects
- Memory is allocated first before calling constructor
- Constructor is called first before allocating memory
Show answer
Answer: (c) Memory is allocated first before calling constructor
Handout reference: Lecture 34, p. 412
Q65. new and delete are _____ whereas malloc and free are _____
- Functions, operators
- Classes, operators
- Operators, functions
- Operators, classes
Show answer
Answer: (c) Operators, functions
Handout reference: Lecture 28, p. 340
Q66. Like member functions, ______ can also access the private data members of a class
- Non-member functions
- Friend functions
- Any function outside class
- None of the given options
Show answer
Answer: (b) Friend functions
Handout reference: Lecture 29, p. 344
Q67. Which of the following statement is best regarding declaration of friend function?
- Friend function must be declared after public keyword
- Friend function must be declared after private keyword
- Friend function must be declared at the top within class definition
- It can be declared anywhere in class as these are not affected by the public and private
Show answer
Answer: (d) It can be declared anywhere in class as these are not affected by the public and private
Handout reference: Lecture 29, p. 344
Q68. The static data members of a class are initialized _______
- at file scope
- within class definition
- within member function
- within main function
Show answer
Answer: (a) at file scope
Handout reference: Lecture 38, p. 465
Q69. Which kind of functions can access private member variables of a class?
- Friend functions of the class
- Private member functions of the class
- Public member functions of the class
- Friend, private and public functions
Show answer
Answer: (d) Friend, private and public functions
Handout reference: Lecture 29, p. 344
Q70. When an array of objects is defined, how often is the constructor called?
- Constructor will be called once for whole array
- Constructor will be called for each object of the array
- Constructor will never call
- Depends on the size of array
Show answer
Answer: (b) Constructor will be called for each object of the array
Handout reference: Lecture 34, p. 407
Q71. The stream objects cin and cout are included in which header file?
- iostream.h
- fstream.h
- istream.h
- ostream.h
Show answer
Answer: (a) iostream.h
Handout reference: Lecture 36, p. 431
Q72. Missing semicolon ‘;’ at the end of C++ statement is
- Logical error
- Syntax error
- Runtime error
- None of the given options
Show answer
Answer: (b) Syntax error
Handout reference: Lecture 3, p. 15
Q73. Which of the following function calling mechanism is true for the function prototype given below? float func(float &)
- Call by value
- Call by reference using pointer
- Call by reference using reference variable
- None of the given options
Show answer
Answer: (c) Call by reference using reference variable
Handout reference: Lecture 30, p. 361
Q74. The region of memory, available for allocation at run time in C language is called ________ memory whereas in C++ language is called as ________________
- Heap, Stack
- Stack, Free Store
- Heap, Free Store
- None of above
Show answer
Answer: (c) Heap, Free Store
Handout reference: Lecture 28, p. 342
Q75. A variable which is defined inside a function is called
- Automatic variable
- Global variable
- Functional variable
- None of the given option
Show answer
Answer: (a) Automatic variable
Handout reference: Lecture 38, p. 458
Q76. Default mechanism of function calling in case of array is _____ and in case of variable is ___
- Call by value, call by reference
- Call by referene, call by reference
- Call by reference, call by value
- Call by value, call by value
Show answer
Answer: (c) Call by reference, call by value
Handout reference: Lecture 14, p. 153
Q77. What does STL stand for?
- Source template library
- Standard template library
- Stream template library
- Standard temporary library
Show answer
Answer: (b) Standard template library
Handout reference: Lecture 42, p. 517
Q78. For which array, the size of the array should be one more than the number of elements in an array?
- int
- double
- float
- char
Show answer
Answer: (d) char
Handout reference: Lecture 12, p. 112
Q79. While calling function, the arguments are assigned to the parameters from _____________
- left to right
- right to left
- no specific order is followed
- none of the given options
Show answer
Answer: (a) left to right
Handout reference: Lecture 25, p. 293
Q80. new operator allocates memory from free store and return _____________
- A pointer
- A reference
- An integer
- A float
Show answer
Answer: (a) A pointer
Handout reference: Lecture 28, p. 330
Q81. In if structure the block of statements is executed only,
- When the condition is false
- When it contain arithmetic operators
- When it contain logical operators
- When the condition is true
Show answer
Answer: (d) When the condition is true
Handout reference: Lecture 5, p. 32
Q82. Header file: fstream.h includes the definition of the stream classes __________
- ifstream, fstream, cout
- ifstream, fstream, ofstream
- fstream, cin, cout
- None of the above
Show answer
Answer: (b) ifstream, fstream, ofstream
Handout reference: Lecture 18, p. 198
Q83. To access the data members of structure _______ is used
- dot operator (.)
- * operator
- arrow operator (->)
- None of given
Show answer
Answer: (a) dot operator (.)
Handout reference: Lecture 20, p. 230
Q84. Classes defined inside other classes are called ________ classes
- looped
- nested
- overloaded
- none of the given options
Show answer
Answer: (b) nested
Handout reference: Lecture 40, p. 494
Q85. If constructor contains a return statement in its body then compiler will give __________
- No error
- Syntax error
- Logical error
- Run time error
Show answer
Answer: (a) No error
Why: A constructor may contain a plain return; (no value), so there is no error.
Handout reference: Lecture 27, p. 320
Q86. The keyword_______ is used to return some value from a function
- return
- break
- continue
- goto
Show answer
Answer: (a) return
Handout reference: Lecture 9, p. 78
Q87. The input/output streams cin and cout are ________ therefore have _______
- Structures, function
- Objects, member functions
- Functions, objects
- None of the given options
Show answer
Answer: (b) Objects, member functions
Handout reference: Lecture 35, p. 425
Q88. Assignment operator is -------------------------associative
- right
- left
- binary
- unary
Show answer
Answer: (a) right
Handout reference: Lecture 31, p. 370
Q89. Static variable which is defined in a function is initialized __________
- Only once during its life time
- Every time the function call
- Compile time of the program
- None of the above
Show answer
Answer: (a) Only once during its life time
Handout reference: Lecture 38, p. 460
Q90. A constructor that will create a new object with a full copy of the other object, is copy is known as ___________
- deep copy
- shallow copy
- constructor copy
- none of the options
Show answer
Answer: (a) deep copy
Handout reference: Lecture 39, p. 472
Q91. Overloaded new operator function takes parameter of type size_t and returns
- void (nothing)
- void pointer
- object pointer
- int pointer
Show answer
Answer: (b) void pointer
Handout reference: Lecture 34, p. 413
Q92. In C++, what does & indicate in a reference declaration and in an address-of expression, respectively?
- Address of variable, reference variable
- Reference variable, value of variable
- Reference variable, address of variable
- Address of variable, value of variable
Show answer
Answer: (c) Reference variable, address of variable
Handout reference: Lecture 30, p. 365
Q93. All preprocessor directives are started with the symbol______
- *
- ++
- @
- #
Show answer
Answer: (d) #
Handout reference: Lecture 23, p. 270
Q94. When we use manipulators in our program then which header file should be included?
- iostream.h
- stdlib.h
- stdio.h
- iomanip.h
Show answer
Answer: (d) iomanip.h
Handout reference: Lecture 36, p. 431
Q95. Which character is inserted at the end of string to indicate the end of string?
- new line
- tab
- null
- carriage return
Show answer
Answer: (c) null
Handout reference: Lecture 12, p. 113
Q96. Assignment operator is used for ___________
- calculation
- reading
- assigning value to variables
- None of the given options
Show answer
Answer: (c) assigning value to variables
Handout reference: Lecture 3, p. 16
Q97. Overloaded delete operator function takes parameter of void pointer and returns ________
- void
- void pointer
- pointer to an object
- pointer of type int
Show answer
Answer: (a) void
Handout reference: Lecture 34, p. 413
Q98. What should be the return type of the constructor?
- void pointer
- int
- same as object type
- constructors do not return any thing
Show answer
Answer: (d) constructors do not return any thing
Handout reference: Lecture 27, p. 320
Q99. "setprecision" manipulator will set
- The number of digits after the decimal point
- The number of digits before the decimal point
- The number of digits in a number
- None of the given options
Show answer
Answer: (c) The number of digits in a number
Why: Judgment call: in the default mode setprecision(n) sets the number of significant digits; with fixed it sets the digits after the decimal point.
Handout reference: Lecture 36, p. 436
Q100. Which of the following option will be true, if we overload "-=" operator?
- only - operator needs to be overloaded
- Minus (-) and = operators need to be overloaded
- the -= operator need to be overloaded explicitly
- the - and = operators need to be overloaded implicitly
Show answer
Answer: (c) the -= operator need to be overloaded explicitly
Handout reference: Lecture 31, p. 369
Q101. Operator overloading can be performed through__________________
- Classes
- Functions
- Operators
- Reference
Show answer
Answer: (b) Functions
Handout reference: Lecture 31, p. 370
Q102. When a value is referred by a normal variable then it is known as,
- Direct Reference
- Indirect Reference
- Partial Reference
- Proper Reference
Show answer
Answer: (a) Direct Reference
Handout reference: Lecture 14, p. 142
Q103. _______ is used to trace the logic of the program and correct the logical errors
- Compiler
- Editor
- Linker
- Debugger
Show answer
Answer: (d) Debugger
Handout reference: Lecture 2, p. 12
Q104. Which of the following function do NOT initialize the chunk of memory to all zero?
- calloc() function
- Both malloc() and calloc()
- None of the above
- malloc() function
Show answer
Answer: (d) malloc() function
Handout reference: Lecture 24, p. 280
Q105. The function free() returns back the allocated memory got thorough calloc and malloc to _____
- stack
- heap
- stack and heap
- None of the given options
Show answer
Answer: (b) heap
Handout reference: Lecture 24, p. 282
Q106. If we want to use stream insertion and extraction operators with _______ then we have to overload these operators
- int, float, double
- objects of class
- int, float, object
- int, char, float
Show answer
Answer: (b) objects of class
Handout reference: Lecture 37, p. 449
Q107. If text is a pointer of class String then what is meant by the following statement? text = new String [5]
- Creates an array of 5 string objects statically
- Creates an array of 5 string objects dynamically
- Creates an array of pointers to string
- Creates a string Object
Show answer
Answer: (b) Creates an array of 5 string objects dynamically
Handout reference: Lecture 34, p. 409
Q108. The compiler does not provide a copy constructor if we do not provide it………
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 39, p. 474
Q109. new and delete operators cannot be overloaded as member functions
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 34, p. 412
Q110. To avoid dangling reference, always return the reference of a local variable from a function
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 30, p. 364
Q111. We can delete an array of objects without specifying [] brackets if a class is not doing dynamic memory allocation internally
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 34, p. 410
Q112. The second parameter of operator functions for << and >> are objects of the class for which we are overloading these operators
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 37, p. 451
Q113. We can also do conditional compilation with preprocessor directives
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 23, p. 270
Q114. The precedence of an operator can be changed through operator overloading
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 31, p. 370
Q115. Deleting an array of objects without specifying [] brackets may lead to memory leak
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 34, p. 410
Q116. break statement can be used outside a loop or switch statement
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 22, p. 264
Q117. When we do dynamic memory allocation in the constructor of a class, then it is necessary to provide a destructor
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 39, p. 477
Q118. With New keyword, data types and class members are initialized with meaningful values instead of garbage
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 28, p. 332
Q119. A function can declare itself a friend of a class
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 29, p. 344
Q120. When new operator is overloaded at global level then corresponding built-in new operator will not be visible to whole of the program
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 34, p. 411
Q121. Operating System is
- An application software
- System Software
- Computer Language
- Interpreter
Show answer
Answer: (b) System Software
Handout reference: Lecture 2, p. 8
Q122. ofstream is used for________
- Input file stream
- Output file stream
- Input and output file stream
- All of the given
Show answer
Answer: (b) Output file stream
Handout reference: Lecture 18, p. 198
Q123. Transpose of a matrix means that when we interchange rows and columns_____________
- the first row becomes the Last column
- the first row becomes the first column
- the Last row becomes the first column
- the first column becomes the first row
Show answer
Answer: (b) the first row becomes the first column
Handout reference: Lecture 13, p. 130
Q124. In_________, we try to have a precise problem statement
- Analysis
- Design
- Coding
- None of the given
Show answer
Answer: (a) Analysis
Handout reference: Lecture 13, p. 135
Q125. _______________are conventional names of the command line parameters of the ‘main()’ function
- ‘argb’ and ‘argv’
- ‘argc’ and ‘argv’
- ‘argc’ and ‘argu’
- None of the given
Show answer
Answer: (b) ‘argc’ and ‘argv’
Handout reference: Lecture 16, p. 177
Q126. A function that calls itself is known as
- Iterative function
- Inline function
- Recursive function
- main ()
Show answer
Answer: (c) Recursive function
Handout reference: Lecture 10, p. 96
Q127. Loader loads the executable code from hard disk to main memory
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 2, p. 12
Q128. The number 544.53 must be stored in _____ data type
- int
- short
- float
- char
Show answer
Answer: (c) float
Handout reference: Lecture 3, p. 19
Q129. Which of the following is used with bit manipulation?
- Signed integer
- Un-signed integer
- Signed double
- Un-signed double
Show answer
Answer: (b) Un-signed integer
Handout reference: Lecture 21, p. 244
Q130. Memory allocated at run time is a system resource and it is the responsibility of _____ to de-allocate the
- System
- Programmer
- User of program
- None of given options
Show answer
Answer: (b) Programmer
Handout reference: Lecture 39, p. 469
Q131. Which looping process checks the test condition at the end of the loop?
- for
- while
- do while
- no looping process checks the test condition at the end
Show answer
Answer: (c) do while
Handout reference: Lecture 7, p. 55
Q132. There is a pointer variable named ptr of type int then address of which type of variable the ptr will store in it?
- variable of type char
- variable of type short
- variable of type int
- variable of type double
Show answer
Answer: (c) variable of type int
Handout reference: Lecture 14, p. 145
Q133. The input/output streams; cin and cout are ____
- Operators
- Functions
- Objects
- Structures
Show answer
Answer: (c) Objects
Handout reference: Lecture 35, p. 421
Q134. dec, hex, oct are all __________
- Member functions
- Objects of input/output streams
- Parameterized manipulators
- Non-parameterized manipulators
Show answer
Answer: (d) Non-parameterized manipulators
Handout reference: Lecture 36, p. 439
Q135. A stream is an ordered sequence of bytes
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 35, p. 421
Q136. Which of the following array is the most suitable for storing a matrix structure?
- Single-dimensional array
- Two-dimensional array
- Three-dimensional array
- Four-dimensional array
Show answer
Answer: (b) Two-dimensional array
Handout reference: Lecture 12, p. 120
Q137. Copy constructor becomes necessary while dealing with _______allocation in the class
- Dynamic memory
- Static memory
- Both Dynamic and Static memory
- None of the given options
Show answer
Answer: (a) Dynamic memory
Handout reference: Lecture 39, p. 474
Q138. Default constructor takes _________
- one parameter
- two parameters
- no parameters
- character type parameter
Show answer
Answer: (c) no parameters
Handout reference: Lecture 27, p. 320
Q139. All the preprocessors directives start with ________
- $
- &
- #
- _
Show answer
Answer: (c) #
Handout reference: Lecture 23, p. 270
Q140. The members of a class declared with the keyword struct are _____________by default
- static
- private
- protected
- public
Show answer
Answer: (d) public
Handout reference: Lecture 28, p. 335
Q141. In statement Matrix m2 = m1
- Assignment operator is being used
- Copy constructor is being used
- Statement has syntax error
- None of the given options
Show answer
Answer: (b) Copy constructor is being used
Handout reference: Lecture 39, p. 478
Q142. To get the value stored at a memory address, we use the________________
- referencing operator
- dereferencing operator
- simple operator
- None of the given
Show answer
Answer: (b) dereferencing operator
Handout reference: Lecture 14, p. 146
Q143. In C/C++; by default arguments are passed by _______ to a function
- Reference
- Value
- Type
- Data
Show answer
Answer: (b) Value
Handout reference: Lecture 25, p. 293
Q144. The string in the array is terminated by a _______
- zero
- nil
- null
- one
Show answer
Answer: (c) null
Handout reference: Lecture 12, p. 112
Q145. At the___________, we try to break up the problem into functional units
- analysis phase
- design phase
- Implementation phase
- None of the given
Show answer
Answer: (b) design phase
Handout reference: Lecture 13, p. 135
Q146. _________operator uses the sign ^
- Bit-wise OR
- Exclusive OR
- AND Operator
- NOT operator
Show answer
Answer: (b) Exclusive OR
Handout reference: Lecture 21, p. 247
Q147. Suppose int multi[5][10]; when we are using **multi , it means,
- Single dereferencing
- Single referencing
- Double referencing
- Double dereferencing
Show answer
Answer: (d) Double dereferencing
Handout reference: Lecture 16, p. 172
Q148. What will be the output of the following statement?cout << setfill('0') << setw(7) << 128;
- 0000128
- 0128128
- 1280000
- 0012800
Show answer
Answer: (a) 0000128
Handout reference: Lecture 36, p. 435
Q149. The operator function for << (stream insertion) >> and stream extraction must be
- Member function of class
- Non-member function of class
- Both member and non-member function
- None of the given options
Show answer
Answer: (b) Non-member function of class
Handout reference: Lecture 37, p. 443
Q150. Which of the following operators can not be overloaded?
- new
- delete
- +=
- sizeof
Show answer
Answer: (d) sizeof
Handout reference: Lecture 31, p. 369
Q151. The second parameter of operator function for >> operator must always be passed
- By value
- By reference
- None of the given option
- Function takes no argument
Show answer
Answer: (b) By reference
Handout reference: Lecture 37, p. 451
Q152. In overloading the assignment (=) operator, which object(s) will call the operator function?
- Right object of the assignment operator
- No object will call the operator function
- Left object of the assignment operator
- Both objects will call the operator function
Show answer
Answer: (c) Left object of the assignment operator
Handout reference: Lecture 31, p. 370
Q153. The only operator that the compiler overloads for user define data type by default is
- Plus (+) operator
- Minus (-) operator
- Equal (==) operator
- Assignment (=) operator
Show answer
Answer: (d) Assignment (=) operator
Handout reference: Lecture 31, p. 370
Q154. What does the this pointer always point to?
- A value of data member
- Current object of the class
- Current function of the class
- Current pointer of the class
Show answer
Answer: (b) Current object of the class
Handout reference: Lecture 32, p. 388
Q155. What is the purpose of endl stream manipulator?
- Insert a new line
- Flush the stream
- Terminate a string with null
- Insert a new line and flush the stream
Show answer
Answer: (d) Insert a new line and flush the stream
Handout reference: Lecture 36, p. 434
Q156. When we used eof (end of file) with the file reading than which of the following is a true statement?
- This is a way to check type of the stream
- This is a way to check source of the stream
- This is a way to check state of the stream
- This is a way to check destination of the stream
Show answer
Answer: (c) This is a way to check state of the stream
Handout reference: Lecture 35, p. 425
Q157. Ostream class is ____ and not under our control
- User-defined
- Built-in
- Both
- None
Show answer
Answer: (b) Built-in
Handout reference: Lecture 38, p. 453
Q158. _____ must be included to use stream manipulator in your code
- Conio.h
- Stdlib.h
- Iomanip
- Iostream
Show answer
Answer: (c) Iomanip
Handout reference: Lecture 36, p. 431
Q159. Which of the following is a destination of cout stream?
- Printer
- Constant
- Variable
- Data type
Show answer
Answer: (a) Printer
Why: Judgment call: cout is connected to the standard output (normally the screen); of the options given, Printer is the closest.
Handout reference: Lecture 35, p. 422
Q160. Static data members of a class can be ____
- Public
- Private
- Both
- None
Show answer
Answer: (c) Both
Handout reference: Lecture 38, p. 466
Q161. Once the _____ are created, they exist for the life time of the program
- Local variables
- Static variables
- Automatic variables
- non static variables
Show answer
Answer: (b) Static variables
Handout reference: Lecture 38, p. 459
Q162. If the memory in the free store is not sufficient ____________________
- Malloc function returns 0
- Malloc function returns 1
- Malloc function returns free space
- Malloc functions returns NULL pointer
Show answer
Answer: (d) Malloc functions returns NULL pointer
Handout reference: Lecture 28, p. 342
Q163. Reference is not really an address it is ______________
- A value
- A number
- A synonym
- An antonym
Show answer
Answer: (c) A synonym
Handout reference: Lecture 30, p. 363
Q164. Which situation would require the use of non-member overloaded operator?
- The overloaded operator is an Assignment operator
- The left most operand is an object of a class
- The left operand is built-in data type
- The operator returns a reference
Show answer
Answer: (c) The left operand is built-in data type
Handout reference: Lecture 31, p. 373
Q165. When break statement is encountered in switch statement,it
- Exits from switch statement
- enter from switches statement
- both a&b
- none of the given option
Show answer
Answer: (a) Exits from switch statement
Handout reference: Lecture 8, p. 68
Q166. The remainder(%) operator is a _ operator
- logical
- Arithmetic
- Relational
- Conditional
Show answer
Answer: (b) Arithmetic
Handout reference: Lecture 22, p. 257
Q167. Which loop is particularly suitable when the number of iterations is known in advance?
- for
- while
- do-while
- all looping processes require that the iterations be known
Show answer
Answer: (a) for
Handout reference: Lecture 7, p. 58
Q168. In order to get the right most digit of a number, we divide this number by 10 and take _
- Its remainder
- Its quotient
- Its divisor
- The number
Show answer
Answer: (a) Its remainder
Handout reference: Lecture 4, p. 28
Q169. How many bytes of memory are occupied by array str? char str[] = "programming";
- 10
- 11
- 12
- 13
Show answer
Answer: (c) 12
Handout reference: Lecture 15, p. 169
Q170. Switch statement deals with _ _type of data
- Integer
- Float
- Character
- Both Integer and Character
Show answer
Answer: (d) Both Integer and Character
Handout reference: Lecture 8, p. 67
Q171. A constructor has the same name as that of_
- Variable
- Class
- Structure
- Function
Show answer
Answer: (b) Class
Handout reference: Lecture 26, p. 316
Q172. Whenever New operator is called to create an object, the _
- Constructor
- Destructor
- Pointer
- Array
Show answer
Answer: (a) Constructor
Handout reference: Lecture 28, p. 336
Q173. Sequence of event(s) when deallocating memory using delete operator
- Only block of memory is deallocated for object
- Only destructor is called for object
- Memory is deallocated first before calling destructor
- Destructor is called first before deallocating memory
Show answer
Answer: (d) Destructor is called first before deallocating memory
Handout reference: Lecture 34, p. 410
Q174. if there is a symbol(& sign) used with the variable name following by data type then it refers to
- Logic expression
- Value of variable
- Reference variable
- Address of variable
Show answer
Answer: (c) Reference variable
Handout reference: Lecture 30, p. 365
Q175. A macro when takes arguments is called
- Function
- Procedure
- Parameterized macro
- Simple macro
Show answer
Answer: (c) Parameterized macro
Handout reference: Lecture 23, p. 273
Q176. We can use cin.peek() function to -
- See the next character that we are going to get
- Get to the end of the object buffer
- Get to the end of input buffer
- See the first character of input buffer
Show answer
Answer: (a) See the next character that we are going to get
Handout reference: Lecture 35, p. 428
Q177. data members of a contained object can be accessed from inside of the containing class
- Private
- Public
- Protected
- All
Show answer
Answer: (b) Public
Handout reference: Lecture 40, p. 487
Q178. The C language was developed in late 60’s and 70’s in
- Richards laboratories
- Microsoft laboratories
- Bell laboratories
- IBM laboratries
Show answer
Answer: (c) Bell laboratories
Handout reference: Lecture 2, p. 10
Q179. What happens to an argument that is passed by reference to a function?
- The function cannot access the argument’s value
- A separate local variable is created to hold a copy of the argument
- A temporary independent value is created in the caller
- The function accesses the original argument through a reference
Show answer
Answer: (d) The function accesses the original argument through a reference
Handout reference: Lecture 13, p. 134
Q180. In year C was approved as a standard language worldwide
- 1988
- 1967
- 1989
- 1986
Show answer
Answer: (c) 1989
Why: C was standardized by ANSI in 1989 (ISO adopted it in 1990).
Handout reference: Lecture 2, p. 11
Q181. Which statement immediately exits the innermost enclosing loop or switch?
- Continue
- Goto
- Pause
- Break
Show answer
Answer: (d) Break
Handout reference: Lecture 8, p. 68
Q182. If we write a statement like s2 = s1; ___ will be the calling object and ____ will be passed to the = operator as an argument
- s1, s1
- s1, s2
- s2, s1
- s2, s2
Show answer
Answer: (c) s2, s1
Handout reference: Lecture 33, p. 395
Q183. In the S2=S1, ___ is the object that is calling or driving the = operator. ___ object is being passed as an argument to the = operator
- S1, S2
- S2,S1
- =, +
- None of the Above
Show answer
Answer: (b) S2,S1
Handout reference: Lecture 31, p. 371
Q184. Stream insertion ( << ) and extraction operators ( >> ) are always implemented as -- _______functions
- Member
- Non Member
- Objects
- Classes
Show answer
Answer: (b) Non Member
Handout reference: Lecture 37, p. 451
Q185. We can change the arity (number of operands) through operator overloading
- False
- True
Show answer
Answer: (a) False
Handout reference: Lecture 31, p. 379
Q186. Self-assignment is dangerous especially at a time when we have memory manipulation in a class
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 33, p. 398
Q187. Which declaration represents an overloaded pre-increment operator implemented as a class member?
- ClassName operator+();
- ClassName operator+(int);
- ClassName operator++();
- ClassName operator++(int);
Show answer
Answer: (c) ClassName operator++();
Handout reference: Lecture 32, p. 387
Q188. Assume sizeof(int) is 4 bytes. By how many bytes does an int pointer advance after executing intPtr += 3;?
- 3 bytes
- 6 bytes
- 12 bytes
- 24 bytes
Show answer
Answer: (c) 12 bytes
Handout reference: Lecture 15, p. 159
Q189. Which expression dynamically allocates an array of ten int elements in C++?
- new int(10);
- new int[10];
- int new(10);
- int new[10];
Show answer
Answer: (b) new int[10];
Handout reference: Lecture 28, p. 333
Q190. Which C memory-management function can resize an already allocated block of memory?
- malloc()
- calloc()
- realloc()
- free()
Show answer
Answer: (c) realloc()
Handout reference: Lecture 24, p. 283
Q191. For which types are the standard stream insertion (<<) and extraction (>>) operators already overloaded?
- User-defined classes only
- Built-in data types
- All user-defined classes and built-in data types automatically
- None of the given options
Show answer
Answer: (b) Built-in data types
Handout reference: Lecture 37, p. 443
Q192. What is the normal input source for the cin stream object?
- File
- Disk
- Keyboard
- RAM
Show answer
Answer: (c) Keyboard
Handout reference: Lecture 35, p. 422
Q193. Which statement initializes an int variable x to 10 at the time of its declaration?
- int x; x = 10;
- int x = 10;
- int x, x = 10;
- x = 10;
Show answer
Answer: (b) int x = 10;
Handout reference: Lecture 5, p. 35
Q194. Which is the correct declaration of a two-dimensional 2-by-2 array of float values?
- float arr{2}{2};
- float arr[2][2];
- float arr[2,2];
- float[2][2] arr;
Show answer
Answer: (b) float arr[2][2];
Handout reference: Lecture 12, p. 120
Q195. Does an ordinary non-static local variable continue to exist after its function returns?
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 38, p. 458
Q196. The C++ delete operator returns memory previously allocated with new to free store.
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 28, p. 330
Q197. A function template may contain only generic data types, not ordinary data types.
- True
- False
Show answer
Answer: (b) False
Handout reference: Lecture 41, p. 499
Q198. Assume arr is an array and ptr is a compatible pointer. Which statement makes ptr point to the first element of arr?
- *ptr = arr;
- ptr = arr;
- *ptr = arr[5];
- ptr = arr[5];
Show answer
Answer: (b) ptr = arr;
Handout reference: Lecture 15, p. 158
Q199. Which C header files define the NULL macro, as described in the handouts?
- strings.h and iostream.h
- ctype.h and conio.c
- conio.c and conio.h
- stdlib.h and stddef.h
Show answer
Answer: (d) stdlib.h and stddef.h
Handout reference: Lecture 24, p. 279
Q200. For a class that manages dynamically allocated memory, an incorrectly implemented self-assignment can produce which kind of error?
- Syntax error
- Logical error
- Link error
- None of the given options
Show answer
Answer: (b) Logical error
Handout reference: Lecture 39, p. 476
Q201. Including objects of existing classes as data members of a new class is a way to reuse code.
- True
- False
Show answer
Answer: (a) True
Handout reference: Lecture 40, p. 488
Q202. Which is a valid generic declaration for a binary member operator+ that returns an object of the class?
- ClassName operator+(ClassName rhs);
- operator ClassName+();
- operator ClassName+(rhs);
- ClassName operator+();
Show answer
Answer: (a) ClassName operator+(ClassName rhs);
Handout reference: Lecture 31, p. 371
Q203. What is the conventional return type of an overloaded stream extraction (>>) operator?
- The class being read
- ostream&
- istream&
- void
Show answer
Answer: (c) istream&
Handout reference: Lecture 37, p. 445
Q204. What is the range of values returned by rand() on the implementation used in the course (RAND_MAX = 32767)?
- 0–32768
- 1–32768
- 0–32767
- 1–32767
Show answer
Answer: (c) 0–32767
Why: RAND_MAX is 32767 on the compilers used in the course; it can differ on other compilers.
Q205. When using a library function, predefined object, or macro, which file is normally included?
- Source file
- Object file
- Header file
- Executable file
Show answer
Answer: (c) Header file
Q206. In the statement int &x = y;, what happens when x is initialized?
- A new integer variable x is created with the value of y
- x is a pointer holding the address of y
- x becomes another name for y without creating a separate integer object
- A new variable y is created with the value of x
Show answer
Answer: (c) x becomes another name for y without creating a separate integer object
Q207. Which operator is used in a C-style type cast?
- Binary
- Cast
- Cost
- Const
Show answer
Answer: (b) Cast
Q208. When a function template is instantiated, the compiler identifies the type parameters and generates what?
- A function specialization for the required types
- An old function copy
- A separate unrelated template declaration
- A runtime-only function
Show answer
Answer: (a) A function specialization for the required types
Q209. Templates provide a way of abstracting which kind of information?
- Type
- Data value
- Method name only
- Access level
Show answer
Answer: (a) Type
Q210. What is a name defined by the preprocessor that is substituted with its replacement text?
- Include
- Directive
- Macro
- Define statement
Show answer
Answer: (c) Macro
Q211. Where may a header file be included in a C++ source file?
- Anywhere syntactically valid before its contents are needed
- Only at the beginning of the file
- Only at the end of the file
- Only inside main()
Show answer
Answer: (a) Anywhere syntactically valid before its contents are needed
Q212. Which is NOT, by itself, a memory-management error?
- Memory leak
- Lost or unreferenced allocated memory
- Using a void pointer
- Dangling pointer
Show answer
Answer: (c) Using a void pointer
Q213. In obj3 = obj1 - obj2;, if obj1 invokes the overloaded operator and obj2 is its parameter, what kind of operator function is used?
- Friend function
- Virtual function
- Member function
- Non-member function
Show answer
Answer: (c) Member function
Q214. The base address of an array is the address of which element?
- First
- Second
- Third
- Fourth
Show answer
Answer: (a) First
Q215. What type of expression normally controls a loop?
- Arithmetic expression only
- Constant expression only
- Boolean expression
- Primary expression only
Show answer
Answer: (c) Boolean expression
Q216. What does a break statement do when executed inside a loop?
- Exits the current loop
- Exits the entire program
- Immediately starts the next loop iteration
- Causes a compilation error
Show answer
Answer: (a) Exits the current loop
Q217. Which of the following is not an integer literal?
- 0
- -32
- 65531
- 4.0
Show answer
Answer: (d) 4.0
Q218. The ws manipulator is used with which kind of stream?
- Output
- Input
- Both input and output
- Buffered only
Show answer
Answer: (b) Input
Q219. Using objects as data members of other classes promotes which software quality?
- Accessibility
- Reliability
- Reusability
- Usability
Show answer
Answer: (c) Reusability
Q220. When an array of class objects is destroyed, how are destructors invoked?
- Only once for the whole array
- Once for each constructed array element
- Never
- Only for the first element
Show answer
Answer: (b) Once for each constructed array element
Q221. When #define PI 3.1415926 is used, what happens to PI during preprocessing?
- It cannot be replaced with another value automatically during execution
- A function modifies its value
- Its occurrences are replaced by the fixed macro text
- A runtime operation updates the macro
Show answer
Answer: (c) Its occurrences are replaced by the fixed macro text
Q222. Which is a valid C++ class declaration?
- class B {}
- public class A {}
- object A { int x; };
- class A { int x; };
Show answer
Answer: (d) class A { int x; };
Q223. When accessing an element in a C++ multidimensional array, how are subscripts written?
- Separated only by commas
- All inside one set of brackets separated by commas
- Separated by commas and braces
- Each subscript enclosed in its own brackets
Show answer
Answer: (d) Each subscript enclosed in its own brackets
Q224. What is the default type of an unsuffixed decimal integer literal such as 10 when its value fits?
- short
- float
- int
- double
Show answer
Answer: (c) int
Q225. Which header traditionally declares malloc() and calloc() in C/C++?
- memory.h
- iostream.h
- stdlib.h
- conio.h
Show answer
Answer: (c) stdlib.h
Q226. An allocation expression new T normally returns a pointer to which part of the allocated object?
- Second address
- Start of the allocated object
- Last address
- Previous memory block
Show answer
Answer: (b) Start of the allocated object
Q227. For obj3 = obj1 + obj2;, when + is overloaded as a member of obj1’s class, which operand calls the operator?
- obj2 calls + and obj1 is passed
- obj1 calls + and obj2 is passed
- Both are passed as explicit arguments
- Either may invoke it interchangeably
Show answer
Answer: (b) obj1 calls + and obj2 is passed
Q228. A function template must have at least how many template parameters in this course context?
- Zero
- One
- Two
- Three
Show answer
Answer: (b) One
Q229. What does the compiler-generated copy-assignment operator normally perform?
- It prohibits assignment
- It assigns no data members
- It assigns only selected members
- It performs memberwise assignment
Show answer
Answer: (d) It performs memberwise assignment
Q230. A pointer declared float* ptr; may directly hold the address of which type of object?
- int
- float
- char
- double
Show answer
Answer: (b) float
Q231. Which of the following is NOT a preprocessor directive?
- #error
- #define
- #line
- #ndefine
Show answer
Answer: (d) #ndefine
Q232. When x = 7; then the expression x%= 2; will calculate the value of x as,
- 1
- 3
- 7
- 2
Show answer
Answer: (a) 1
Q233. When we are using const keyword with a variable x then initializing it at the time of declaration is,
- Must
- Optional
- Not necessary
- A syntax error
Show answer
Answer: (a) Must
Q234. What is the output of the following C++ code?int arr[6] = {2, 3, 7, 4, 5, 6};
int *ptr1 = &arr[1];
int *ptr2 = &arr[4];
cout << (ptr2 - ptr1);
- 3
- 9
- 12
- 2
Show answer
Answer: (a) 3
Q235. C is a/an ______ language
- low level
- object based
- object oriented
- function oriented
Show answer
Answer: (d) function oriented
Why: Course wording (C is a procedural, function-oriented language).
Q236. What is wrong with the following for-loop header?for (int k = 2, k <= 12, k++)
- the increment should always be ++k
- the variable must always be the letter i when using a for loop
- there should be a semicolon at the end of the statement
- Commas must be replaced with semicolons
Show answer
Answer: (d) Commas must be replaced with semicolons
Q237. The reserved words public and private comes from
- structures
- strings
- accessibility modifiers
- types of functions
Show answer
Answer: (c) accessibility modifiers
Q238. Which aspect of a class should be hidden from clients to preserve encapsulation?
- Functions name within class
- Class implementation of Functionality and Identifiers
- Methods Functionality within class
- None of the given options
Show answer
Answer: (b) Class implementation of Functionality and Identifiers
Q239. seekg() and write() are functionally _________________
- Different
- Identical
- Two names of same function
- None of the above
Show answer
Answer: (a) Different
Q240. Suppose a program contains an array declared as int arr[100]; what will be the size of array?
- 0
- 99
- 100
- 101
Show answer
Answer: (c) 100
Q241. Which of the following statements is true about new when dynamically allocating memory for an object?
- The new operator determines the size of an object
- Allocates memory to object and returns pointer of valid type
- Creates an object and calls the constructor to initialize the object
- All of the given options
Show answer
Answer: (d) All of the given options
Q242. For non-member operator function, object on left side of the operator may be
- Object of operator class
- Object of different class
- Built-in data type
- All of the given options
Show answer
Answer: (d) All of the given options
Q243. Class is a user defined___________
- data type
- memory reference
- value
- none of the given options
Show answer
Answer: (a) data type
Q244. In obj3 = obj1 + obj2;, if operator+ is overloaded as a non-member function, how are the operands supplied?
- obj1 will be passed as an argument to + operator whereas obj2 will drive the + operator
- obj1 will drive the + operator whereas obj2 will be passed as an argument to + operator
- Both objects (obj1, obj2) will be passed as arguments to the + operator
- Any of the objects (obj1, obj2) can drive the + operator
Show answer
Answer: (c) Both objects (obj1, obj2) will be passed as arguments to the + operator
Q245. Which of the following function cannot be overloaded?
- Member functions
- Utility functions
- Constructor
- Destructor
Show answer
Answer: (d) Destructor
Q246. The code is written to __________ the program
- implement
- design
- analysis
- none of the given options
Show answer
Answer: (a) implement
Q247. In C/C++ if we define an array of size eight ( i.e. int Arr [8]; then the last element of this array will be stored at,
- Arr[0]
- Arr[8]
- Arr[7]
- Arr[-1]
Show answer
Answer: (c) Arr[7]
Q248. Array is a data structure which store
- Memory addresses
- Variables
- Data Type
- Data
Show answer
Answer: (d) Data
Q249. The default value of a parameter can be provided inside the ________________
- function prototype
- function definition
- both function prototype or function definition
- none of the given options
Show answer
Answer: (c) both function prototype or function definition
Q250. When an operator function is defined as member function for a binary Plus (+) operator then the number of argument it take is/are
- Zero
- One
- Two
- N arguments
Show answer
Answer: (b) One
Q251. "new" and "delete" keywords are _____________ in C++ language
- Built-in- Function
- Operators
- Memory Allocation Function
- None of the given options
Show answer
Answer: (b) Operators
Q252. Which two values are printed, in order, by the cout statements in this program?int func(int);
int num = 10;
int main() {
int num;
num = 5;
cout << num;
cout << func(num);
}
int func(int x) {
return num;
}
- 5, 5
- 10, 5
- 5, 10
- 10, 10
Show answer
Answer: (c) 5, 10
Q253. Every class contains _______________
- Constructor
- Destructor
- Both a constructor and a destructor
- None of the given options
Show answer
Answer: (c) Both a constructor and a destructor
Q254. What does 5 ^ 6 , evaluate to in decimal where ‘^’ is Exclusive OR operator?
- 1
- 2
- 3
- 4
Show answer
Answer: (c) 3
Q255. In C++, what are the default access levels of struct members and class members, respectively?
- private, public
- public, private
- private, protected
- public, protected
Show answer
Answer: (b) public, private
Q256. Which of the following is true for the C++ statement given below?int &ref = val;
- It creates a synonym for variable ‘val’
- It creates an alias for variable ‘val’
- It’s a new name for variable ‘val’
- All of the given options
Show answer
Answer: (d) All of the given options
Q257. Unary operator implemented as member function takes ____ arguments whereas non- member function takes _____ arguments
- One, zero
- Zero, one
- One, two
- Two, one
Show answer
Answer: (b) Zero, one
Q258. Given the following operator+ declaration in class M, how is the operator implemented for p + q?class M {
public:
M& operator+(const M&);
};
- Member function
- Non-member function
- Friend function
- None of the given options
Show answer
Answer: (a) Member function
Q259. What does (*this) represents?
- The current function of the class
- The current pointer of the class
- The current object of the class
- A value of the data member
Show answer
Answer: (c) The current object of the class
Q260. What purpose do classes serve?
- Data encapsulation
- Providing a convenient way of modeling real-world objects
- Simplifying code reuse
- All of the given options
Show answer
Answer: (d) All of the given options
Q261. new operator is used to allocate memory from the free store during
- Compile Time
- Run Time
- Link Time
- None of the given options
Show answer
Answer: (b) Run Time
Q262. && is -------------------- operator
- An arithmetic
- Logical
- Relational
- Unary
Show answer
Answer: (b) Logical
Q263. Which of the following function(s) is/are included in ctype.h header file?
- isdigit(int c)
- isxdigit(int c )
- tolower(int c)
- All of the above
Show answer
Answer: (d) All of the above
Q264. The object _______________may be used both for file input and file output
- fstream
- ifstream
- ofstream
- none of the given options
Show answer
Answer: (a) fstream
Q265. If there is more than one statement in the block of a for loop, which of the following must be placed at the beginning and the ending of the loop block?
- parentheses ( )
- braces { }
- brackets [ ]
- arrows < >
Show answer
Answer: (b) braces { }
Q266. A pointer variable can be,
- Decremented
- Incremented
- Multiplied
- Both incremented and Decremented
Show answer
Answer: (d) Both incremented and Decremented
Q267. What are the values of a and b after executing these statements?int a = 3;
int b = a++;
- 3,4
- 4,4
- 3,3
- 4,3
Show answer
Answer: (d) 4,3
Q268. Consider the following code segment. What will be the output of this code?int addValue(int *a) {
int b = (*a) + 2;
return b;
}
int main() {
int x = 6;
cout << x << ",";
cout << addValue(&x) << ",";
cout << x;
}
- 6,8,6
- 6,6,8
- 6,8,8
- 6,6,6
Show answer
Answer: (a) 6,8,6
Q269. When ever dynamic memory allocation is made in C/C++, it is freed_____________
- Explicitly
- Implicitly
- Both explicitly and implicitly
- None of the given options
Show answer
Answer: (a) Explicitly
Q270. What happens when the following array of String objects is initialized (assuming both constructors exist)?String str[5] = {String("Programming"), String("CS201")};
- Default constructor will call for all objects of array
- Parameterized constructor will call for all objects of array
- The parameterized constructor is called for the first two objects and the default constructor for the remaining three.
- Default constructor will call for first 3 objects and Parameterized constructor for remaining
Show answer
Answer: (c) The parameterized constructor is called for the first two objects and the default constructor for the remaining three.
Q271. Overloaded member operator function is always called by _______
- Class
- Object
- Compiler
- Primitive data type
Show answer
Answer: (b) Object
Q272. The static data members of a class can be accessed by ________
- only class
- only object
- both class and objects
- none of given options
Show answer
Answer: (c) both class and objects
Q273. Given the following operator! declaration in class M, how is the operator implemented for !s?class M {
friend int operator!(const M&);
};
- Member function
- Non-member function
- Binary operator function
- None of the given options
Show answer
Answer: (b) Non-member function
Q274. The variables having a name, type and size are just like empty boxes
- True
- False
Show answer
Answer: (a) True
Q275. setw is a parameterized manipulator
- True
- False
Show answer
Answer: (a) True
Q276. The operator functions of << and >> operators are always the member function of a class
- True
- False
Show answer
Answer: (b) False
Q277. Reusing the variables in program helps to save the memory
- True
- False
Show answer
Answer: (a) True
Q278. We can also define a user-defines manipulators
- True
- False
Show answer
Answer: (a) True
Q279. An array stores the numbers into consecutive memory locations
- True
- False
Show answer
Answer: (a) True
Q280. The template functions do not promote the code reuse
- True
- False
Show answer
Answer: (b) False
Q281. The default copy constructor provides member wise assignment
- True
- False
Show answer
Answer: (a) True
Q282. We can also create an array of user defined data type
- True
- False
Show answer
Answer: (a) True
Q283. Assignment operator is used to initialize a newly declared object from existing object
- True
- False
Show answer
Answer: (b) False
Q284. eof( ), bad( ), good( ), clear( ) all are manipulators
- True
- False
Show answer
Answer: (b) False
Q285. The return type of operator function must always be void
- True
- False
Show answer
Answer: (b) False
Q286. Heap is constantly changing in size
- True
- False
Show answer
Answer: (a) True
Q287. We can use New keyword inside of Class Constructor
- True
- False
Show answer
Answer: (a) True
Q288. Array is passed by value to a function by default
- True
- False
Show answer
Answer: (b) False
Q289. When an operator function is define as member function then operand on the left side of operator must be an object
- True
- False
Show answer
Answer: (a) True
Q290. We cannot define a variable of user-defined data type in the class
- True
- False
Show answer
Answer: (b) False
Q291. C++ is a case-sensitive language
- True
- False
Show answer
Answer: (a) True
Q292. Template class cannot have static variables
- True
- False
Show answer
Answer: (b) False
Q293. It is possible to define a class within another class
- True
- False
Show answer
Answer: (a) True
Q294. Set-precision is a parameter less manipulator
- True
- False
Show answer
Answer: (b) False
Q295. We can do arithmetic with references like pointers
- True
- False
Show answer
Answer: (b) False
Q296. Overloaded delete operator function takes the same parameter as an argument returned by new operator function
- True
- False
Show answer
Answer: (a) True
Q297. We cannot make a member function of a class as template function
- True
- False
Show answer
Answer: (b) False
Q298. Templates are not type safe
- true
- false
Show answer
Answer: (b) false
Q299. Dealing with structures and functions passing by reference is the most economical method
- True
- False
Show answer
Answer: (a) True
Q300. Constructors cannot be overloaded like ordinary functions
- True
- False
Show answer
Answer: (b) False
Q301. Computer can understand only machine language code
- True
- False
Show answer
Answer: (a) True
Q302. We can change a Unary operator to Binary operator through operator overloading
- False
- True
Show answer
Answer: (a) False
Q303. Compiler is a
- System software
- Application Software
- Driver
- Editor
Show answer
Answer: (a) System software
Q304. If most significant bit of un-signed number is 1 then it represents a positive number
- True
- False
Show answer
Answer: (a) True
Q305. A Matrix can be composed of ints, floats or doubles as their elements. Best way is to handle this , _______________
- Write a separate class to handle each
- Use templates
- Use strings to store all types
- None of the given options
Show answer
Answer: (b) Use templates
Q306. Function prototype is written,
- Within main function
- After the return statement in main
- Before the return statement in main
- Before call of that function
Show answer
Answer: (d) Before call of that function
Q307. If int sum = 54, what is the value of sum after executing sum = sum - 3;?
- 52
- 50
- 51
- 57
Show answer
Answer: (c) 51
Q308. In while loop the loop counter must be initialized,
- With in the loop
- Before entering the loop
- At the end of the loop
- None of the given options
Show answer
Answer: (b) Before entering the loop
Q309. Computer can understand only __________language code
- High level
- Low level
- Machine
- Fourth generation
Show answer
Answer: (c) Machine
Q310. < , <= , > , >= are called __________ operators
- Arithmetic
- Logical
- Relational
- Conational
Show answer
Answer: (c) Relational
Q311. If int a = 50; then the value of a/= 3; will be,
- 15
- 18
- 16
- 17
Show answer
Answer: (c) 16
Q312. From the following; which one is used as an assignment operator?
- Equal sign ‘=’
- Double equal sign ‘==’
- Both equal and double equal sign
- None of the given options
Show answer
Answer: (a) Equal sign ‘=’
Q313. Which statement about C++ static member functions is accurate?
- must be declared inside the class definition, but defined outside it
- must be declared private
- have multiple copies for the entire class
- Can directly access static data members; an explicit object is needed to access non-static data
Show answer
Answer: (d) Can directly access static data members; an explicit object is needed to access non-static data
Q314. If Num is an integer variable then Num++ means,
- Add 1 two times with Num
- Add 1 with Num
- Add 2 with Num
- Subtract 2 from Num
Show answer
Answer: (b) Add 1 with Num
Q315. If the return type of a function is void then it means that it will,
- Return any type of data
- Return some specific type of data
- Return no data
- Return just character data
Show answer
Answer: (c) Return no data
Q316. Assuming int occupies 4 bytes and double occupies 8 bytes, what is sizeof(VAZ) for the following union?union intorDouble {
int ival;
double charvar;
};
int main() {
intorDouble VAZ;
int size = sizeof(VAZ);
}
- 2
- 4
- 8
- 12
Show answer
Answer: (c) 8
Q317. The member functions of a class occupy _____ region in memory for ____ object(s) of class
- separate, each
- common, all
- different, each
- different, all
Show answer
Answer: (b) common, all
Q318. Which of the following is true while overloading operators?
- Precedence of an operator can be changed
- The arity (number of operands) can be changed
- No new operators can be created
- Associativity of an operator can be changed
Show answer
Answer: (c) No new operators can be created
Q319. What will be the output of the following statement?cout << setbase(16) << 52;
- 74
- 52
- 34
- 64
Show answer
Answer: (c) 34
Q320. Within the statement obj1=obj2; obj1 will call the assignment operator function and obj2 will be passed as an argument to function
- True
- False
Show answer
Answer: (a) True
Q321. Which is NOT a protection level provided by classes in C++?
- protected
- hidden
- private
- public
Show answer
Answer: (b) hidden
Q322. We cannot use ______________ pointer for storing and reading data from it
- NULL
- integer
- double
- zero
Show answer
Answer: (a) NULL
Q323. We cannot increment ________________
- pointers
- arrays
- references
- variables
Show answer
Answer: (b) arrays
Q324. From the following; which on is the correct syntax of an array declaration: array size is 5 and it is of float data type?
- float [5] name;
- name[5] float;
- float name[5];
- None of the given options
Show answer
Answer: (c) float name[5];
Q325. If an array has 50 elements, what is allowable range of subscripts?
- 0 – 49
- 1 – 49
- 0 – 50
- 1 – 50
Show answer
Answer: (a) 0 – 49
Q326. C++ is a_________________ language
- High level
- Low level
- Machine
- Fourth Generation
Show answer
Answer: (a) High level
Q327. In the course examples, what type of displacement is commonly supplied to seekg() and seekp()?
- int
- short
- long
- double
Show answer
Answer: (c) long
Q328. Which of the following is used for allocating space for static variables?
- Heap
- Static storage area
- Free store
- Stack
Show answer
Answer: (b) Static storage area
Q329. Truth tables are used for analyzing ___________
- logical expressions
- arithmetic expressions
- both logical and arithmetic expressions
- none of the given options
Show answer
Answer: (a) logical expressions
Q330. When operator function is implemented as member function then return type of function ____
- Can be any data type
- Must be built – in data type
- Must be user defined data type
- Must be an object of same class
Show answer
Answer: (a) Can be any data type
Q331. We cannot define friends for the _____ that are already written and not in our control
- Classes
- Functions
- Destructor
- Constructors
Show answer
Answer: (a) Classes
Q332. What will be the output of the following code segment?float pi = 32.3996;
cout << fixed;
cout << setprecision(2) << pi;
- 32.00
- 32.39
- 32.40
- 32.310
Show answer
Answer: (c) 32.40
Q333. Consider the following code segment. Which of the following will be called while executing the second line?String s1, s2;
s1 = s2;
- Default operator
- Copy constructor
- Assignment operator
- Parameterized constructor
Show answer
Answer: (c) Assignment operator
Q334. Consider the following code. The printed value will be converted into:int n = 10;
cout << oct << n;
- base 2
- base 8
- base 10
- decimal number system
Show answer
Answer: (b) base 8
Q335. Which of the following is normally a destination for cin stream?
- Mouse
- Printer
- Variable
- Keyboard
Show answer
Answer: (c) Variable
Q336. This reference to a variable can be obtained by preceding the identifier of a variable with ________________
- ^ sign
- Operator
- Dot operator
- Ampersand sign &
Show answer
Answer: (d) Ampersand sign &
Q337. Once an object is declared as a friend, _________________________
- It has access to public members only
- It has to protected data members only
- It has no access to data members of the class
- It has access to all non-public members as if they were public
Show answer
Answer: (d) It has access to all non-public members as if they were public
Q338. Structure is a collection of _ under a single name
- Only function
- Only variables
- Both data members and member functions
- None
Show answer
Answer: (c) Both data members and member functions
Why: In C++ a struct can hold member functions as well as data (in C it holds only data).
Q339. What does the C++ statement cout << expression normally do?
- Read the data from keyboard
- Read the data from file
- Write into a file
- Display information on the screen
Show answer
Answer: (d) Display information on the screen
Q340. What quality describes an interface that is easy to understand and use?
- Scalability
- Reliability
- sustainability
- usability
Show answer
Answer: (d) usability
Q341. Which of the following if missing would result in infinite recursion in case of recursive function?
- Recursive call
- Base case
- Function parameters
- Local variables
Show answer
Answer: (b) Base case
Q342. Which of the given operator is not a valid compound assignment operator?
- >>=
- =>>
- *=
- &=
Show answer
Answer: (b) =>>
Q343. What is the term for reusing an existing segment of code with little or no modification?
- Code efficiency
- Code reusability
- Code notification
- Code compatibility
Show answer
Answer: (b) Code reusability
Q344. By default, how is an individual scalar array element passed to a C++ function?
- By reference
- By data type
- By value
- By data
Show answer
Answer: (c) By value
Q345. Which statement correctly declares an array of ten int elements?
- int[10] name;
- name[10] int;
- int name[10];
- int name[];
Show answer
Answer: (c) int name[10];
Q346. We cannot define a function as a friend of a Template class
- True
- False
Show answer
Answer: (b) False
Q347. Reserve words cannot be used as a variable name
- True
- False
Show answer
Answer: (a) True
Q348. We can also define a variable of user define data type (object) as static
- True
- False
Show answer
Answer: (a) True
Q349. Most efficient method of dealing with structure variables is to define the structure globally
- True
- False
Show answer
Answer: (b) False
Q350. Operating system falls under the category of ______types of software
- System Software
- Application Software
- Device drivers
- None of the above
Show answer
Answer: (a) System Software
Q351. The preprocessor runs before which phase of C/C++ translation?
- Compiler
- Execution
- Linking
- None of the given options
Show answer
Answer: (a) Compiler
Q352. cerr and clog are the objects of stream class
- True
- False
Show answer
Answer: (a) True
Q353. A template function can not have static variables
- True
- False
Show answer
Answer: (b) False
Q354. A C++ friend function must always be defined outside its class definition.
- True
- False
Show answer
Answer: (b) False
Q355. Assuming ptr points to the first element of an array, which expression obtains the fourth element?
- ptr[3]
- (ptr + 3)
- *(ptr + 3)
- Both A and C
Show answer
Answer: (d) Both A and C
Part 2: Subjective Questions
Short Questions
Short answers of 2-5 marks.
Q1. Why is the loop header for (int i = 0; j < numRows; i--) incorrect, and how can it be repaired?
The loop declares and initializes i but tests j, which is not necessarily declared or related to the loop. It also decrements i when a traversal from 0 up to numRows normally needs incrementing. The corrected header is: for (int i = 0; i < numRows; ++i).
Q2. What are the main types of operators based on the number of operands?
Unary operators act on one operand (for example, ++x or !flag). Binary operators act on two operands (for example, a + b). The conditional operator ?: is a ternary operator acting on three operands.
Q3. Write the general syntax of a switch statement.
The general form of the switch statement (the expression must be an integer or character type; each case label is a constant):
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements (runs when no case matches)
}break stops execution from falling through into the next case.
Q4. Which bitwise operator produces 1 when two corresponding bits are different?
The bitwise exclusive OR operator (^). A bit in a ^ b is 1 exactly when the corresponding bits of a and b differ.
Q5. Differentiate between std::endl and the newline character \n.
Both move output to the next line, but std::endl also flushes the output stream. The character \n only inserts a newline; it does not force a flush.
Q6. If inner and outer blocks declare variables with the same name, which variable is used inside the inner block?
The variable declared in the inner block shadows the one declared in the outer block until the inner scope ends.
Q7. How many operands do unary and binary operators require? Can operator overloading change this number?
A unary operator takes one operand and a binary operator takes two operands. Operator overloading cannot change the number of operands (arity) prescribed by C++.
Q8. Compare if/else and switch selection statements.
if/else evaluates general Boolean conditions, including ranges and compound expressions. switch selects among case labels based on an integral or enumeration expression; each case label is a constant expression, and break prevents unintentional fall-through.
Q9. Define a static local variable and explain its lifetime.
A static local variable has static storage duration. It is initialized once, retains its value between function calls, and exists until program termination.
Q10. Which arithmetic operator cannot accept floating-point operands in C++?
The remainder/modulus operator (%) requires integral operands. It cannot be directly applied to float or double values.
Q11. When is the result of the bitwise exclusive OR (XOR) operation equal to 1 for a pair of bits?
XOR yields 1 when its two input bits differ: 0 XOR 1 = 1 and 1 XOR 0 = 1. It yields 0 if both bits are identical.
Q12. What is a truth Table?
A truth table lists every possible combination of the truth values (true/false) of the operands and shows the result of a logical expression for each combination. It is used to analyse and check complicated logical conditions, and it is the basic tool of logic design.
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 1 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 0 |
| 1 | 1 | 1 | 1 | 0 |
Q13. What does code optimization mean?
It is process by which we make our code such a way that it improves the speed of program. By use of optimization we refine program codes in such a way that it run faster and consume less memory. We do it in such a way that output quality is not compromised.
Q14. What is a language translator? Name two main kinds used in programming.
A language translator is a program that converts a program written in a programming language into a form the computer can execute (machine language). The two main kinds are:
- Compiler: translates the whole program at once and produces an executable file; it reports all syntax errors and generates no executable if there is an error.
- Interpreter: translates and executes the program one statement at a time, stopping at the first error; execution is slower because translation is repeated on every run.
Q15. Explain the role of testing when designing a program.
Testing checks whether the implemented program meets its specified requirements. Prepare test cases covering normal inputs, boundary values, invalid inputs and expected outputs; run the tests, investigate failures, correct errors and repeat. Independent testing can reveal assumptions the programmer missed.
Q16. What is a runtime error?
A runtime error occurs during execution rather than compilation, such as a division by zero, out-of-range memory access or failure to open a required file. Some runtime errors terminate the program; others produce incorrect behavior. Error checking and exception handling can mitigate them.
Q17. Classify LINUX, DISK CLEANUP, WORD PROCESSOR, WINDOWS, and STUDENT INFORMATION SYSTEM as system or application software.
System software: Linux (operating system), Windows (operating system), Disk Cleanup (system utility). Application software: Word processor; Student Information System.
Q18. Define automatic variables and explain why they are called automatic.
An automatic local variable is created when its block is entered and its lifetime normally ends when the block exits. Storage duration is managed automatically by the language, unlike manually allocated dynamic objects. Example: void f() { int x=0; }
Q19. What steps should be followed to design a good computer program?
Analyze the requirements and inputs/outputs; decompose the problem into manageable parts; choose algorithms and data structures; write clear code with meaningful names and comments; test against normal, boundary, and invalid cases; debug, refine, and make reusable components where appropriate.
Q20. Explain the C++ statement const int *ptr = &x;.
ptr points to an integer whose value cannot be modified through ptr. The pointer itself can be reassigned. The declaration is valid if x is an int object whose address can be taken.
Q21. How much memory is allocated by char name[] = "Hello World";, and why?
The array has 12 char elements: 11 visible characters (including the space) plus the terminating null character (\0). Under the C++ definition, sizeof(char) is 1 byte, so sizeof(name) is 12 bytes.
Q22. What does the C++ new operator return, and what happens if allocation fails?
A successful new expression returns a pointer to the newly created object. An ordinary new expression throws std::bad_alloc on allocation failure; new (std::nothrow) returns nullptr instead.
Q23. What is the output of the following C++ code?int x = 10;
int &y = x;
y = 5;
cout << x;
The output is 5 because y is a reference to x. Assigning 5 through y changes the same object x.
Q24. What happens when malloc, calloc, or new cannot allocate the requested memory?
On allocation failure, malloc() and calloc() return a null pointer. In standard C++, ordinary new throws std::bad_alloc; the nothrow form of new returns nullptr. These failure mechanisms must be handled appropriately.
Q25. Declare a float array of ten elements and initialize its first four elements to 1.0, 2.0, 3.0, and 4.0.
float values[10] = {1.0f, 2.0f, 3.0f, 4.0f};The remaining six elements are initialized to zero.
Q26. What two arguments does the C calloc function take?
calloc(count, size) takes the number of elements (count) and the size of each element in bytes (size). It allocates count × size bytes and initializes the allocated bytes to zero.
Q27. What is the benefit of references and when should they be used?
References allow existing objects to be accessed under another name without making copies. Passing a large object as const T& can avoid copying while preventing modification; passing T& permits intentional changes to the caller’s object.
Q28. What is a memory leak?
A memory leak occurs when dynamically allocated storage remains allocated but the program no longer has a usable way to release it. For example, reassigning an owning raw pointer without deleting its previous allocation can leak memory. Prefer automatic storage or RAII types such as std::vector and std::unique_ptr.
Q29. Write the general syntax for dynamically allocating an array using the C++ new operator.
The syntax is Type* ptr = new Type[number_of_elements];. For example, int* values = new int[10]; allocates ten int elements and returns a pointer to the first. Release the allocation with delete[] values;.
Q30. Distinguish an ordinary variable from a pointer variable.
An ordinary variable such as int x = 5; stores a value of its declared type. A pointer variable such as int* p = &x; stores the memory address of an object; *p accesses that object. A pointer has a type that describes the object to which it points.
Q31. Declare a 3 × 3 integer matrix and initialize all nine elements to zero.
int matrix[3][3] = {};The empty initializer value-initializes every element, so all nine integers are zero. The equivalent traditional form is int matrix[3][3] = {0};.
Q32. How can a C++ function accept an argument by reference without allowing it to modify the caller’s object?
Declare the parameter as a const reference, for example void display(const Student& s);. This avoids an unnecessary copy and prevents the function from modifying s through that reference. Other aliases to a non-const object may still modify it independently.
Q33. Explain the advantages and disadvantages of reading a text file character by character versus line by line.
Character-by-character input is useful when every character must be examined, but may require more function calls and manual handling of line boundaries. Line-by-line input using getline() conveniently preserves each line as a unit and is generally clearer for processing line-oriented records. The appropriate approach depends on the required parsing and buffering.
Q34. Give the general syntax of a C++ class template.
template <typename T>
class Box {
T value;
public:
explicit Box(T x) : value(x) {}
};Q35. Show how to call a function template returning int when its argument x is double.
template <typename T, typename U>
T func(U value) { return static_cast<T>(value); }
double x = 3.5;
int result = func<int, double>(x);Q36. What is returned when reciprocal(5) instantiates the following template with T = int?template <typename T> T reciprocal(T x) { return 1 / x; }
The result is 0. Integer division truncates 1/5 to zero. With a floating-point argument, the result would be fractional.
Q37. What is printed when the following functions are each called three times?void func1() { int x=0; ++x; cout << x << endl; }
void func2() { static int x=0; ++x; cout << x << endl; }
func1 prints 1, 1, 1 on separate lines because x is recreated each time. func2 prints 1, 2, 3 because static x persists between calls.
Q38. What is the main advantage of function overloading?
Function overloading makes programs more readable and expressive by allowing related operations on different parameter types to share a descriptive function name.
Q39. Why does a C++ compiler use name mangling?
Name mangling encodes a function’s name and relevant type/signature information in a unique symbol so overloaded functions and other external entities can be distinguished during linking.
Q40. What distinguishes two overloaded functions in C++?
Overload resolution distinguishes functions using their parameter types, parameter count, and (where applicable) their order. Changing only a function’s return type or parameter names does not constitute overloading.
Q41. Can two C++ functions be overloaded if they have the same parameter types but different parameter names? Justify your answer.
No. Parameter names are not part of a function signature for overload resolution. For example, f(int x, int y) and f(int a, int b) have identical parameter types and therefore cannot coexist as two distinct overloads.
Q42. How do we provide the default values of function parameters?
The default value of a parameter is given in the function prototype or in the function definition (but only in one of them), using = after the parameter, and only for the right-most parameters.
int add(int a, int b = 10); // prototype with a default // add(5) -> 15, add(5, 2) -> 7
Q43. Name the two kinds of templates provided by C++.
C++ provides function templates and class templates. A function template defines a family of functions parameterized by types (or values); a class template defines a family of class types.
Q44. Can the C++ functions func(int, int) and func(int&, int&) both be declared? What happens if they are called with two non-const int lvalues?
Both overloads can be declared because their parameter types are different. But a call such as func(a, b), where a and b are non-const int lvalues, is ambiguous: both signatures are viable and neither is preferred. The overload accepting values can be called with integer literals; the reference overload cannot bind non-const int& parameters to literals.
void func(int x, int y); void func(int& x, int& y);
Q45. Write a C++ function template named Add() that adds two values, and call it using integer variables.
#include <iostream>
using namespace std;
template <typename T>
T Add(T a, T b) { return a + b; }
int main() {
int x = 12, y = 25;
cout << "Sum = " << Add(x, y) << "\n";
return 0;
}Q46. Write a C++ program that reads a radius and calculates the area of a circle.
#include <iostream>
using namespace std;
int main() {
const double PI = 3.141592653589793;
double radius;
cin >> radius;
double area = PI * radius * radius;
cout << "Area = " << area << "\n";
return 0;
}Q47. Define a default function argument and give an example.
A default argument is a value given in the function declaration that is used when the caller leaves that argument out. Default arguments must be the right-most parameters.
int power(int base, int exponent = 2); // prototype with a default power(5); // uses exponent = 2 -> 25 power(5, 3); // uses exponent = 3 -> 125
Q48. Write a C++ function template Square that returns the square of its argument. Read a float in main and call Square; for 12.3 the expected output is approximately 151.29.
#include <iostream>
using namespace std;
template <typename T> T Square(T x) { return x * x; }
int main() {
float x; cin >> x;
cout << Square(x) << '\n';
}Q49. Write a C++ program that reads an entire sentence using getline() and prints it.
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentence;
getline(cin, sentence);
cout << sentence << "\n";
return 0;
}Q50. Write C++ code to read characters into a string until a comma is encountered.
#include <iostream>
#include <string>
using namespace std;
int main() {
string text;
getline(cin, text, ',');
cout << text << "\n";
return 0;
}Q51. Write C++ output statements that display the value 1.2345678 to three decimal places, using a field width of nine padded with leading zeros.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double value = 1.2345678;
cout << setfill('0') << setw(9) << fixed << setprecision(3) << value;
return 0;
}Output: 00001.235
Q52. Demonstrate decimal, hexadecimal, and octal output using C++ manipulators.
#include <iostream>
using namespace std;
int main() {
int value = 25;
cout << dec << value << '\n';
cout << hex << value << '\n';
cout << oct << value << '\n';
}Output: 25, 19, 31 (on separate lines).
Q53. If the user enters 123 in octal, what does the following program print in hexadecimal?int input;
cin >> oct >> input;
cout << hex << input;
53. Octal 123 equals decimal 83, which is hexadecimal 53.
Q54. Explain the interpretation of cout << a << b << c; in C++.
Insertion operators associate left to right: ((cout << a) << b) << c. Each insertion returns a stream reference, allowing the next value to be inserted. The variables must be declared and supported by the output operator.
Q55. What are the usual source and destination of input read through cin in C++?
By default, cin reads characters from standard input (normally the keyboard) and extracts them into a destination variable, such as int age; cin >> age;. Input redirection can change the source without changing the program.
Q56. Write a C++ program demonstrating setprecision() with three double variables.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double a = 12.12345, b = 13.123456, c = 14.1234567;
cout << fixed << setprecision(2) << a << "\n";
cout << fixed << setprecision(3) << b << "\n";
cout << fixed << setprecision(4) << c << "\n";
return 0;
}Q57. Write a C++ program that prints two integer variables in decimal, hexadecimal, and octal.
#include <iostream>
using namespace std;
int main() {
int var1 = 25, var2 = 50;
cout << dec << var1 << ' ' << var2 << '\n';
cout << hex << var1 << ' ' << var2 << '\n';
cout << oct << var1 << ' ' << var2 << '\n';
}Q58. What happens to an automatic local variable during recursive function calls?
Each recursive call creates its own activation record and a separate instance of each ordinary local variable. Values for one invocation do not overwrite another invocation’s local variables. The instances cease to exist as their corresponding calls return.
Q59. Are friend functions members of a class? How do they access its data and functions?
A friend function is not a member of the class granting friendship. A declaration inside the class using the friend keyword grants the function access to that class’s private and protected members. It is ordinarily called as a regular non-member function, not through a class object.
Q60. Explain the difference between an ordinary function declaration and a member-function declaration inside a class.
Both declarations specify a name, return type, and parameters. A non-static member-function declaration also establishes a class member with an implicit this pointer when called on an object, and access to the class’s members. Member functions can use public, protected, or private access control.
Q61. Explain the expression if (&m != this) in a copy-assignment operator.
The address &m is compared with this, which points to the current object. If the addresses differ, the right-hand object is not the same as the destination object and it is safe to perform the normal copy-assignment steps. The check prevents self-assignment problems, especially when a class manages dynamic resources.
Q62. What are the two types of conversion involving user-defined class types in C++?
Conversions may go from a built-in type to a class type, commonly through a converting constructor, or from a class type to another type, commonly through a conversion function. Converting constructors can also enable class-to-class conversions. Explicit conversions may be provided to avoid unintended implicit conversions.
Q63. Distinguish between a default constructor and a parameterized constructor.
A default constructor can be called with no arguments and initializes a newly created object. A parameterized constructor accepts arguments to initialize an object with specified values. A class may overload constructors to provide both forms.
Q64. Why may class data members contain indeterminate values when an object is created, and how can this be prevented?
Built-in data members of a default-initialized object are not necessarily initialized automatically. Initialize each member using default member initializers or a constructor initializer list, for example: class A { int x = 0; };
Q65. How are static data members declared and initialized in a C++ class?
A static data member is shared by all objects of the class. It is declared inside the class with static and defined (initialised) once outside the class, at file scope:
class Counter {
public:
static int count; // declaration
};
int Counter::count = 0; // definition and initialisation at file scopeIn C++17 an inline static int count = 0; inside the class is also allowed. It can be accessed as Counter::count or through an object.
Q66. Define a class and an object, with an example.
A class defines a user-defined type containing data and member functions. An object is an instance of the class.
class Student { public: int id; };
Student s; // s is an objectQ67. What is the this pointer in C++? Explain its uses.
Inside a non-static member function, this is a pointer to the object on which the function was called. It can disambiguate a member name (this->x = x), return the current object (*this), and pass the current object to another function.
Q68. State the limitations of C++ friendship between classes.
Friendship is granted explicitly by the class being accessed. It is neither reciprocal nor transitive nor inherited. A friend can access private and protected members but is not itself a member function solely because it is a friend.
Q69. Explain the principle of friendship in C++.
A class may grant a non-member function or another class access to its private and protected members by declaring it as friend. Other functions cannot declare themselves friends of a class.
Q70. How can a containing class initialize an object member when its constructor runs?
Use the member initializer list in the containing class constructor. Example: Widget(int x) : member(x) {}. Object members are initialized in declaration order.
Q71. If class B contains a member object of class A, which class constructs and destroys first?
The A member is constructed before the body of B’s constructor runs. B’s destructor body runs first, then the A member is destroyed. Destruction happens in reverse order of construction.
Q72. When is a class constructor called?
A constructor is called automatically when an object of the class is created (when the object is declared, when it comes into scope, or when it is created with new). For an array of objects it is called once for each element. It initialises the data members of the new object.
Q73. Is a C++ constructor a function, and can it be overloaded?
Yes. A constructor is a special member function: it has the same name as the class and no return type. It can be overloaded, i.e. a class may have several constructors with different parameter lists (default, parameterized, copy), and the compiler selects one from the arguments used when the object is created.
Q74. What is a class in C++?
A class is a user-defined data type (a blueprint) that groups data members and the member functions that operate on them under one name, with access control (public, private, protected) to hide the implementation. Objects are created from it. Example: class Student { int id; public: void setId(int i) { id = i; } };
Q75. How does the linker produce an executable from the compiled object code?
The linker combines the compiled program’s object code with the required object code of library functions, resolves external references, and produces an executable.
Q76. Differentiate between a struct and a class in C++.
Both can contain data, constructors, and member functions. The primary language differences are their default member access and default inheritance access: struct defaults to public; class defaults to private.
Q77. What happens when new and delete are used to create and destroy a class object?
An ordinary new expression obtains storage, initializes the object by calling its constructor, and returns a pointer. A matching delete expression destroys the object by calling its destructor and then releases the storage. Arrays allocated by new[] must be released by delete[] so all their elements are destroyed.
Q78. Give the syntax of a class declaring a non-member function as its friend, including the function definition.
class Box {
int value = 5;
friend int readValue(const Box& b);
};
int readValue(const Box& b) { return b.value; }Q79. What is a nested (inner) class? Give an example.
A nested class is declared within another class and has its own members and access control.
class Outer {
public:
class Inner { public: int value = 0; };
};
Outer::Inner item;Q80. Is it possible to change the meaning of subtraction between two built-in integers by operator overloading?
No. An overloaded operator must involve at least one operand of a class or enumeration type. C++ does not allow the built-in subtraction operation between two int values to be redefined.
Q81. Can the new and delete operators be overloaded?
Yes. A class may provide class-specific operator new and operator delete functions, and global forms can also be defined. These functions customize allocation and deallocation; construction and destruction remain separate stages.
Q82. Identify the copy-construction and assignment operations in these statements:
(a) Matrix m1(m2);
(b) Matrix m1, m2; m1 = m2;
(c) Matrix m1 = m2;
(a) Copy constructor; (b) copy assignment operator; (c) copy constructor (copy-initialization of a new object).
Q83. Give the declarations of pre-increment and post-increment member operator functions.
Member operator functions of a class ClassName:
ClassName& operator++(); // prefix (++obj) ClassName operator++(int); // postfix (obj++): the unused int parameter only distinguishes it
Q84. Write the declarations of overloaded input and output stream operators for a Date class.
class Date {
friend std::ostream& operator<<(std::ostream&, const Date&);
friend std::istream& operator>>(std::istream&, Date&);
};Q85. Explain the difference between unary and binary operators and show how they are overloaded in C++.
A unary operator acts on one operand; a binary operator on two. In a member overloaded unary operator there are no explicit operands; in a member binary operator there is one explicit operand. A non-member unary operator has one argument; a non-member binary operator has two. C++ does not permit changing an operator’s arity or precedence.
class Number {
int value;
public:
explicit Number(int n=0):value(n) {}
Number operator-() const { return Number(-value); }
Number operator+(const Number& b) const { return Number(value+b.value); }
};Q86. Differentiate function overloading from operator overloading.
Function overloading defines multiple functions with the same name but different parameter lists. The compiler selects an appropriate overload based on arguments. Operator overloading defines behavior for existing C++ operators when applied to user-defined types. Operator overloads are special functions named operator+, operator==, etc.; they cannot create new operators or change precedence/arity.
Q87. Why must the first parameter of a non-member output stream insertion operator be passed by reference?
The first parameter is the output stream. Streams cannot be copied, and the operator has to write into the existing stream (for example cout), not into a copy of it. So the parameter is std::ostream&, and the function returns the same reference so that calls can be chained (cout << a << b).
std::ostream& operator<<(std::ostream& os, const Date& d);
Long Questions
Longer questions that need complete code or a full explanation.
Q88. Explain why binary search is more efficient than linear search for a sorted array.
Linear search checks elements one by one until the target is found or the array ends. In the worst case, it requires n comparisons, so its time complexity is O(n). Binary search requires a sorted array; it compares the target with the middle element and discards approximately half of the remaining search interval after each comparison. Therefore its worst-case time complexity is O(log n). For an array of 1,000 sorted elements, linear search may examine all 1,000 elements. Binary search requires at most about 10 comparisons to locate a matching element or determine that it is absent. Binary search is not directly suitable for unsorted data unless the data is sorted or organized appropriately first.
Q89. Write a C++ program that calculates an employee’s salary from days worked and daily pay rate.
#include <iostream>
using namespace std;
int main() {
int days;
double rate;
cout << "Days worked: "; cin >> days;
cout << "Daily rate: "; cin >> rate;
double salary = days * rate;
cout << "Salary: " << salary << '\n';
}Q90. Discuss the advantages and disadvantages of C++ templates.
Advantages: A single generic function or class can work with multiple data types, reducing duplicated code. The compiler checks instantiated code against concrete types and can optimize it. Disadvantages: Template diagnostics may be complex; heavy instantiation can increase compilation time and executable size; complex template metaprogramming can reduce readability. Templates generally require definitions visible where they are instantiated.
Q91. Write a C++ program that defines a user-defined stream manipulator named Octal and uses it to display a number in octal form.
#include <iostream>
using namespace std;
ostream& Octal(ostream& out) {
out.setf(ios::oct, ios::basefield);
return out;
}
int main() {
int number;
cin >> number;
cout << Octal << number << "\n";
return 0;
}Q92. Write a C++ program that reads eight integers into a 2 × 4 matrix and displays the matrix.
#include <iostream>
using namespace std;
int main() {
int a[2][4];
for (int i=0; i<2; ++i)
for (int j=0; j<4; ++j) cin >> a[i][j];
for (int i=0; i<2; ++i) {
for (int j=0; j<4; ++j) cout << a[i][j] << ' ';
cout << '\n';
}
}Q93. Write a C++ program that displays the salaries 1000, 1500, 20000, 30000, and 60000 in a width of ten, padding with x characters.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int salary[] = {1000, 1500, 20000, 30000, 60000};
for (int s : salary)
cout << setfill('x') << setw(10) << s << '\n';
}Q94. Write a C++ program that reads a number in octal and displays it in hexadecimal.
#include <iostream>
using namespace std;
int main() {
int number;
cin >> oct >> number;
cout << hex << number << '\n';
}Q95. Write a C++ program that reads a string of at most ten characters. If it equals "Virtual", print "Correct Password"; otherwise print its first four characters and its length.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
if (s.size() > 10) return 1;
if (s == "Virtual") cout << "Correct Password\n";
else cout << s.substr(0,4) << " " << s.length() << '\n';
}Q96. Define a buffer and explain why buffering improves file input/output performance.
A buffer is a temporary region of memory used to hold data while it is transferred between a program and an input/output device. For output, the program accumulates multiple values in memory and writes them to a file as a larger block, reducing the number of relatively expensive device operations. Input buffering similarly reads a block of data and supplies it to the program as needed. A buffer is flushed when its contents are written to the destination; buffered output should be flushed or the stream closed when the data must be safely delivered. Example: Instead of issuing a separate file write for each of 1,000 numbers, a program can accumulate a batch of numbers in a buffer and write the batch. Buffering reduces I/O overhead, although it does not eliminate the need to handle failed writes or ensure that the final partial buffer is flushed.
Q97. List the important steps when implementing an assignment operator for a class that manages dynamic memory.
Check whether the source and destination are the same object; allocate replacement storage if necessary; copy the source data; release or safely replace the old resource; maintain class invariants; and return *this by reference to support chained assignment. A copy-and-swap implementation is another safe approach.
Q98. Write a safe copy-assignment operator for a String class that manages a dynamically allocated character buffer and handles self-assignment.
#include <cstring>
#include <utility>
class String {
char* buf;
public:
String() : buf(new char[1]{'\0'}) {}
explicit String(const char* text) {
buf = new char[std::strlen(text) + 1];
std::strcpy(buf, text);
}
String(const String& other) : String(other.buf) {}
~String() { delete[] buf; }
String& operator=(const String& other) {
if (this == &other) return *this;
char* next = new char[std::strlen(other.buf) + 1];
std::strcpy(next, other.buf);
delete[] buf;
buf = next;
return *this;
}
};Q99. Explain what a Matrix constructor does when it stores row and column counts, allocates a two-dimensional array dynamically, and fills every element with zero.
It stores the requested row and column sizes, allocates an array of row pointers, allocates a column array for each row, and initializes each matrix entry to 0.0. The class must deallocate each row followed by the pointer array in its destructor. In modern C++, std::vector is generally safer than manual ownership of a double**. Correctly written form of the constructor described in the question:
Matrix::Matrix(int row, int col) {
numRows = row;
numCols = col;
elements = new double*[numRows];
for (int i = 0; i < numRows; ++i) {
elements[i] = new double[numCols];
for (int j = 0; j < numCols; ++j)
elements[i][j] = 0.0;
}
}Q100. Do friend functions violate encapsulation? Justify your answer.
Friendship is an explicit, controlled exception to normal access rules. It exposes private members only to the named function or class, not to all callers. Overusing friendship may increase coupling and weaken information hiding, so it should be granted only where necessary.
Q101. What problems can arise when a class with an owning pointer data member is assigned to another object, and one of the objects is deleted?
The compiler-generated copy assignment usually copies the pointer value (shallow copy). Both objects then point to the same allocation. If one deletes that allocation, the other pointer dangles; subsequent dereference or deletion is undefined behavior. Implement appropriate copy/move operations (Rule of Three/Five) or use RAII types such as std::vector or std::unique_ptr.
Q102. Write a C++ program with a class myClass containing two integer data members, a default constructor, a destructor, setters and getters. Ask the user for the number of objects, allocate an array dynamically, and then free it.
#include <iostream>
using namespace std;
class myClass {
int a, b;
public:
myClass() : a(0), b(0) {}
~myClass() {}
void setA(int x) { a = x; }
void setB(int x) { b = x; }
int getA() const { return a; }
int getB() const { return b; }
};
int main() {
int count;
cin >> count;
if (count < 0) return 1;
myClass* items = new myClass[count];
delete[] items;
}Q103. Write a C++ program using a Date class and a Person class. Date must contain day, month and year, setters and getters, and a showdate() function. Person must contain Name and Address as char pointers and a Bday member of type Date, with Display() and setdate() functions. In main(), create a Person object and call its member functions.
One complete implementation is shown below. The Person class allocates and frees the character buffers that it owns; its copy operations are disabled to prevent accidental shallow copies.
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class Date {
int day, month, year;
public:
Date() : day(1), month(1), year(2000) {}
void setDay(int d) { day = d; }
void setMonth(int m) { month = m; }
void setYear(int y) { year = y; }
int getDay() const { return day; }
int getMonth() const { return month; }
int getYear() const { return year; }
void showdate() const {
cout << getDay() << '-' << getMonth() << '-' << getYear();
}
};
class Person {
char* Name;
char* Address;
Date Bday;
static char* copyText(const char* text) {
char* p = new char[strlen(text) + 1];
strcpy(p, text);
return p;
}
public:
Person(const char* name, const char* address)
: Name(copyText(name)), Address(copyText(address)) {}
Person(const Person&) = delete;
Person& operator=(const Person&) = delete;
~Person() { delete[] Name; delete[] Address; }
void setdate(int d, int m, int y) {
Bday.setDay(d);
Bday.setMonth(m);
Bday.setYear(y);
}
void Display() const {
cout << "Name: " << Name << '\n';
cout << "Address: " << Address << '\n';
cout << "Date of Birth: ";
Bday.showdate();
cout << '\n';
}
};
int main() {
string name, address;
int day, month, year;
cout << "Name: "; getline(cin, name);
cout << "Address: "; getline(cin, address);
cout << "Birth date (day month year): ";
if (!(cin >> day >> month >> year)) return 1;
Person person(name.c_str(), address.c_str());
person.setdate(day, month, year);
person.Display();
}Q104. Write an overloaded stream-insertion operator (<<) for a class Matrix that stores a 3 × 3 integer array Elements.
#include <iostream>
using namespace std;
class Matrix {
int Elements[3][3]{};
public:
friend ostream& operator<<(ostream& os, const Matrix& m) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j)
os << m.Elements[i][j] << (j == 2 ? "" : " ");
os << "\n";
}
return os;
}
};Q105. Write a non-member stream extraction operator for the following class to input its 3 × 3 integer matrix: class Matrix { int Elements[3][3]; };
#include <iostream>
class Matrix {
int Elements[3][3];
public:
friend std::istream& operator>>(std::istream& in, Matrix& m) {
for (int i=0; i<3; ++i)
for (int j=0; j<3; ++j) in >> m.Elements[i][j];
return in;
}
};Q106. A math class contains one data member number. Overload + to support the expression obj2 = 10 + obj1.
class Math {
int number;
public:
explicit Math(int n=0) : number(n) {}
friend Math operator+(int n, const Math& m) {
return Math(n + m.number);
}
};
Math obj1(5);
Math obj2 = 10 + obj1;Part 3: Short Notes & Key Terms
- Class
- A user-defined type that groups data members and member functions under one name, with access control.
- Object
- An instance of a class; it occupies memory and has its own copy of the non-static data members.
- Encapsulation
- Binding data and the functions that operate on it into one unit and hiding the details with private/protected access.
- Constructor
- Special member function with the class name and no return type, called automatically when an object is created; it can be overloaded.
- Destructor
- Member function named ~ClassName with no parameters and no return type, called automatically when an object is destroyed; used to release resources.
- Copy constructor
- Constructor of the form ClassName(const ClassName&) that creates a new object as a copy of an existing one; the default one makes a shallow copy.
- Shallow vs deep copy
- Shallow copy copies pointer values (both objects share the same memory); deep copy allocates new memory and copies the contents.
- this pointer
- Implicit pointer available inside non-static member functions that points to the current object.
- static data member
- One copy shared by all objects of the class; defined once outside the class and accessible as Class::name.
- static member function
- Belongs to the class, not to an object; has no this pointer and can access only static members.
- const member function
- Declared with const after the parameter list; it promises not to modify the object's data members.
- Friend function
- A non-member function given access to the private and protected members of a class by a friend declaration inside the class.
- Operator overloading
- Giving operators such as + , ++ , << a user-defined meaning for class types; precedence and number of operands cannot change.
- Prefix vs postfix ++
- operator++() is prefix; operator++(int) is postfix, where the unused int only distinguishes it.
- Inheritance
- A new (derived) class acquires the members of an existing (base) class, enabling code reuse.
- Access in inheritance
- Private members of the base are never directly accessible in the derived class; protected members are accessible there but not outside.
- Polymorphism
- One interface, many forms: compile-time (overloading) and run-time (virtual functions).
- Virtual function
- A base class member function declared virtual so that the call is resolved at run time according to the actual object type.
- Pure virtual function / abstract class
- A function declared = 0; a class with at least one pure virtual function is abstract and cannot be instantiated.
- Function overloading
- Several functions with the same name but different parameter lists; the return type alone is not enough.
- Default arguments
- Values given in the prototype that are used when the caller omits trailing arguments.
- Pass by value vs reference
- By value copies the argument; by reference (or pointer) lets the function change the caller's variable.
- Pointer
- A variable that stores a memory address; dereferenced with *, address taken with &.
- new and delete
- new allocates memory on the heap and calls the constructor; delete frees it and calls the destructor; use delete[] for arrays.
- Array
- A fixed-size collection of elements of the same type in contiguous memory; indexes start at 0 and C-strings need one extra byte for the null character.
- Stream operators
- << (insertion) writes to an output stream and >> (extraction) reads from an input stream; overloaded versions take the stream by reference and return it for chaining.
- Compiler vs interpreter
- A compiler translates the whole program into an executable at once; an interpreter translates and runs one statement at a time.
- Truth table
- A table of all combinations of true/false inputs and the result of a logical expression.
- switch statement
- Multi-way selection on an integer or character expression; break prevents fall-through and default handles the unmatched case.
- Reference
- An alias for an existing variable; it must be initialised when declared and cannot be re-seated.
No comments:
Post a Comment
Please give us your feedback & help us to improve this site.