28.10.26

CS304 Midterm Past Papers: Solved MCQs and Subjective Questions (Object Oriented Programming)

Getting ready for the midterm of CS304 (Object Oriented 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. The technique in which we visualize our programming problems according to real life's problems is called ______.

  1. structured programming
  2. object oriented programming
  3. procedural programming
  4. none of the given
Show answer

Answer: (b) object oriented programming

Q2. Three main characteristics of Object Oriented Programming are:

  1. Encapsulation, dynamic binding, polymorphism
  2. polymorphism, overloading, overriding
  3. encapsulation, inheritance, dynamic binding
  4. encapsulation, inheritance, polymorphism
Show answer

Answer: (d) encapsulation, inheritance, polymorphism

Q3. Which of the following is an advantage of OOP?

  1. OOP makes it easy to re-use the code
  2. It provides an ability to create one user defined data type by extending the other
  3. It provides the facility of defining Abstract data types through which real world entities can be defined better
  4. All of the given options
Show answer

Answer: (d) All of the given options

Q4. Which part of an object exhibits its state?

  1. Data
  2. Operations
  3. Any public part
  4. Any private part
Show answer

Answer: (a) Data

Q5. Only tangible things can be chosen as an object.

  1. True
  2. False
Show answer

Answer: (b) False
Why: Intangible things (a bank account, a loan, a date) can also be objects.

Q6. A real world object can be transformed into a programming entity by defining its respective

  1. Class
  2. Function
  3. Only states
  4. Only behaviour
Show answer

Answer: (a) Class

Q7. If some objects exhibit identical characteristics, then they belong to:

  1. Different classes
  2. Multiple classes
  3. Same class
  4. None of the given
Show answer

Answer: (c) Same class

Q8. In OOP a class is an example of ______.

  1. Data Type
  2. Abstract Type
  3. User Defined Type
  4. None of the given
Show answer

Answer: (c) User Defined Type

Q9. A C++ class is similar to ______.

  1. Structure
  2. Header File
  3. Library File
  4. None of the given
Show answer

Answer: (a) Structure
Why: Both are user defined types; the difference is that members of a class are private by default and members of a struct are public by default.

Q10. A class can be identified from a statement by ______.

  1. Noun
  2. Pronoun
  3. Verb
  4. Adverb
Show answer

Answer: (a) Noun

Q11. We capture the object attributes and behavior in Object Oriented Programming using ______.

  1. Class
  2. Function
  3. Data Members
  4. Instances
Show answer

Answer: (a) Class

Q12. Suppose there is an object of type Person. Which of the following can be considered as one of its attributes?

  1. Name
  2. Age
  3. Work()
  4. Both Name and Age
Show answer

Answer: (d) Both Name and Age

Q13. Data members are the attributes of objects.

  1. True
  2. False
Show answer

Answer: (a) True

Q14. Data items in a class must be private.

  1. True
  2. False
Show answer

Answer: (b) False
Why: Data is usually kept private to support data hiding, but the language does not force it.

Q15. Class is not a mechanism to create objects and define user data types.

  1. True
  2. False
Show answer

Answer: (b) False
Why: The statement is negative: a class is exactly the mechanism used to create objects and define user defined types, so the statement is false.

Q16. Class abc{ ----- }; Is a valid class declaration?

  1. Yes
  2. No
Show answer

Answer: (a) Yes
Why: The dashes stand for the class body. In real C++ the keyword is written in lower case (class abc { ... };).

Q17. Graphical representation of the classes and objects is called an object model. It shows ______.

  1. Class Name only
  2. Class Name and attributes
  3. Relationships of the objects and classes
  4. all of the given
Show answer

Answer: (d) all of the given

Q18. A good model is ______ related to a real life problem.

  1. Loosely
  2. Openly
  3. Closely
  4. Not
Show answer

Answer: (c) Closely

Q19. Consider a class named Vehicle. Which of the following can be instances of class Vehicle? (1. Car, 2. Computer, 3. Desk, 4. Ahmed, 5. Bicycle, 6. Truck)

  1. 1, 4, 5
  2. 2, 5, 6
  3. 1, 2, 3, 6
  4. 1, 5, 6
Show answer

Answer: (d) 1, 5, 6
Why: Car, Bicycle and Truck are vehicles. A computer and a desk are not vehicles, and Ahmed is a person.

Q20. Which one of the following terms best represents the statement "Hiding details of an object from the other parts of a program"?

  1. Obfuscation
  2. Data Mining
  3. Compilation
  4. Encapsulation
Show answer

Answer: (d) Encapsulation

Q21. Using encapsulation we can achieve

  1. Information hiding
  2. Least interdependencies among modules
  3. Implementation independence
  4. All of given options
Show answer

Answer: (a) Information hiding
Why: Answer as per the handout key (information hiding).

Q22. Information hiding can be achieved through ______.

  1. Encapsulation, Inheritance
  2. Encapsulation, Polymorphism
  3. Encapsulation, Abstraction
  4. Encapsulation, Overloading
Show answer

Answer: (c) Encapsulation, Abstraction

Q23. We achieve independence of internal implementation from its external interface through ______.

  1. Encapsulation
  2. Information Hiding
  3. Abstraction
  4. both encapsulation and information hiding
Show answer

Answer: (c) Abstraction
Why: Answer as per the handout key (abstraction).

Q24. Which of the following features of OOP is used to deal with only relevant details?

  1. Abstraction
  2. Information hiding
  3. Object
  4. Inheritance
Show answer

Answer: (a) Abstraction

Q25. An employee working in an organization has: 1. Name 2. Past experience 3. Age 4. Relatives 5. Hobbies in spare time. Keeping in view the principle of abstraction, which of the above information does the company need to save as the employee's record?

  1. 2, 4
  2. 1, 3, 5
  3. 1, 2, 3
  4. 1, 2, 3, 4
Show answer

Answer: (c) 1, 2, 3

Q26. Which one is a class association?

  1. Simple Association
  2. Inheritance
  3. Composition
  4. Aggregation
Show answer

Answer: (b) Inheritance
Why: Simple association, composition and aggregation are object associations; inheritance is the relationship between classes.

Q27. Which one of the following is not an object association?

  1. Simple Association
  2. Inheritance
  3. Aggregation
  4. Composition
Show answer

Answer: (b) Inheritance

Q28. Which of the following is a weak relationship between two objects?

  1. Inheritance
  2. Composition
  3. Aggregation
  4. None of given
Show answer

Answer: (c) Aggregation

Q29. The life of a sub-object is not dependent on the life of the master class in ______.

  1. Composition
  2. Aggregation
  3. Separation
  4. None of the given
Show answer

Answer: (b) Aggregation

Q30. The life of a sub-object is dependent on the life of the master class in ______.

  1. Separation
  2. Composition
  3. Aggregation
  4. None of the given
Show answer

Answer: (b) Composition

Q31. Consider the statement "room has chair". Which type of association exists between room and chair?

  1. Inheritance
  2. Composition
  3. There is no association
  4. Aggregation
Show answer

Answer: (d) Aggregation
Why: A chair can exist without the room, so it is aggregation.

Q32. The ______ relationship indicates that an object contains other objects.

  1. None of given
  2. 'has-a'
  3. 'is-a'
Show answer

Answer: (b) 'has-a'
Why: The shared key said "None of given", but a 'has-a' relationship is exactly containment (composition/aggregation). A fourth option was cut off in the source and is left out.

Q33. It is illegal to make objects of one class members of another class.

  1. True
  2. False
Show answer

Answer: (b) False
Why: This is composition/aggregation and is perfectly legal.

Q34. A generalization-specialization relation between classes is implemented using

  1. data hiding
  2. friend classes
  3. encapsulation
  4. inheritance
Show answer

Answer: (d) inheritance

Q35. Which of the following is the way to extract common behavior and attributes from the given classes and make a separate class of those common behaviors and attributes?

  1. Generalization
  2. Sub-typing
  3. Specialization
  4. Extension
Show answer

Answer: (a) Generalization

Q36. If only one behaviour of a derived class is incompatible with the base class, then it is:

  1. Generalization
  2. Specialization
  3. Extension
  4. Inheritance
Show answer

Answer: (b) Specialization

Q37. The ability to derive a class from more than one class is called

  1. Single inheritance
  2. Encapsulation
  3. Multiple inheritance
  4. Polymorphism
Show answer

Answer: (c) Multiple inheritance

Q38. Which of the following is not an example of multiple inheritance?

  1. Mermaid
  2. Woman
  3. None of the given
  4. Amphibious Vehicle
Show answer

Answer: (b) Woman
Why: A mermaid (woman + fish) and an amphibious vehicle (car + boat) combine two parents; a woman does not.

Q39. Which of the following features of OOP is used to derive a class from another?

  1. Encapsulation
  2. Polymorphism
  3. Data hiding
  4. Inheritance
Show answer

Answer: (d) Inheritance

Q40. Inheritance is a way to

  1. organize data.
  2. pass arguments to objects of classes.
  3. add features to existing classes without rewriting them.
  4. improve data-hiding and encapsulation.
Show answer

Answer: (c) add features to existing classes without rewriting them.

Q41. Inheritance is a way to

  1. make general classes into more specific classes.
  2. pass arguments to objects of classes.
  3. improve data hiding and encapsulation.
  4. providing class growth through natural selection.
Show answer

Answer: (a) make general classes into more specific classes.
Why: Same stem as the previous question but with a different option set.

Q42. In object oriented programming, a class of objects can ______ properties from another class of objects.

  1. Utilize
  2. Borrow
  3. Inherit
  4. Adopt
Show answer

Answer: (c) Inherit

Q43. The concept of derived classes is involved in

  1. inheritance
  2. encapsulation
  3. structure
  4. array
Show answer

Answer: (a) inheritance

Q44. What can a derived class add?

  1. New data members
  2. New member functions and new friend functions
  3. New constructors and destructor
  4. All of given
Show answer

Answer: (d) All of given

Q45. For classes with common behavior, you can save effort by placing the common behavior in a ______.

  1. Derived Class
  2. Base class
  3. Deprived Class
  4. Named class
Show answer

Answer: (b) Base class

Q46. ______ is a relationship.

  1. Inheritance
  2. Polymorphism
  3. Abstraction
  4. Encapsulation
Show answer

Answer: (a) Inheritance
Why: The stem is incomplete in the source ('is-a' relationship); the handout key is inheritance.

Q47. If a class A inherits from class B, then class A is called

  1. Child class
  2. Derived class
  3. Parent class
  4. Child and derived class
Show answer

Answer: (d) Child and derived class

Q48. Suppose you have been given the following design: "A person has a name, age, address and sex. You are designing a class to represent a type of person called a patient. This kind of person may be given a diagnosis, have a spouse and may be alive." Given that the Person class has already been created, which of the following would be appropriate to include when you design the Patient class?

  1. registration date and diagnosis
  2. age and sex
  3. sex and diagnosis
  4. diagnosis and age
Show answer

Answer: (a) registration date and diagnosis
Why: Age and sex are already inherited from Person, so only new attributes (registration date, diagnosis) belong in Patient.

Q49. Your chief software designer shows a sketch: at the top of the hierarchy is a class Computer with two child classes, LinuxPC and WindowsPC. The main difference between the two is the operating system. Under WindowsPC are two subclasses, Server and Workstation. How might you appraise the design?

  1. Give the go-ahead for further design using the current scheme
  2. Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type
  3. Ask for the option of WindowsPC to be removed as it will soon be obsolete
  4. Change the hierarchy to remove the need for the superfluous Computer Class.
Show answer

Answer: (b) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type
Why: When subclasses differ only by a value (the operating system), that value should be a data member, not a new class.

Q50. Which is not an advantage of inheritance?

  1. providing class growth through natural selection.
  2. facilitating class libraries.
  3. avoiding the rewriting of code.
  4. providing a useful conceptual framework.
Show answer

Answer: (a) providing class growth through natural selection.
Why: The shared key was 'avoiding the rewriting of code', which is wrong: reuse without rewriting is the main advantage of inheritance (see the 'add features to existing classes without rewriting them' question above). 'Class growth through natural selection' appears as a wrong option elsewhere in the same paper.

Q51. The major goal of inheritance in C++ is:

  1. To facilitate the conversion of data types.
  2. To help modular programming.
  3. To extend the capabilities of a class.
  4. To hide the details of base class.
Show answer

Answer: (c) To extend the capabilities of a class.

Q52. A member function having the same name as that of a class and a ~ sign with it is called

  1. Constructor
  2. Getter
  3. Setter
  4. Destructor
Show answer

Answer: (d) Destructor

Q53. If MyClass has a destructor, what is the destructor named?

  1. MyClass
  2. ~MyClass
  3. My~Class
  4. MyClass~
Show answer

Answer: (b) ~MyClass

Q54. In order to free the memory occupied by the object, we use ______.

  1. Constructor
  2. Destructor
  3. Shallow Copy
  4. Deep Copy
Show answer

Answer: (b) Destructor

Q55. The return type of a constructor is of ______.

  1. Integer
  2. Character
  3. Double
  4. No type
Show answer

Answer: (d) No type

Q56. Constructor has the same name as the class name.

  1. True
  2. False
Show answer

Answer: (a) True

Q57. ______ is automatically called when the object is created.

  1. member function
  2. object
  3. constructor
  4. None of the given
Show answer

Answer: (c) constructor

Q58. When is a constructor called?

  1. Each time the constructor identifier is used in a program statement
  2. During the instantiation of a new object
  3. During the construction of a new class
  4. At the beginning of any program execution
Show answer

Answer: (b) During the instantiation of a new object

Q59. A default constructor is such a constructor which either has no ______ or, if it has some parameters, these have ______ values.

  1. Parameter, temporary
  2. Null, Parameter
  3. Parameter, default
  4. none of the given
Show answer

Answer: (c) Parameter, default

Q60. Destructor can be overloaded.

  1. True
  2. False
Show answer

Answer: (b) False
Why: A class has only one destructor; it takes no parameters.

Q61. Constructor and destructor can be declared constant.

  1. True
  2. False
Show answer

Answer: (b) False

Q62. When we create objects, then space is allocated to:

  1. Member functions
  2. Access specifier
  3. Data members
  4. None of the given
Show answer

Answer: (c) Data members
Why: Member functions are stored once for the class, not once per object.

Q63. Consider the code below: class Fred { public: Fred(); ... }; int main() { Fred a[10]; Fred* p = new Fred[10]; ... } Select the best option.

  1. Fred a[10]; calls the default constructor 9 times; Fred* p = new Fred[10]; calls the default constructor 10 times
  2. Produce an error
  3. Fred a[10]; calls the default constructor 11 times; Fred* p = new Fred[10]; calls the default constructor 11 times
  4. Fred a[10]; calls the default constructor 10 times; Fred* p = new Fred[10]; calls the default constructor 10 times
Show answer

Answer: (d) Fred a[10]; calls the default constructor 10 times; Fred* p = new Fred[10]; calls the default constructor 10 times
Why: The shared key (11 and 11) is wrong. Each array of 10 objects calls the default constructor exactly once per element, so 10 times for both.

Q64. To initialize an array of objects, only ______ will be called.

  1. Default Constructor
  2. Overloaded Constructor
  3. Default Object
  4. None of the above
Show answer

Answer: (a) Default Constructor

Q65. C++ compiler does not allow to dynamically allocate memory for objects.

  1. True
  2. False
Show answer

Answer: (b) False
Why: Objects can be created dynamically with the new operator.

Q66. Consider two lines of code written for a class Student: 1. Student sobj1; 2. Student sobj2 = sobj1; In line No. 1, which constructor of the Student class will be called?

  1. Default constructor of Student class.
  2. Copy constructor of student class
  3. Both default and copy constructor of student class
  4. None of the given options
Show answer

Answer: (a) Default constructor of Student class.

Q67. Consider two lines of code written for a class Student: 1. Student sobj1; 2. Student sobj2(sobj1); In line No. 2, which constructor of the Student class will be called?

  1. Default constructor of Student class
  2. Copy constructor of Student class
  3. Both default and copy constructor of Student class
  4. No constructor will be called
Show answer

Answer: (b) Copy constructor of Student class

Q68. Consider two lines of code written for a class Student: 1. Student sobj1, sobj2; 2. sobj2 = sobj1; In line No. 2, which constructor of the Student class will be called?

  1. Default constructor of Student class.
  2. Copy constructor of Student class
  3. Both default and copy constructor of Student class
  4. No constructor will be called.
Show answer

Answer: (d) No constructor will be called.
Why: Both objects already exist after line 1, so line 2 is an assignment (assignment operator), not a construction. One shared key marked 'Default constructor', which is wrong.

Q69. There is only one form of copy constructor.

  1. True
  2. False
Show answer

Answer: (b) False
Why: A copy constructor can take const X& or X& (and further parameters with default values).

Q70. What problem(s) may occur when we copy objects without using a deep copy constructor?

  1. Dangling pointer
  2. Memory Leakage
  3. All of the given
  4. System crash
Show answer

Answer: (c) All of the given

Q71. If a class involves dynamic memory allocation, then:

  1. Default copy constructor, shallow copy is implemented
  2. User defined copy constructor, shallow copy is implemented
  3. Default copy constructor, deep copy is implemented
  4. User defined copy constructor, deep copy is implemented
Show answer

Answer: (d) User defined copy constructor, deep copy is implemented
Why: The ends of three options were cut off in the source ('implement', 'impl'); they are written out in full here.

Q72. In case of dynamic memory allocation in a class we should use

  1. User defined default constructor
  2. User defined copy constructor
  3. Both of these
  4. None of these
Show answer

Answer: (c) Both of these

Q73. By default, the assignment operator (=) performs

  1. Shallow copy
  2. Deep copy
  3. Both of these
  4. None of these
Show answer

Answer: (a) Shallow copy

Q74. A compiler generated copy constructor performs

  1. Shallow copy
  2. Deep copy
  3. Both of these options
  4. None of these options
Show answer

Answer: (a) Shallow copy

Q75. Suppose that the Test class does not have an overloaded assignment operator. What happens when an assignment a = b is given for two Test objects a and b?

  1. The automatic assignment operator is used
  2. The copy constructor is used
  3. Compiler error
  4. Run-time error
Show answer

Answer: (a) The automatic assignment operator is used
Why: The shared key said 'the copy constructor is used', which is wrong: a and b already exist, so the compiler-supplied assignment operator (a memberwise, shallow copy) runs. A copy constructor is used only when a new object is created from an existing one.

Q76. A copy constructor is invoked when

  1. a function does not return by value.
  2. an argument is passed by value.
  3. a function returns by reference.
  4. an argument is passed by reference.
Show answer

Answer: (b) an argument is passed by value.

Q77. this pointers are not accessible for static member functions.

  1. True
  2. False
Show answer

Answer: (a) True

Q78. The this pointer does not pass implicitly to ______ functions.

  1. Static Member
  2. Non-Static Member
  3. Instance Number
  4. None of the given
Show answer

Answer: (a) Static Member

Q79. A static member function can be called even when a class is not ______.

  1. Declared
  2. Defined
  3. Instantiated
  4. Called
Show answer

Answer: (c) Instantiated

Q80. A static member function cannot be declared ______.

  1. Static
  2. Implicit
  3. Explicit
  4. Virtual
Show answer

Answer: (d) Virtual
Why: A static member function has no this pointer, so it cannot be virtual.

Q81. ______ remain in memory even when all objects of a class have been destroyed.

  1. Static variables
  2. Instance variable
  3. Primitive variables
  4. None of given
Show answer

Answer: (a) Static variables

Q82. We can get only one unique value which can be used by all the objects of that class by the use of

  1. static variables
  2. dynamic variables
  3. instance variables
  4. data members
Show answer

Answer: (a) static variables

Q83. When a variable is defined as static in a class then all objects of this class

  1. Have different copies of this variable
  2. Have same copy of this variable
  3. Can not access this variable
  4. None of given
Show answer

Answer: (b) Have same copy of this variable

Q84. Static variables act like a global variable in the context or scope of the class.

  1. True
  2. False
Show answer

Answer: (a) True

Q85. A static variable can be initialized more than once.

  1. True
  2. False
Show answer

Answer: (b) False
Why: A static data member is initialized once, at its definition outside the class. (One shared file marked True for the same statement; the handout says it is initialized once.)

Q86. Static data members are called ______ variable.

  1. Class
  2. Object
  3. Structure
  4. none of the given
Show answer

Answer: (a) Class

Q87. The members of a class that can be accessed without creating an object of the class are called

  1. Private member
  2. Data Member
  3. Public Member
  4. Static
Show answer

Answer: (d) Static
Why: One shared key marked 'Public member', but public members still need an object; static members are accessible through the class name.

Q88. Constant objects cannot change their state.

  1. True
  2. False
Show answer

Answer: (a) True

Q89. An object can be declared constant with the use of the Constant keyword.

  1. True
  2. False
Show answer

Answer: (a) True
Why: The actual keyword is const.

Q90. The keyword that is used so that the variable cannot change state is ______.

  1. static
  2. const
  3. friend
  4. private
Show answer

Answer: (b) const

Q91. In a constant member function the type of the this pointer is:

  1. Constant pointer
  2. Constant pointer to object
  3. Constant pointer to class
  4. Constant pointer to constant object
Show answer

Answer: (d) Constant pointer to constant object
Why: Most shared files marked 'Constant pointer to object', but in a const member function this has the type const X * const: a constant pointer to a constant object (see Microsoft's 'Type of this Pointer' documentation).

Q92. ______ provides the facility to access the data member.

  1. accessor function
  2. private function
  3. inline function
  4. None of the given
Show answer

Answer: (a) accessor function

Q93. Given the following class: class Base { int Age = 33; }. How can you improve the above class with respect to accessing the field Age?

  1. Define the variable Age as private
  2. Define the variable Age as protected
  3. Define the variable Age as private and create a get method that returns it and a set method that updates it
  4. Define the variable Age as protected and create a set method that returns it and a get method that updates it
Show answer

Answer: (c) Define the variable Age as private and create a get method that returns it and a set method that updates it

Q94. The outside world can access only ______ members of a class using its object.

  1. Public
  2. Private
  3. Protected
  4. No member is accessible.
Show answer

Answer: (a) Public

Q95. The main function of the scope resolution operator (::) is

  1. To define an object
  2. To define a data member
  3. To link the definition of an identifier to its declaration
  4. To make a class private
Show answer

Answer: (c) To link the definition of an identifier to its declaration

Q96. The dot operator (class member access operator) connects the following two entities (reading from left to right):

  1. A class member and a class object
  2. A class object and a class
  3. A class and a member of that class
  4. A class object and a member of that class
Show answer

Answer: (d) A class object and a member of that class

Q97. Which one of the following operators is used to access members of value data types?

  1. ->
  2. .
  3. &
  4. None of the given options
Show answer

Answer: (b) .

Q98. The ______ keyword tells the compiler to substitute the code within the function definition for every instance of a function call.

  1. virtual
  2. inline
  3. instance
  4. none of the given
Show answer

Answer: (b) inline

Q99. What is a class?

  1. A class is a section of computer memory containing objects
  2. A class is a section of the hard disk reserved for object oriented programs
  3. A class is the part of an object that contains the variables.
  4. A class is a description of a kind of object
Show answer

Answer: (d) A class is a description of a kind of object

Q100. Friend functions are ______ functions of a class.

  1. None of given
  2. object member
  3. non-member
  4. data member
Show answer

Answer: (c) non-member

Q101. Friend functions of a class are ______ members of that class.

  1. Public
  2. Private
  3. Protected
  4. None of the given options.
Show answer

Answer: (d) None of the given options.
Why: A friend function is not a member of the class at all.

Q102. ______, which means if A declares B as its friend it does NOT mean that A can access private data of B. It only means that B can access all data of A.

  1. Friendship is one way only
  2. Friendship is two way only
  3. NO Friendship between classes
  4. Any kind of friendship
Show answer

Answer: (a) Friendship is one way only

Q103. Friend class and friend function can be used as an alternate to each other.

  1. True
  2. False
Show answer

Answer: (a) True

Q104. It is possible to declare as a friend

  1. a member function
  2. a global function
  3. a class
  4. all of the above
Show answer

Answer: (d) all of the above

Q105. The following can be declared as a friend in a class:

  1. an object
  2. a class
  3. a public data member
  4. a private data member
Show answer

Answer: (b) a class

Q106. A friend function of a class C cannot access

  1. private data members and member functions.
  2. public data members and member functions.
  3. protected data members and member functions.
  4. the data members of the derived class of C.
Show answer

Answer: (d) the data members of the derived class of C.

Q107. Operator overloading is

  1. making C++ operators work with objects.
  2. giving C++ operators more than they can handle.
  3. giving new meanings to existing Class members.
  4. making new C++ operators
Show answer

Answer: (a) making C++ operators work with objects.

Q108. A normal C++ operator that acts in special ways on newly defined data types is said to be

  1. glorified.
  2. encapsulated.
  3. classified.
  4. overloaded.
Show answer

Answer: (d) overloaded.

Q109. Which operator can not be overloaded?

  1. The relation operator ( >= )
  2. Assignment operator ( = )
  3. Script operator ( [] )
  4. Conditional operator ( ? : )
Show answer

Answer: (d) Conditional operator ( ? : )

Q110. The operator that cannot be overloaded is

  1. ++
  2. ::
  3. ( )
  4. ~
Show answer

Answer: (b) ::

Q111. The >= operator can be overloaded.

  1. True
  2. False
Show answer

Answer: (a) True

Q112. The compiler won't object if you overload the * operator to perform division.

  1. True
  2. False
Show answer

Answer: (a) True
Why: It compiles, but it is poor design because it confuses users.

Q113. An overloaded operator always requires one less argument than its number of operands.

  1. True
  2. False
Show answer

Answer: (a) True
Why: True for member-function overloads, where the left operand is the calling object (the key from the handout reference).

Q114. Associativity can be changed in operator overloading.

  1. True
  2. False
Show answer

Answer: (b) False
Why: Neither precedence nor associativity (nor the number of operands) can be changed.

Q115. Unary operators and the assignment operator are right associative.

  1. True
  2. False
Show answer

Answer: (a) True

Q116. Which of the following operators always takes no argument if overloaded?

  1. /
  2. -
  3. +
  4. ++
Show answer

Answer: (d) ++

Q117. Which of the following operator(s) take(s) one or no argument if overloaded?

  1. ++
  2. *
  3. %
  4. All of the given choices
Show answer

Answer: (d) All of the given choices
Why: As member functions, unary operators take no argument and binary operators take one.

Q118. Assume a class C with objects obj1, obj2 and obj3. For the statement obj3 = obj1 - obj2 to work correctly, the overloaded - operator must

  1. take two arguments.
  2. return a value
  3. create a named temporary object.
  4. take four arguments
Show answer

Answer: (b) return a value

Q119. Identify which of the following overloaded operator function's declarations is appropriate for the call Rational_number_1 + 2.325, where Rational_number_1 is an object of the user defined class Rational_number.

  1. Rational_number operator+( Rational_number & obj);
  2. Rational_number operator+(double& obj);
  3. Rational_number operator+(Rational_number &obj, double& num);
  4. operator+(double& obj);
Show answer

Answer: (b) Rational_number operator+(double& obj);
Why: The only option with the right shape is a member function taking a double and returning a Rational_number (const double& would be even better in real code).

Q120. Suppose obj1 and obj2 are two objects of a user defined class A. The + operator is overloaded to add obj1 and obj2 using the call obj1 + obj2. Identify the correct function prototype for the given call.

  1. A operator + ( A &obj);
  2. int + operator();
  3. int operator (plus) ();
  4. A operator(A &obj3);
Show answer

Answer: (a) A operator + ( A &obj);

Q121. To convert from a user-defined class to a basic type, you would most likely use

  1. a built-in conversion operator.
  2. a one-argument constructor.
  3. an overloaded = operator.
  4. a conversion operator that's a member of the class.
Show answer

Answer: (d) a conversion operator that's a member of the class.

Q122. The statement objA = objB; will cause a compiler error if the objects are of different classes.

  1. True
  2. False
Show answer

Answer: (a) True
Why: Only if no conversion or assignment operator between the two classes is provided.

Q123. Overloading a postfix increment operator by means of a member function takes

  1. no argument
  2. one argument
  3. two arguments
  4. three arguments
Show answer

Answer: (b) one argument
Why: The shared key said 'no argument', but the postfix form takes one dummy int argument to tell it apart from the prefix form.

Q124. Which of the following ways is legal to access a class data member x using the this pointer?

  1. this.x
  2. *this.x
  3. *(this.x)
  4. (*this).x
Show answer

Answer: (d) (*this).x

Q125. Overloading the function call operator ( )

  1. requires a class with an overloaded operator.
  2. requires a class with an overloaded [ ] operator.
  3. allows you to create objects that act syntactically like functions.
  4. usually makes use of a constructor that takes arguments.
Show answer

Answer: (c) allows you to create objects that act syntactically like functions.
Why: The shared key said 'requires a class with an overloaded operator', which is circular. Overloading operator() makes objects callable like functions.

Q126. Which of the following operators can be overloaded through a friend function?

  1. ->
  2. =
  3. ( )
  4. *
Show answer

Answer: (d) *
Why: The operators =, ( ), [ ] and -> must be overloaded as member functions.

Q127. Which of the following statements is NOT valid about operator overloading?

  1. Only existing operators can be overloaded.
  2. An overloaded operator must have at least one operand of its class type.
  3. The overloaded operators follow the syntax rules of the original operator.
  4. none of the above.
Show answer

Answer: (d) none of the above.
Why: All three statements are valid, so 'none of the above' is the answer.

Q128. Given a class named Book, which of the following is not a valid constructor?

  1. Book ( ) { }
  2. Book ( Book b) { }
  3. Book ( Book &b) { }
  4. Book (char* author, char* title) { }
Show answer

Answer: (b) Book ( Book b) { }
Why: A copy constructor must take a reference; Book(Book b) would call itself endlessly.

Q129. A copy constructor takes

  1. no argument
  2. one argument
  3. two arguments
  4. arbitrary no. of arguments
Show answer

Answer: (b) one argument

Q130. How many constructors can a class have?

  1. 0
  2. 1
  3. 2
  4. any number
Show answer

Answer: (d) any number
Why: Constructors can be overloaded, as long as their parameter lists differ.

Q131. Which of the following is not a characteristic of a constructor?

  1. They should be declared in the public section.
  2. They do not have return type.
  3. They can not be inherited.
  4. They can be virtual.
Show answer

Answer: (d) They can be virtual.

Q132. The members of a class, by default, are

  1. public
  2. protected
  3. private
  4. mandatory to specify
Show answer

Answer: (c) private

Q133. A property which is not true for classes is that they

  1. are removed from memory when not in use.
  2. permit data to be hidden from other classes.
  3. bring together all aspects of an entity in one place.
  4. Can closely model objects in the real world.
Show answer

Answer: (a) are removed from memory when not in use.
Why: The shared key (bring together all aspects of an entity) is a true property of classes. Classes do not get removed from memory when unused.

Q134. A struct is the same as a class except that

  1. there are no member functions.
  2. all members are public.
  3. cannot be used in inheritance hierarchy.
  4. it does not have a this pointer.
Show answer

Answer: (b) all members are public.
Why: By default all members of a struct are public. The shared key (C) is wrong: structs can be used in inheritance.

Q135. The this pointer

  1. implicitly points to an object.
  2. can be explicitly used in a class.
  3. can be used to return an object.
  4. All of the above.
Show answer

Answer: (d) All of the above.

Q136. A static function

  1. should be called when an object is destroyed.
  2. is closely connected with an individual object of a class.
  3. can be called using the class name and function name.
  4. is used when a dummy object must be created.
Show answer

Answer: (c) can be called using the class name and function name.

Q137. Which one is not a keyword in C++?

  1. operator
  2. B_op
  3. const
  4. None of given
Show answer

Answer: (b) B_op

Q138. In which of the following do different forms of a single entity exist?

  1. Encapsulation
  2. Composition
  3. Polymorphism
  4. Aggregation
Show answer

Answer: (c) Polymorphism
Why: Polymorphism literally means 'many forms'.

Q139. Which of the following is a tangible entity?

  1. Database
  2. Date of birth
  3. Time
  4. Car
Show answer

Answer: (d) Car

Q140. A class defined within another class is:

  1. Encapsulation
  2. Nested Class
  3. Inheritance
  4. Containership
Show answer

Answer: (b) Nested Class

Q141. Member initialization list is used to:

  1. Modify data members
  2. Data members
  3. Initialize data members
  4. De-allocate memory
Show answer

Answer: (c) Initialize data members

Q142. ______ associates the objects of exactly three classes.

  1. N-ary Association
  2. Ternary Association
  3. Two way Association
  4. Binary Association
Show answer

Answer: (b) Ternary Association

Q143. Suppose Person is a class. Which of the following statements defines an object of class Person?

  1. Person person;
  2. Create Person object;
  3. Define Object;
  4. Object Person;
Show answer

Answer: (a) Person person;

Q144. The C++ code "class circle : public shape" shows ______ relationship.

  1. Composition
  2. Simple Association
  3. Aggregation
  4. Inheritance
Show answer

Answer: (d) Inheritance

Q145. In the expression b = c / d, the arity of the division (/) operator is ______.

  1. 4
  2. 2
  3. 3
  4. 1
Show answer

Answer: (b) 2
Why: Arity is the number of operands; / is a binary operator.

Q146. In the expression c1*c2 + c3 - c4, which of the following will be executed first?

  1. c3 - c4
  2. c1*c2
  3. c2 + c3
Show answer

Answer: (b) c1*c2
Why: * has higher precedence than + and -. A fourth option was cut off in the source.

Q147. Choose the correct declaration of the overloaded equality (==) operator for class String as a member function.

  1. bool operator == (const String & s1, const String & s2);
  2. None of the given options
  3. bool operator == (const String & s);
  4. bool operator == ( );
Show answer

Answer: (c) bool operator == (const String & s);
Why: A member operator takes only the right-hand operand; the left one is the calling object.

Q148. Which of the following statements best describes the constructor?

  1. Constructor is used to modify constant data members of the class.
  2. Constructor is used to delete the objects of a class.
  3. All of the given options
  4. Constructor is used to initialize the data members of a class.
Show answer

Answer: (d) Constructor is used to initialize the data members of a class.

Q149. The functions defined inside the class are by default ______.

  1. Static
  2. Constant
  3. Inline
Show answer

Answer: (c) Inline
Why: A fourth option was cut off in the source.

Q150. When an object of a derived class is declared, it has an anonymous object of its base class.

  1. True
  2. False
Show answer

Answer: (a) True
Why: The base class part (sub-object) is created inside every derived class object.

Q151. Which of the following is an integral part of an object?

  1. State
  2. Behavior
  3. Unique identity
  4. All of the given
Show answer

Answer: (d) All of the given
Why: An object is made of state, behaviour and identity.

Q152. Consider the statement "Cupboard has books". What is the relationship between Cupboard and books?

  1. Composition
  2. Aggregation
  3. Inheritance
  4. None of the given options
Show answer

Answer: (b) Aggregation
Why: The books can exist without the cupboard, so it is aggregation (a weak has-a relationship).

Q153. Which sentence clearly defines an object?

  1. one instance of a class.
  2. another word for a class.
  3. a class with static methods.
  4. a method that accesses class attributes.
Show answer

Answer: (a) one instance of a class.

Q154. Consider the call of the overloaded operator "+": Rational_number_1 + Rational_number_2, where both are objects of class Rational_number. Which of the two objects will be passed as an argument to the overloaded operator function?

  1. Rational_number_1
  2. Rational_number_2
  3. Both Rational_number_1 & Rational_number_2
  4. any of the two objects, randomly
Show answer

Answer: (b) Rational_number_2
Why: For a member operator, the left operand is the calling object (it becomes this); only the right operand is passed as the argument.

Q155. How can the information hidden within an object be accessed?

  1. Through its interface
  2. Through its private data members
  3. Through its private member functions
  4. Through both public and private members
Show answer

Answer: (a) Through its interface

Q156. Encapsulation means

  1. Extending the behaviour of class in another class
  2. Data and behaviour are tightly coupled within an entity
  3. One entity takes all the attributes and operations of the other
  4. Taking out the common features and put those in a separate class
Show answer

Answer: (b) Data and behaviour are tightly coupled within an entity

Q157. Which of the following ensures that data and behaviour are tightly coupled within an object?

  1. Inheritance
  2. Abstraction
  3. Polymorphism
  4. Encapsulation
Show answer

Answer: (d) Encapsulation

Q158. Suppose we have two classes derived from a single class. Can we write a method with the same name in both of these derived classes? Choose the best option.

  1. No
  2. Only if the two classes have the same name
  3. Only if the main program does not declare both kinds
  4. Yes
Show answer

Answer: (d) Yes

Q159. The this pointer does not point to the current object of any class.

  1. True
  2. False
Show answer

Answer: (b) False

Q160. Which of the following operators can not be overloaded?

  1. Scope resolution operator ( :: )
  2. Insertion operator ( << )
  3. Extraction operator ( >> )
  4. The relation operator ( > )
Show answer

Answer: (a) Scope resolution operator ( :: )

Q161. Adding a derived class to a base class requires fundamental changes to the base class.

  1. True
  2. False
Show answer

Answer: (b) False

Q162. Consider the code: class c1 { }; class c2 : public c1 { }; class c3 : public c2 { }; Then c2 is

  1. Direct base class of c3
  2. Direct child class of c3
  3. Direct base class of c1
  4. None of these
Show answer

Answer: (a) Direct base class of c3

Q163. A class D can be derived from a class C, which is derived from a class B, which is derived from a class A.

  1. True
  2. False
Show answer

Answer: (a) True

Q164. Function overloading is done with respect to

  1. A single class
  2. A derived class
  3. A base class
  4. Both derived and base classes
Show answer

Answer: (a) A single class

Q165. Which type of inheritance is represented by the statement class X : public A, public B { ... };

  1. Single inheritance
  2. Multiple inheritance
  3. Double inheritance
  4. None of the given options
Show answer

Answer: (b) Multiple inheritance

Q166. The process of building new classes from existing ones is called

  1. Structure
  2. Inheritance
  3. Polymorphism
  4. Template
Show answer

Answer: (b) Inheritance

Q167. The mechanism of deriving a class from another derived class is known as

  1. Polymorphism
  2. Single Inheritance
  3. Multilevel Inheritance
  4. Message Passing
Show answer

Answer: (c) Multilevel Inheritance

Q168. Which of the following is the valid class declaration header for the derived class d with base classes b1 and b2?

  1. class d : public b1, public b2
  2. class d : class b1, class b2
  3. class d : public b1, b2
  4. class d : b1, b2
Show answer

Answer: (a) class d : public b1, public b2

Q169. To access the public function fbase() of the base class, a statement in a derived class function fder() uses the statement

  1. fbase();
  2. fder();
  3. base::fbase();
  4. der::fder();
Show answer

Answer: (a) fbase();

Q170. In inheritance the base class usually represents

  1. Generalization
  2. Specialization
  3. Association
  4. Aggregation
Show answer

Answer: (a) Generalization

Q171. The address of a variable temp of type float is

  1. *temp
  2. &temp
  3. float& temp
  4. float temp&
Show answer

Answer: (b) &temp

Q172. If the variable count exceeds 100, a single statement that prints "Too many" is

  1. if (count<100) cout << "Too many";
  2. if (count>100) cout >> "Too many";
  3. if (count>100) cout << "Too many";
  4. None of these.
Show answer

Answer: (c) if (count>100) cout << "Too many";

Q173. A function call mechanism that passes arguments to a function by passing a copy of the values of the arguments is

  1. call by name
  2. call by value
  3. call by reference
  4. call by value result
Show answer

Answer: (b) call by value

Q174. A variable defined within a block is visible

  1. from the point of definition onward in the program.
  2. from the point of definition onward in the function.
  3. from the point of definition onward in the block.
  4. throughout the function.
Show answer

Answer: (c) from the point of definition onward in the block.

Q175. The break statement causes an exit

  1. from the innermost loop only.
  2. only from the innermost switch.
  3. from all loops & switches.
  4. from the innermost loop or switch.
Show answer

Answer: (d) from the innermost loop or switch.

Q176. Which of the following cannot be legitimately passed to a function?

  1. A constant.
  2. A variable.
  3. A structure.
  4. A header file.
Show answer

Answer: (d) A header file.

Q177. If you wanted to sort many large objects or structures, it would be most efficient to

  1. place them in an array and sort the array.
  2. place pointers to them in an array and sort the array.
  3. place them in a linked list and sort the linked list.
  4. place references to them in an array and sort the array.
Show answer

Answer: (b) place pointers to them in an array and sort the array.
Why: Only the small pointers are swapped, not the large objects. One shared key marked the linked list option.

Q178. Which statement gets affected when i++ is changed to ++i?

  1. i = 20; i++;
  2. for (i = 0; i<20; i++) { }
  3. a = i++;
  4. while (i++ == 20) cout << i;
Show answer

Answer: (c) a = i++;
Why: Only in a = i++ is the value of the expression used, so prefix and postfix give different results. One shared key marked the first option, which is wrong.

Q179. Which of the following is false for cin?

  1. It represents standard input.
  2. It is an object of istream class.
  3. It is a class of which stream is an object.
  4. Using cin the data can be read from user's terminal.
Show answer

Answer: (c) It is a class of which stream is an object.

Q180. Declaration of a pointer reserves memory space

  1. for the object.
  2. for the pointer.
  3. both for the object and the pointer.
  4. none of these.
Show answer

Answer: (b) for the pointer.

Q181. Identify the operator that is NOT used with pointers

  1. ->
  2. &
  3. *
  4. >>
Show answer

Answer: (d) >>

Q182. Consider the statements: char *ptr; ptr = "hello"; cout << *ptr; What will be printed?

  1. first letter
  2. entire string
  3. it is a syntax error
  4. last letter
Show answer

Answer: (a) first letter

Q183. The new operator

  1. returns a pointer to the variable
  2. creates a variable called new
  3. obtains memory for a new variable
  4. tells how much memory is available
Show answer

Answer: (c) obtains memory for a new variable

Q184. Consider the statements: int x = 22, y = 15; x = (x>y) ? (x+y) : (x-y); What will be the value of x after executing these statements?

  1. 22
  2. 37
  3. 7
  4. Error. Cannot be executed
Show answer

Answer: (b) 37

Q185. An array element is accessed using

  1. a FIFO approach
  2. an index number
  3. the operator
  4. a member name
Show answer

Answer: (b) an index number

Q186. We can output text to an object of class ostream using the insertion operator << because

  1. the ostream class is a stream
  2. the insertion operator works with all classes.
  3. we are actually outputting to cout.
  4. the insertion operator is overloaded in ostream.
Show answer

Answer: (d) the insertion operator is overloaded in ostream.

Q187. Name the header file to be included for the use of the built-in function isalnum()

  1. string.h
  2. process.h
  3. ctype.h
  4. dos.h
Show answer

Answer: (c) ctype.h

Q188. What is the output of the code fragment? int f=1, i=2; while(++i<5) f*=i; cout<<f;

  1. 12
  2. 24
  3. 6
  4. 3
Show answer

Answer: (a) 12
Why: i becomes 3 (f = 3), then 4 (f = 12), then 5 stops the loop.

Q189. What will be the values of x, m and n after the execution of the following statements? int x, m, n; m = 10; n = 15; x = ++m + n++;

  1. x=25, m=10, n=15
  2. x=26, m=11, n=16
  3. x=27, m=11, n=16
  4. x=27, m=10, n=15
Show answer

Answer: (b) x=26, m=11, n=16
Why: ++m makes m = 11 and gives 11; n++ gives 15 and then makes n = 16; x = 11 + 15 = 26.

Q190. Which of the following will produce a value 10 if x = 9.7?

  1. floor(x)
  2. abs(x)
  3. log(x)
  4. ceil(x)
Show answer

Answer: (d) ceil(x)

Q191. What would be the output of the following program? int main() { int x, y=10, z=10; x = (y == z); cout << x; return 0; }

  1. 1
  2. 0
  3. 10
  4. Error
Show answer

Answer: (a) 1

Q192. A white space is:

  1. blank space
  2. new line
  3. tab
  4. all of the above
Show answer

Answer: (d) all of the above

Q193. What will be the result of the expression 13 & 25?

  1. 38
  2. 25
  3. 9
  4. 12
Show answer

Answer: (c) 9
Why: 01101 & 11001 = 01001 = 9.

Q194. What will be the output of the following program? void main() { float x=5, y=2; int result; result = x % y; cout << result; }

  1. 1
  2. 0
  3. Error message
  4. 5
Show answer

Answer: (c) Error message
Why: The % operator cannot be applied to floating point operands, so the compiler reports an error.

Q195. Member functions, when defined within the class specification

  1. are always inline.
  2. are not inline.
  3. are inline by default, unless they are too big or too complicated.
  4. are not inline by default.
Show answer

Answer: (c) are inline by default, unless they are too big or too complicated.
Why: One shared key marked 'always inline'; inline is only a request that the compiler may ignore for big or complex functions.

Q196. In C++, the compiler can generate code for which of the following operators?

  1. ==
  2. =
  3. &
  4. &&
Show answer

Answer: (b) =
Why: The compiler supplies a default assignment operator (=) if the class does not define one.

Q197. Member functions under the ______ access specifier are also called the interface to the class.

  1. Private
  2. Protected
  3. Public
  4. Inline
Show answer

Answer: (c) Public

Q198. In a member initialization list, more than one member should be separated by ______.

  1. Commas
  2. Parenthesis
  3. Curly braces
  4. Quotes
Show answer

Answer: (a) Commas

Q199. Constant member functions are just ______ and ______ change the object state.

  1. Read only, can
  2. Read only, can not
  3. Write only, can
  4. Write only, can not
Show answer

Answer: (b) Read only, can not

Q200. C2 + C1 is equivalent to ______ when the plus operator is overloaded as a member function and C2, C1 are objects.

  1. C1 operator + (C2)
  2. C1.operator + (C1)
  3. C2.operator + (C1)
  4. C2.operator + (C2)
Show answer

Answer: (c) C2.operator + (C1)

Q201. While overloading the stream insertion operator, the return type must be ______.

  1. ostream (by reference)
  2. istream
  3. instream
  4. tostream
Show answer

Answer: (a) ostream (by reference)
Why: It returns ostream & so that calls can be chained: cout << a << b;

Q202. While overloading the stream extraction operator, the return type must be ______.

  1. ostream
  2. tostream
  3. istream (by reference)
  4. instream
Show answer

Answer: (c) istream (by reference)

Q203. The subscript operator must be a ______ of the class when overloaded.

  1. Static function
  2. Virtual function
  3. Member function
  4. Non member function
Show answer

Answer: (c) Member function

Q204. To overload the subscript operator, it requires one ______ type parameter.

  1. Int
  2. Float
  3. Char
  4. String
Show answer

Answer: (a) Int

Q205. When a constructor is defined as constant (const), then

  1. It can not change the state of an object
  2. It can not initialize the state of an object
  3. It only sets the state of the object
  4. Compile time error will occur
Show answer

Answer: (d) Compile time error will occur
Why: Constructors cannot be declared const.

Q206. The state of a "bank account" includes:

  1. Account number, Current balance
  2. Account number, Cash withdraw
  3. Current balance, Cash deposit
  4. Current balance, Cash withdraw
Show answer

Answer: (a) Account number, Current balance
Why: State is data (account number, balance); deposit and withdraw are behaviour.

Q207. Which one is not an example of a model?

  1. Highway Map
  2. Computer
  3. Circuit Drawing
  4. Engineering Drawing
Show answer

Answer: (b) Computer

Q208. How many parameter(s) can be taken by a destructor?

  1. One more than constructor
  2. One less than constructor
  3. No parameters
  4. One parameter
Show answer

Answer: (c) No parameters

Q209. Why should we avoid the use of friend functions/classes?

  1. Friend function/class minimizes encapsulation
  2. Difficult to use
  3. Decreases complexity
  4. Increase program code size
Show answer

Answer: (a) Friend function/class minimizes encapsulation

Q210. The property of an object which distinguishes it from other objects is called

  1. Messages
  2. Identity
  3. Interface
  4. Behavior
Show answer

Answer: (b) Identity

Q211. Which of the following is NOT an advantage of information hiding?

  1. Simplifies the model
  2. Restriction to change
  3. Prevents damage from errant external code
  4. Provide direct access to data members
Show answer

Answer: (d) Provide direct access to data members

Q212. Assume that a user wants to count how many objects are created for a particular class. Which one will be most suitable to perform this task?

  1. Const data member
  2. Non static data member
  3. Static data member
  4. Global data member
Show answer

Answer: (c) Static data member

Q213. Objects communicate with each other through ______.

  1. Messages
  2. Data Members
  3. Member Functions
  4. Pointers
Show answer

Answer: (a) Messages

Q214. Which one is the correct way to initialize static variables?

  1. Student int:noOfStudent = 0;
  2. Student:noOf Student = 0;
  3. int Student::noOfStudents = 0;
  4. int Student:noOfStudent(0)=0
Show answer

Answer: (c) int Student::noOfStudents = 0;
Why: A static data member is defined once outside the class, using the scope resolution operator.

Q215. Which of the following is a necessary ingredient in an object model?

  1. Class
  2. Objects
  3. Association
  4. All of given
Show answer

Answer: (d) All of given
Why: An object model is made of classes, objects and the associations between them. The sources did not mark a key, so this is taken from the lecture description of an object model.

Q216. The process of hiding unwanted details from users is called ______.

  1. Protection
  2. Encapsulation
  3. Argumentation
  4. Abstraction
Show answer

Answer: (b) Encapsulation
Why: This is the key given with the handout page reference (page 16, encapsulation). Many textbooks call 'hiding unwanted details' abstraction, so confirm it from your handout.

Q217. Through the interface we access object ______.

  1. States
  2. Data members
  3. Behaviour
  4. None of the given
Show answer

Answer: (c) Behaviour
Why: An interface is the set of functions an object exposes, i.e. its behaviour. No source marked a key for this one.

Q218. ______ is creating objects of one class inside another class.

  1. Association
  2. Composition
  3. Aggregation
  4. Inheritance
Show answer

Answer: (b) Composition
Why: No source marked a key; composition is the 'whole creates its parts' relationship in the lecture.

Q219. "A fan has wings." Which type of relation exists between fan and wings?

  1. Aggregation
  2. Association
  3. Generalization
  4. Composition
Show answer

Answer: (d) Composition
Why: The wings (blades) are parts of the fan and do not exist independently, so it is composition. No source marked a key.

Q220. The sentence "Object Oriented Programming book in bookshelf" is an example of:

  1. Association
  2. Multiple association
  3. Aggregation
Show answer

Answer: (c) Aggregation
Why: The shelf holds a collection of books that can exist without it, so it is aggregation. No source marked a key.

Q221. A generic class showing all the common attributes and behavior of other classes represents a very important feature in OOP called ______.

  1. Inheritance
  2. Encapsulation
  3. Polymorphism
  4. Abstraction
Show answer

Answer: (a) Inheritance
Why: Answer as per the handout key (page 26).

Q222. ______ satisfy the condition of polymorphism.

  1. Carbon
  2. Diamond
  3. Coal
  4. all of the given
Show answer

Answer: (d) all of the given
Why: Taken from the handout's carbon example (one thing, many forms); all sources agree.

Q223. Memory is allocated to non-static members only when:

  1. Class is created
  2. Object is defined
  3. Object is initialized
  4. Object is created
Show answer

Answer: (d) Object is created
Why: Memory for non-static data members is allocated when an object is created, not when the class is defined. 'Object is defined' is also close, so treat this one as a judgment call.

Q224. We can use the this pointer in the constructor body and even in the initialization list of any class if we are careful.

  1. True
  2. False
Show answer

Answer: (b) False
Why: All shared files give False; technically the pointer can be used in the constructor body, so confirm the wording from your handout.

Q225. Which of the following statements is true?

  1. We can create new C++ operators.
  2. We can change the precedence of the C++ operators.
  3. We can change the associativity of the C++ operators.
  4. We can not change operator templates.
Show answer

Answer: (d) We can not change operator templates.
Why: Only existing operators can be overloaded and their precedence and associativity cannot be changed, so the first three statements are false.

Q226. Which of the following is an advantage of encapsulation?

  1. Reuse of the code
  2. Complexity
  3. Better understanding
  4. Efficient code
Show answer

Answer: (c) Better understanding
Why: Taken from the marked Grand Quiz Spring 2021 screenshot; no handout reference was available to confirm it.

Q227. Which of the following issue(s) can be caused by the use of friend functions?

  1. All of the given
  2. Tough debugging
  3. Programming bugs
  4. Data vulnerability
Show answer

Answer: (a) All of the given
Why: Taken from the marked Grand Quiz Spring 2021 screenshot. Friends bypass encapsulation, which can expose data and make bugs harder to trace.

Q228. There are ______ types of constructors in C++.

  1. 4
  2. 5
  3. 3
  4. 2
Show answer

Answer: (c) 3
Why: Default, parameterized and copy constructors. Taken from the marked Grand Quiz screenshot.

Q229. Data members which are static

  1. cannot be assigned a value
  2. can only be used in static functions
  3. cannot be defined in a Union
  4. can be accessed outside the class
Show answer

Answer: (d) can be accessed outside the class
Why: A public static member can be reached from outside with ClassName::member. One shared key said 'only in static functions', which is wrong (non-static functions may use them as well).

Q230. Sender of the message does not need to know the exact class of the receiver in ______.

  1. Abstraction
  2. Polymorphism
  3. Inheritance
  4. none of the given
Show answer

Answer: (b) Polymorphism
Why: Taken from a student-recalled paper; no handout reference was available to confirm it.

Q231. Separation of implementation from interface provides the facility to restrict the ______ from direct access.

  1. Data member
  2. Data function
  3. Class
  4. Object
Show answer

Answer: (a) Data member
Why: Based on a student-recalled paper.

Q232. In ______, a base class can be replaced by its derived class.

  1. Sub-typing
  2. Super-typing
  3. Multiple-typing
  4. Restricted-typing
Show answer

Answer: (a) Sub-typing
Why: Sub-typing means the derived class is behaviourally compatible with the base class. No handout reference was available.

Part 2: Subjective Questions

Q1. What is a class? How is it different from an object? (2 marks)

A class is a user defined data type that describes the attributes (data members) and behaviours (member functions) shared by a group of similar things. An object is a real instance of a class that occupies memory and holds its own values.

  • A class is a blueprint; an object is the thing built from it.
  • A class is defined once; many objects can be created from it.
  • Memory for data members is allocated only when an object is created.

Q2. Define abstraction and give an example. (2 marks)

Abstraction means focusing on the essential, relevant details of an entity and ignoring the rest. Example: for an employee record a company stores name, age and experience, but not hobbies or relatives, because those are irrelevant to the job.

Q3. What is encapsulation? How does it support information hiding? (3 marks)

Encapsulation binds data and the functions that work on it into a single unit (a class). Data is kept private and is reached only through public member functions (the interface), so the internal implementation can change without affecting the users of the class.

Q4. Differentiate between abstraction and encapsulation. (3 marks)

  • Abstraction decides what to show (the relevant view of an object); encapsulation decides how to package and protect it.
  • Abstraction works at the design level; encapsulation is achieved through classes and access specifiers.
  • Abstraction gives independence of the interface from the implementation; encapsulation gives information hiding.

Q5. What are the three types of object associations? Give an example of each. (3 marks)

  • Simple association: objects use each other, e.g. a teacher and a student.
  • Aggregation (weak 'has-a'): the part can live without the whole, e.g. a room has chairs.
  • Composition (strong 'has-a'): the part's life depends on the whole, e.g. a fan has blades; a house has rooms.

Q6. Differentiate between aggregation and composition. (3 marks)

  • Aggregation is a weak relationship; composition is a strong one.
  • In aggregation the sub-object can exist without the master object; in composition it is created and destroyed with it.
  • Aggregation example: a room and its chairs. Composition example: a fan and its blades.

Q7. What is inheritance? What are its advantages? (3 marks)

Inheritance is a mechanism by which a derived (child) class acquires the attributes and behaviours of a base (parent) class. It models an 'is-a' relationship.

  • Reuse of existing code without rewriting it.
  • A class can be extended with new members.
  • Natural hierarchical classification and easier maintenance.

Q8. Differentiate between generalization and specialization. (2 marks)

  • Generalization extracts the common attributes and behaviour of several classes into a new base class (bottom-up).
  • Specialization derives a new class from an existing one by adding or changing features (top-down).

Q9. What is multiple inheritance? Give an example. (2 marks)

It is the ability of a class to derive from more than one base class. Example: an amphibious vehicle inherits from both Car and Boat; a mermaid inherits from Woman and Fish.

Q10. What is a constructor? Write its main properties. (3 marks)

  • It has the same name as the class.
  • It has no return type (not even void).
  • It is called automatically when an object is created.
  • It can be overloaded and can take default arguments.
  • It cannot be declared const, and it is normally public.

Q11. What is a destructor? Write its properties. (3 marks)

  • Its name is the class name preceded by a tilde (~).
  • It has no return type and takes no parameters, so it cannot be overloaded.
  • It is called automatically when an object goes out of scope or is deleted.
  • It releases resources (e.g. dynamic memory) held by the object.

Q12. What is a default constructor? (2 marks)

A constructor that can be called without any arguments: either it has no parameters, or all of its parameters have default values. If a class defines no constructor, the compiler supplies one.

Q13. What is a copy constructor? When is it called? (3 marks)

A copy constructor creates a new object as a copy of an existing object of the same class. Its parameter must be a reference: ClassName(const ClassName &obj).

  • When an object is initialized from another: Student s2(s1); or Student s2 = s1;
  • When an object is passed to a function by value.
  • When an object is returned by value.

Q14. Differentiate between shallow copy and deep copy. (3 marks)

  • Shallow copy (default) copies member values bit by bit, so pointers in two objects point to the same memory.
  • Deep copy allocates new memory for the pointer member and copies the contents into it, so each object owns its own data.
  • Shallow copy of dynamic memory causes dangling pointers and double deletion; a user defined copy constructor is needed for deep copy.

Q15. Write a class with a deep copy constructor. (4 marks)

class Student {
    char *name;
public:
    Student(const char *n) {
        name = new char[strlen(n) + 1];
        strcpy(name, n);
    }
    Student(const Student &s) {          // deep copy
        name = new char[strlen(s.name) + 1];
        strcpy(name, s.name);
    }
    ~Student() { delete[] name; }
};

Q16. What is the this pointer? Where is it not available? (3 marks)

this is a hidden pointer, passed implicitly to every non-static member function, that holds the address of the object that called the function. It is used to access members whose names clash with parameters and to return the calling object (return *this;).

It is not available in static member functions, because they are not tied to any particular object. In a const member function its type is const X * const.

Q17. What are static data members and static member functions? (3 marks)

  • A static data member is one shared copy for all objects of the class; it is created once and remains in memory even when no object exists. It is defined (initialized) once outside the class.
  • A static member function can be called with the class name (Class::f()) without any object, has no this pointer and can access only static members directly.

Q18. Write a class with a static counter that counts the objects created. (4 marks)

class Counter {
    static int count;
public:
    Counter() { count++; }
    ~Counter() { count--; }
    static int getCount() { return count; }
};
int Counter::count = 0;

Calling Counter::getCount() returns the number of live objects.

Q19. What is a friend function? Write its characteristics. (3 marks)

  • A non-member function that is granted access to the private and protected members of a class by declaring it with the friend keyword inside the class.
  • It is not a member, so it has no this pointer and is called like a normal function.
  • Friendship is granted, not taken: if A declares B a friend, B can access A's private data but not the reverse. It is not inherited.

Q20. What is a constant object and a constant member function? (3 marks)

  • A constant object (const Student s;) cannot change its state after initialization.
  • A const member function (int get() const;) promises not to modify the data members, and it is the only kind of member function a const object can call.

Q21. What is operator overloading? Which operators cannot be overloaded? (3 marks)

Operator overloading gives an existing C++ operator a new meaning for user defined types, using a function named operator followed by the symbol. Precedence, associativity and the number of operands cannot be changed, and new operators cannot be created.

Operators that cannot be overloaded: :: (scope resolution), . (member access), .*, ?:, sizeof and typeid.

Q22. Overload the + operator for a Complex class. (4 marks)

class Complex {
    int re, im;
public:
    Complex(int r = 0, int i = 0) : re(r), im(i) {}
    Complex operator+(const Complex &c) const {
        return Complex(re + c.re, im + c.im);
    }
};

c3 = c1 + c2; calls c1.operator+(c2).

Q23. How are the prefix and postfix ++ operators overloaded? (3 marks)

Counter& operator++()    { ++value; return *this; }       // prefix
Counter  operator++(int) { Counter t(*this); ++value; return t; } // postfix

The postfix version takes a dummy int argument only to distinguish it from the prefix version.

Q24. What is a conversion operator? Write its syntax. (3 marks)

A member function that converts an object of a user defined class to another type (a basic type or another class). It has no return type in its declaration and no parameters:

operator int() const { return value; }

Q25. What is the member initialization list? Why is it used? (3 marks)

It is a list written after the constructor's parameter list (Box(int w, int h) : width(w), height(h) {}) that initializes members before the constructor body runs.

  • It is the only way to initialize const members, reference members and sub-objects without a default constructor.
  • Members are initialized in the order they are declared in the class, not the order in the list.
  • In ABC() : x(10), z(x), y(x) with declaration order x, y, z, all three members get 10.

Q26. What happens when objects are created with new and with an array? (3 marks)

  • Fred a[10]; and new Fred[10] each call the default constructor once for every element, so 10 times.
  • Objects created with new must be released with delete (delete[] for arrays), which calls the destructor.
  • An array of objects can only be created if the class has a default constructor, because no arguments can be passed for the elements.

Q27. Differentiate between simple association and aggregation. (3 marks)

  • Simple association: two independent objects merely use each other (teacher and student); neither is a part of the other.
  • Aggregation: a 'has-a' (whole-part) relationship in which the whole holds its parts as a collection, but the parts can exist on their own (a room and its chairs).

Q28. Friend functions minimize encapsulation. Explain in your own words. (3 marks)

Encapsulation keeps private data reachable only through the class's own member functions. A friend function is outside the class yet can read and change private and protected members directly, so the data is no longer protected by the class alone. Using too many friends makes the code harder to maintain and debug, so friends should be used sparingly (for example for operators such as <<).

Q29. Write a class with a constant member function. (3 marks)

class Circle {
    double radius;
public:
    Circle(double r) : radius(r) {}
    double area() const {          // const: cannot modify data members
        return 3.14159 * radius * radius;
    }
};

A const member function can be called on constant objects and cannot change any data member.

Q30. What type of copy does the default assignment operator (=) perform when applied to objects? (2 marks)

It performs a shallow (memberwise) copy: every data member is copied as it is. If a class uses dynamic memory, both objects end up pointing to the same memory, so an overloaded assignment operator with a deep copy is needed.

Q31. Can we use the compiler generated default assignment operator when our class uses dynamic memory? Justify. (3 marks)

No. The default operator only copies pointer values, so two objects share one block of memory. When one object is destroyed the other is left with a dangling pointer, and deleting the same memory twice may crash the program. The old memory of the left-hand object is also leaked. We must overload = to free the old memory, allocate new memory and copy the contents (deep copy).

Q32. Give a one line definition of object orientation. (1 marks)

Object orientation is a programming approach in which a problem is modelled as a set of objects that combine data and operations, and which can be related to and inherit from one another.

Q33. What is the difference between object-based and object-oriented programming? (3 marks)

  • Object-based languages support objects and abstract data types but not inheritance or polymorphism (e.g. early Ada, Modula-2).
  • Object-oriented languages support classes, inheritance and polymorphism as well (C++, Java).

Q34. Model a furniture store (chairs, tables, computer tables, dining tables, beds) using inheritance and show the is-a relationship in C++. (5 marks)

Base class Furniture holds the common members (price, material, colour). Chair, Table and Bed derive from Furniture; ComputerTable and DiningTable derive from Table. Each derived class is-a kind of its parent: a DiningTable is-a Table and a Table is-a Furniture.

class Furniture { protected: float price; };
class Chair : public Furniture { };
class Table : public Furniture { };
class Bed   : public Furniture { };
class ComputerTable : public Table { };
class DiningTable   : public Table { };

Q35. What is a null pointer? What is the difference between global and local variables? (3 marks)

  • A null pointer is a pointer that points to nothing; it is set to 0 (NULL) and tested against 0 before use.
  • A global variable is declared outside all functions and can be used throughout the program (global scope).
  • A local variable is declared inside a function or block and can only be used there (local scope).

Q36. What is meant by a direct base class? (1 marks)

The class named directly in the base-class list of a derived class. In class B : public A, A is the direct base class of B; if C derives from B, then A is an indirect base of C.

Q37. Why is the use of friend functions discouraged in C++? (2 marks)

A friend function is allowed to touch the private and protected members of a class, so it breaks encapsulation and data hiding. If many friends depend on the internal data, a change in the class forces changes in all of them, and bugs become harder to trace. Friends should therefore be used only where really needed, for example for operators such as << or + with a non-class left operand.

Q38. Can we overload the default constructor? Justify your answer. (2 marks)

A class can have only one default constructor (one that can be called with no arguments), so it cannot be overloaded with another no-argument version. The class can, however, have any number of other constructors with different parameter lists (parameterized and copy constructors), and that is what constructor overloading means.

Care is needed with default arguments: A(); together with A(int x = 0); makes the call A a; ambiguous and causes a compile error.

Q39. Can we create an array of objects of a class that has a user defined constructor? Justify your answer. (3 marks)

Yes, but only if the class also has a default constructor. When an array such as Student s[5]; is declared, no arguments can be passed to the elements, so the compiler calls the default constructor for each one. If the class defines only a constructor with parameters, the compiler does not generate a default constructor and the declaration fails.

class Employee {
    int id;
public:
    Employee(int _id) { id = _id; }
};
Employee e[2];   // error: no default constructor

Q40. Find the error in the following code, explain its cause and write the corrected code. (3 marks)

class Employee {
    int id;
public:
    Employee(int _id) { id = _id; }
};
int main() {
    Employee E[2];
}

Error: Employee E[2]; needs a default constructor for each element, but because the class defines its own constructor the compiler does not supply one.

Correction: add a default constructor (or give the parameter a default value).

class Employee {
    int id;
public:
    Employee(int _id = 0) { id = _id; }   // also works as default constructor
};
int main() {
    Employee E[2];                         // OK
}

Q41. How does the compiler know whether an overloaded ++ is the prefix or the postfix version? Differentiate between the two. (2 marks)

  • The postfix version has an extra dummy int parameter, which is used only to distinguish it from the prefix version: operator++() is prefix, operator++(int) is postfix.
  • Prefix (++x) increments first and returns the updated object, normally by reference.
  • Postfix (x++) returns the old value, so it saves a copy of the object, increments, and returns the copy by value.

Q42. Classify each of the operators %, &, && and sizeof as unary or binary. (2 marks)

  • % (modulus): binary.
  • && (logical AND): binary.
  • sizeof: unary.
  • &: both. It is unary as the address-of operator (&x) and binary as bitwise AND (a & b).

Note: one student recollection of this paper lists % and & as unary, which is wrong.

Q43. Write two advantages of declaring a member function as const. Also show the syntax. (2 marks)

  • It documents and guarantees that the function does not change the object, and the compiler reports an error if it tries to.
  • It can be called on constant objects (and through const references), which are otherwise unable to call any member function that is not const.
returnType functionName(parameters) const;     // e.g. int getAge() const;

Q44. Consider the statement Crs1 - Crs2 - Crs3, where the - operator is overloaded and Crs1, Crs2, Crs3 are objects of class Course. How does the compiler convert this statement into function calls? (3 marks)

The - operator is left associative, so Crs1 - Crs2 is evaluated first and its result is then used as the left operand with Crs3.

// operator overloaded as a member function
(Crs1.operator-(Crs2)).operator-(Crs3);

// operator overloaded as a non-member (friend) function
operator-(operator-(Crs1, Crs2), Crs3);

For this to work the function must return a Course object.

Q45. Class Course holds a char *bufferPtr and an int size. Implement SetCourse(char c, int pos), which changes a single character at the given position of the string pointed to by bufferPtr. (3 marks)

void Course::SetCourse(char c, int pos) {
    if (bufferPtr != 0 && pos >= 0 && pos < size)   // check the bounds first
        bufferPtr[pos] = c;
}

Q46. What are the values of x, y and z after an object of this class is created? (2 marks)

class ABC {
    int x;
    int y;
    int z;
public:
    ABC();
};
ABC::ABC() : x(10), z(y), y(x) { }

Members are initialized in the order in which they are declared (x, y, z), not in the order of the initialization list. So x = 10, then y = x = 10, then z = y = 10. All three become 10.

Q47. Write C++ code to overload the subscript operator [] for a String class. (3 marks)

class String {
    int size;
    char *bufferPtr;
public:
    char& operator[](int index) {
        return bufferPtr[index];          // returns a reference so s[i] = 'a' works
    }
};

It must return a reference so the operator can be used on the left side of an assignment as well. A bounds check on index can be added for safety.

Q48. Overload the subtraction operator for the Complex class so that a double value can be subtracted from a Complex object and a Complex object from a double value: Complex c1; Complex c2 = 1.546 - c1; Complex c3 = c1 - 2.456; (5 marks)

class Complex {
    double real, img;
public:
    Complex(double r = 0, double i = 0) : real(r), img(i) {}
    Complex operator-(double d) const {                    // c1 - 2.456
        return Complex(real - d, img);
    }
    friend Complex operator-(double d, const Complex &c);  // 1.546 - c1
};
Complex operator-(double d, const Complex &c) {
    return Complex(d - c.real, -c.img);
}

The second form has a double on the left, so it cannot be a member function and is written as a friend (non-member) function.

Q49. Write C++ code to overload the assignment operator for a String class that holds dynamic memory. How can the chained statement s1 = s2 = s3 = s4 be supported? (5 marks)

class String {
    int size;
    char *bufferPtr;
public:
    String& operator=(const String &rhs) {
        if (this != &rhs) {                    // protect against s = s
            delete[] bufferPtr;                // free old memory
            size = rhs.size;
            bufferPtr = new char[size + 1];    // allocate new memory
            strcpy(bufferPtr, rhs.bufferPtr);  // deep copy
        }
        return *this;                          // allows chaining
    }
};

The operator is right associative, so s1 = (s2 = (s3 = s4)) is evaluated from the right. Each call must return the object it assigned to (by reference), so the result of one assignment can be the right side of the next. Returning void would break the chain. Checking for self-assignment and doing a deep copy avoids dangling pointers and memory leaks.

Q50. Write C++ code to overload the assignment operator for a Complex class. (3 marks)

class Complex {
    double real, img;
public:
    Complex& operator=(const Complex &c) {
        real = c.real;
        img  = c.img;
        return *this;
    }
};

Q51. Write C++ code to overload the insertion operator (<<) for a user defined class so that the whole program compiles. (3 marks)

#include <iostream>
using namespace std;

class Complex {
    double real, img;
public:
    Complex(double r = 0, double i = 0) : real(r), img(i) {}
    friend ostream& operator<<(ostream &out, const Complex &c);
};

ostream& operator<<(ostream &out, const Complex &c) {
    out << c.real << " + " << c.img << "i";
    return out;                               // allows cout << a << b;
}

int main() {
    Complex c(2, 3);
    cout << c << endl;
}

The left operand is cout (an ostream), not our class, so the operator cannot be a member of the class. It is written as a non-member friend function and returns the stream by reference.

Q52. Why can a static member function access static data members? Explain. (3 marks)

A static data member belongs to the class itself and exists once, whether or not any object has been created. A static member function is also called on the class (Class::f()) and has no this pointer, so it cannot reach the data members of a particular object. It can reach static data members because they do not need an object: there is only one shared copy.

Q53. A university course contains lectures, assignments, quizzes and graded discussion boards (GDB/MDB). Which type of association exists between the course and these parts? Model the scenario in C++ showing both composition and simple association. (5 marks)

The lectures, assignments and quizzes are parts of a course and have no meaning without it, so the relationship is composition (a strong 'has-a'). A student and a course are independent objects that merely use each other (enrolment), so that is a simple association.

class Lecture    { /* ... */ };
class Assignment { /* ... */ };
class Quiz       { /* ... */ };

class Course {
    Lecture    lectures[45];        // composition: parts created and destroyed with the Course
    Assignment assignments[6];
    Quiz       quizzes[1];
public:
    // ...
};

class Student {
    Course *enrolled;               // simple association: Student only uses a Course
public:
    void enrol(Course *c) { enrolled = c; }
};

Q54. Explain how a conversion between types (for example from a class to a basic type, or between two classes) can be achieved in C++. Give an example. (5 marks)

  • A constructor with one argument converts a basic type or another class into the class being constructed.
  • A conversion operator (a member function without return type) converts the object into another type.
class Distance {
    int meters;
public:
    Distance(int m) : meters(m) {}          // int -> Distance
    operator int() const { return meters; } // Distance -> int
};

int main() {
    Distance d = 25;      // calls Distance(int)
    int m = d;            // calls operator int()
}

Q55. Give two uses of a destructor. (2 marks)

  • To release the resources the object acquired during its life, such as dynamic memory (delete), open files or network connections, so there is no memory leak.
  • To carry out any final clean-up work when the object goes out of scope or is deleted, for example updating a counter of live objects or writing a final message to a log.

Q56. Explain two benefits of constructors. (2 marks)

  • They guarantee that every object starts in a well defined state, because they are called automatically when the object is created.
  • They can be overloaded, so objects can be created with different initial values (default, parameterized, copy), and they can validate the initial values.

Q57. Explain two benefits of setter functions. (2 marks)

  • They protect data members: the data stays private and can be changed only through the setter, so objects are not left in an inconsistent state.
  • They allow validation: the setter can check the value (for example that age is not negative) before storing it, and the internal representation can change without affecting users of the class.

Q58. What are accessor functions? Explain with an example. (2 marks)

Accessor (getter) functions are public member functions that give controlled, read access to the private data members of a class. Usually they are declared const.

class Student {
    int rollNo;
public:
    int getRollNo() const { return rollNo; }   // accessor
};

Q59. What is simple association? Explain it with the help of an example. (2 marks)

Simple association is the weakest relationship between objects: two independent objects know about each other and use each other's services, but neither owns the other and each can exist on its own. Example: a teacher and a student. The teacher object sends messages to the student object (for example to ask a question), but if one is destroyed the other is unaffected.

Q60. What is composition? Explain it with the help of an example. (2 marks)

Composition is a strong 'has-a' relationship in which one object is made of other objects, and the parts cannot exist without the whole: they are created with it and destroyed with it. Example: a house has rooms. If the house is destroyed, its rooms are destroyed too.

class Room { };
class House {
    Room r1, r2;      // sub-objects live and die with the House
};

Q61. What is the difference between simple association and composition? (3 marks)

  • Simple association: independent objects that only use each other. Composition: the whole contains its parts as sub-objects.
  • In simple association the lifetimes are unrelated; in composition the part's lifetime depends on the whole.
  • Example of association: teacher and student. Example of composition: house and rooms.

Q62. Explain the difference between a static variable of a class and a non-static variable, with an example. (3 marks)

  • A non-static data member has a separate copy in every object. A static data member has only one copy shared by all objects of the class.
  • Memory for non-static members is allocated when an object is created; a static member exists even before any object is created and remains until the program ends.
  • A static member is defined (initialized) once outside the class and can be reached with the class name.
class Student {
    int rollNo;              // one per object
    static int count;        // one for the whole class
public:
    Student() { count++; }
    static int getCount() { return count; }
};
int Student::count = 0;

Q63. What do you mean by static class members? Write their characteristics. (5 marks)

  • A static data member is shared by all objects of the class; there is only one copy of it.
  • It is initialized only once, outside the class definition, and takes the value 0 by default if it is not initialized.
  • It exists in memory even when no object of the class exists.
  • A static member function can be called without an object (Class::f()), has no this pointer and can access only static members directly.
  • A static member function cannot be virtual or const.
class Counter {
    static int n;
public:
    Counter()  { n++; }
    ~Counter() { n--; }
    static int live() { return n; }
};
int Counter::n = 0;

Q64. Write C++ code to overload the unary decrement operator (--) for a Complex class. (3 marks)

class Complex {
    double real, img;
public:
    Complex(double r = 0, double i = 0) : real(r), img(i) {}
    Complex& operator--() {            // prefix --c
        --real;
        --img;
        return *this;
    }
    Complex operator--(int) {          // postfix c--
        Complex old(*this);
        --real;
        --img;
        return old;
    }
};

Here the operator decrements both parts of the complex number. The version with a dummy int is the postfix form.

Q65. Write a program to overload the unary minus operator using a friend function. (4 marks)

class Complex {
    double real, img;
public:
    Complex(double r = 0, double i = 0) : real(r), img(i) {}
    friend Complex operator-(const Complex &c);   // unary minus
};
Complex operator-(const Complex &c) {
    return Complex(-c.real, -c.img);
}
// c2 = -c1;   calls operator-(c1)

Q66. Overload the stream extraction operator (>>) for a Complex class so that an object can be read with cin. (3 marks)

class Complex {
    double real, img;
public:
    friend istream& operator>>(istream &in, Complex &c);
    friend ostream& operator<<(ostream &out, const Complex &c);
};
istream& operator>>(istream &in, Complex &c) {
    in >> c.real >> c.img;      // the object is not const: it is being changed
    return in;                  // returned by reference so cin >> a >> b works
}
ostream& operator<<(ostream &out, const Complex &c) {
    out << c.real << " + " << c.img << "i";
    return out;
}

Both operators must be non-member (friend) functions because the left operand is the stream (cin or cout), not an object of our class.

Q67. What type is the this pointer inside a member function of class XYZ? In which situations is the copy constructor of a class called? (5 marks)

(a) In an ordinary member function of class XYZ, this has the type XYZ * const (a constant pointer to XYZ: the pointer cannot be changed, but the object it points to can). In a const member function it is const XYZ * const.

(b) The copy constructor is called:

  • when a new object is initialized from an existing object of the same class, e.g. XYZ b(a); or XYZ b = a;
  • when an object is passed to a function by value,
  • when an object is returned from a function by value (a compiler may skip this copy).

Note: a shared answer sheet wrote the type as 'XYZ *this' and listed 'assigning private data members' and 'allocating memory dynamically' as copy constructor situations; these are wrong.

Q68. class Complex { double x, y; static int z; public: Complex(double = 0.0); friend ostream& operator<<(ostream&, const Complex&); static int doSomething() { z = 2 * y; return z; } }; (a) What is wrong in the definition of the member function doSomething()? (b) What will be the effect of writing the friend function operator<<(...) in the private part of the class? (5 marks)

(a) doSomething() is a static member function, so it has no this pointer and cannot use the non-static data member y (it can use only static members such as z). Assigning the double 2 * y to the int z would also lose the fractional part. Fix: make the function non-static, or use only static data, or pass the needed value as a parameter.

(b) No effect. A friend function is not a member of the class, so access specifiers (public, private, protected) do not apply to the friend declaration. It can be written in any section of the class and the function still has access to all members.

Q69. What are friend functions? Write their characteristics with an example. (6 marks)

  • A friend function is a non-member function that is allowed to access the private and protected members of a class. It is declared inside the class with the friend keyword.
  • It is not called with an object and has no this pointer; the object is passed as an argument.
  • It can be declared in any section of the class (public or private makes no difference).
  • Friendship is granted by the class, is not mutual and is not inherited.
class Box {
    double width;
public:
    Box(double w) : width(w) {}
    friend double getWidth(const Box &b);   // friend declaration
};
double getWidth(const Box &b) { return b.width; }   // can read the private member

Q70. How can a common friend function of two different classes be declared? Is it possible for one function to be a friend of two classes? (4 marks)

Yes. The function is declared with the friend keyword in both classes; because the second class is used before it is defined, a forward declaration of one class is required.

class B;                         // forward declaration
class A {
    int a;
public:
    A(int x) : a(x) {}
    friend int sum(const A&, const B&);
};
class B {
    int b;
public:
    B(int y) : b(y) {}
    friend int sum(const A&, const B&);
};
int sum(const A &x, const B &y) { return x.a + y.b; }   // accesses private data of both

The access specifier does not matter: a friend declaration may appear in the private or the public part of the class.

Q71. Friend functions increase "programming bugs" and "data vulnerability". What is your opinion? (3 marks)

I agree to a large extent. A friend function can read and modify private data directly, so the class no longer controls every change to its own data; a bug in any friend can corrupt the object, and when the class changes, all friends must be checked. Hence friends reduce encapsulation and make the data more vulnerable. They are still useful in a few cases (for example the stream operators << and >>, or operators whose left operand is not our class), so they should be used sparingly.

Q72. What is the difference between a constructor and a copy constructor? Which of them is invoked in each situation? (3 marks)

  • A constructor initializes a new object using the values given to it (or defaults). A copy constructor initializes a new object from an existing object of the same class and takes a reference to that object.
  • Student s1; or Student s1(5); calls an ordinary constructor; Student s2(s1); or Student s2 = s1; calls the copy constructor.
  • A copy constructor is also used when an object is passed or returned by value.

Q73. Why is a destructor required in a class? What are its special characteristics? (4 marks)

A destructor is needed to release resources that an object holds (dynamic memory, files, connections) when the object is destroyed. Without it, memory allocated with new inside the object would leak. If the class does not define one, the compiler supplies a default destructor, but it does not free dynamically allocated memory.

  • Its name is ~ followed by the class name.
  • It has no return type and no parameters, so it cannot be overloaded; a class has only one destructor.
  • It is called automatically when the object goes out of scope or is deleted, and it cannot be declared const or static.

Q74. What is encapsulation? What are its advantages? How can it be enforced in C++? (6 marks)

Encapsulation is the binding of data and the functions that work on it into a single unit (a class), together with hiding the internal details from the outside world.

  • Advantages: information hiding, protection of data from accidental or wrong changes, the implementation can change without affecting users of the class, simpler and more maintainable programs.
  • In C++: declare the data members private (or protected) and provide public member functions as the interface; access specifiers enforce the hiding.

Q75. How are member functions different from other (global) functions? (2 marks)

  • A member function belongs to a class and is called through an object; it can access the private members of the class and gets a hidden this pointer.
  • A global function does not belong to any class, is called without an object and can use only the public members of a class.

Q76. How is the working of a member function different from a friend function and a non-member function? (6 marks)

  • Member function: belongs to the class, called with an object (obj.f()), has a this pointer, and has full access to the members of the class.
  • Friend function: not a member and called without an object, so it has no this pointer; objects are passed as arguments. It has full access to the private and protected members because the class has granted friendship.
  • Non-member (ordinary) function: not a member and not a friend, so it can use only the public interface of the class.

Q77. What is the difference between passing a parameter by reference and by constant reference? (2 marks)

  • Pass by reference (void f(Student &s)) gives the function the original object without copying it, and the function can modify it.
  • Pass by constant reference (void f(const Student &s)) also avoids the copy but the function cannot modify the argument, and it can accept constant objects and temporaries.

Q78. Why can the operators . (dot), .*, :: and ?: not be overloaded? List other operators that cannot be overloaded. Can two complex numbers be subtracted by overloading the + operator? (5 marks)

These operators work on names and types that are resolved by the compiler at compile time (member access, scope, selection of one of two expressions), not on values of objects, so C++ does not allow their meaning to be changed. sizeof and typeid cannot be overloaded either, so the full list is: ., .*, ::, ?:, sizeof, typeid.

Technically the + operator can be overloaded to perform subtraction and the compiler will accept it, but it is bad practice because it misleads anyone reading the code. The - operator should be overloaded for subtraction.

Q79. What are binary operators? Give an example of overloading a binary operator using a class. (3 marks)

Binary operators work on two operands, for example + - * / % == < &&. When a binary operator is overloaded as a member function, the left operand is the calling object and the right operand is the single argument.

class Money {
    int rs;
public:
    Money(int r = 0) : rs(r) {}
    Money operator+(const Money &m) const { return Money(rs + m.rs); }
    bool  operator==(const Money &m) const { return rs == m.rs; }
};
// Money c = a + b;     means  a.operator+(b)

Q80. What do you mean by operator overloading? How are unary and binary operators implemented using member functions? (4 marks)

Operator overloading gives an existing operator an additional meaning for a user defined type. The operator is written as a function named operator followed by the symbol.

  • A unary operator as a member function takes no argument (the operand is the calling object): Complex operator-() const;
  • A binary operator as a member function takes one argument, the right operand: Complex operator+(const Complex &c) const;

Q81. Explain the importance of using friend functions in operator overloading with an example. (4 marks)

When the left operand of an operator is not an object of our class (for example 2.5 + c or cout << c), the operator cannot be a member function, because a member function always has the object of its own class on the left. A friend (non-member) function solves this and still has access to the private data.

class Complex {
    double real, img;
public:
    Complex(double r = 0, double i = 0) : real(r), img(i) {}
    friend Complex operator+(double d, const Complex &c);
};
Complex operator+(double d, const Complex &c) {
    return Complex(d + c.real, c.img);
}
// Complex c2 = 2.5 + c1;

Q82. How is an object of one class converted into another class? Explain with an example. (6 marks)

There are two ways: a one-argument constructor in the destination class, or a conversion operator in the source class.

class Meter {
    double m;
public:
    Meter(double x = 0) : m(x) {}
    double get() const { return m; }
};
class Feet {
    double f;
public:
    Feet(double x = 0) : f(x) {}
    Feet(const Meter &mt) : f(mt.get() * 3.28084) {}      // Meter -> Feet using a constructor
    operator Meter() const { return Meter(f / 3.28084); }  // Feet -> Meter using a conversion operator
};
// Meter m(10); Feet ft = m;   // constructor in the destination class
// Meter m2 = ft;              // conversion operator in the source class

Only one of the two methods should be used for a given pair of classes; defining both makes the conversion ambiguous.

Q83. Write a program for conversion from a basic type to a class type. (3 marks)

class Distance {
    int meters;
public:
    Distance(int m = 0) : meters(m) {}   // one-argument constructor does the conversion
    void show() const { cout << meters << " m"; }
};
int main() {
    Distance d = 25;     // int -> Distance (constructor is called)
    d.show();
}

Q84. If da is a member variable of a class, will the statement this.da = 25; inside a member function assign 25 to da? (2 marks)

No, the statement is wrong. this is a pointer, so its members are reached with the arrow operator or by dereferencing it: this->da = 25; or (*this).da = 25;. The dot operator can be used only with an object or a reference.

Q85. Explain the scope of the private members of a class with an example. (3 marks)

A private member can be used only inside the member functions (and friends) of its own class. Code outside the class, including main(), cannot read or write it directly through an object.

class Account {
    double balance;                  // private
public:
    void deposit(double d) { balance += d; }   // OK: member function
};
int main() {
    Account a;
    a.deposit(100);     // OK
    // a.balance = 5;   // error: balance is private
}

Q86. Assume class X has no overloaded operators but has a member function to subtract two objects of X and store the result in the object that calls it. Write the statement that subtracts two objects x1 and x2 and places the result in x3. (2 marks)

x3.subtract(x1, x2);   // x3 is the calling object that receives the result

The function name subtract is assumed; the question does not name it. Because no operator is overloaded, x3 = x1 - x2; would not compile.

Q87. Detect and correct the compile time errors in the following code. (5 marks)

class Exam {
    char *ExamName;
    int No_of_paper;
public:
    Exam() { ExamName = "Final Term"; No_of_paper = 5; }
    void setname(char* name) const { ExamName = name; }
    void setpaper(int paper) const { No_of_paper = paper; }
    char* getname() { return ExamName; }
    int getpaper() { return No_of_paper; }
};
int main() {
    const Exam exam1;
    cout << " Exam = " << exam1.getname() << endl;
    cout << " Number of paper = " << exam1.getpaper();
}
  • Error 1: setname() and setpaper() are declared const but modify data members. Remove const from the setters.
  • Error 2: exam1 is a constant object, so it can call only const member functions, but getname() and getpaper() are not const. Declare them const.
  • Warning: assigning the string literal to char * should be const char *, and const Exam exam1; works because the class has a user defined default constructor.
class Exam {
    const char *ExamName;
    int No_of_paper;
public:
    Exam() { ExamName = "Final Term"; No_of_paper = 5; }
    void setname(const char* name) { ExamName = name; }
    void setpaper(int paper) { No_of_paper = paper; }
    const char* getname() const { return ExamName; }
    int getpaper() const { return No_of_paper; }
};

Q88. Consider the class XYZ below. In which order are the variables e, f and g initialized, and what are their values after an object is created? class XYZ { int e; int f; int g; public: XYZ(); }; XYZ::XYZ() : g(30), e(10), f(20) { } (3 marks)

Members are initialized in the order in which they are declared in the class, not in the order of the initialization list. So e is initialized first, then f, then g. The values are e = 10, f = 20, g = 30; the initialization list only decides which value each member gets.

Note: one shared answer sheet gives f = 30 and g = 20, which is wrong.

Q89. Can an array of objects be initialized in the same way as an integer array, for example A[3] = {1, 2, 3}? Give a C++ example. (4 marks)

Yes. If the class has a constructor that takes one argument, each element of the array can be initialized with a value in braces; for several arguments, call the constructor explicitly for each element.

class Emp {
    int id;
public:
    Emp(int i = 0) : id(i) {}
};
Emp a[3] = {1, 2, 3};                       // calls Emp(1), Emp(2), Emp(3)
Emp b[3] = {Emp(10), Emp(20), Emp(30)};     // explicit form, works for any constructor

Q90. Given int *entry = new int[10]; write code to fill the array with 10 numbers entered from the keyboard. (3 marks)

int *entry = new int[10];
cout << "Enter ten numbers: ";
for (int i = 0; i < 10; i++)
    cin >> entry[i];
// ... use the array ...
delete[] entry;             // release the memory

Q91. What is wrong with the following code? int *p = new int; int *p = new int; cout << "p = " << p << ", q = " << q << ", p+q = " << p+q << endl; (2 marks)

  • The variable p is declared twice in the same scope; the second line was meant to declare q, which is otherwise undeclared.
  • Adding two pointers (p+q) is illegal in C++; only a pointer and an integer can be added, or two pointers subtracted.
  • Also, memory obtained with new should be released with delete.

Q92. What is the output of the following program? class A { int a; public: A(int aa) { a = aa; } void print() { cout << " A = " << a; } }; class B : public A { int b; public: B(int aa, int bb) : A(aa) { b = bb; } void print() { cout << " B = " << b; } }; void main() { A objA(10); B objB(30, 20); objA = objB; objA.print(); } (3 marks)

Output: A = 30

Assigning a derived object to a base object copies only the base part (a = 30); the extra member b is sliced off. objA is still an object of class A, so A::print() runs.

Q93. What is wrong with this program? void main() { class Test { int x; public: int getX() { return x; } void setX(int a) { x = a; } void showX { cout << getX() << endl; } }; } (2 marks)

The function showX is declared without parentheses; it must be written void showX() { ... }. The class itself is allowed to be defined inside main() (a local class); it simply cannot be used before the definition is complete, and the program never creates an object.

Q94. Define the class Person that has a name and an age. Define a default constructor, a constructor with the name as argument (age is 18), a constructor with name and age as arguments, and the copy constructor. (7 marks)

class Person {
    char *name;
    int age;
public:
    Person() : age(0) {
        name = new char[1];
        name[0] = '\0';
    }
    Person(const char *n) : age(18) {
        name = new char[strlen(n) + 1];
        strcpy(name, n);
    }
    Person(const char *n, int a) : age(a) {
        name = new char[strlen(n) + 1];
        strcpy(name, n);
    }
    Person(const Person &p) : age(p.age) {          // deep copy constructor
        name = new char[strlen(p.name) + 1];
        strcpy(name, p.name);
    }
    ~Person() { delete[] name; }
};

Q95. What are the basic characteristics of object oriented programming? (3 marks)

  • Encapsulation: data and functions are bound together in a class and the details are hidden.
  • Inheritance: a new class acquires the features of an existing class, which gives reuse.
  • Polymorphism: the same operation behaves differently on different types of objects.
  • Also: abstraction, objects communicate by messages, and programs are built around objects rather than around functions.

Q96. What is Object Oriented Programming (OOP)? What are its advantages? (6 marks)

OOP is a programming approach in which a problem is modelled as a set of objects that combine data and the operations on that data. Programs are organised around these objects, which are created from classes and communicate with each other.

  • The model is close to the real world problem, so programs are easier to understand.
  • Code can be reused through classes and inheritance.
  • Data hiding and encapsulation make programs more secure and easier to maintain.
  • New features can be added by extending existing classes without rewriting them.
  • Large programs are easier to divide among programmers.

Q97. What is multilevel inheritance? How is it different from multiple inheritance? (5 marks)

  • Multilevel inheritance: a class is derived from a class that is itself derived from another, forming a chain (A → B → C). C inherits from B and, through it, from A.
  • Multiple inheritance: a class has more than one direct base class: class C : public A, public B.
  • In multilevel inheritance every class has one direct parent; in multiple inheritance a class has two or more direct parents at the same level.

Q98. What is the difference between function overloading and operator overloading? / Why do we pass objects by reference to overloaded operators? (2 marks)

Function overloading means several functions with the same name but different parameter lists in one scope; the compiler chooses by the arguments. Operator overloading is the same idea applied to an operator symbol for user defined types. Objects are passed by (constant) reference to an overloaded operator to avoid copying them and, with const, to promise that the operand is not changed.

Part 3: Short Notes & Key Terms

Object
An entity with state (data members) and behaviour (member functions); an instance of a class.
Class
A user defined type that defines the attributes and behaviours common to a group of objects.
Abstraction
Showing only the relevant details of an entity and ignoring the irrelevant ones.
Encapsulation
Binding data and the functions that operate on it into one unit and hiding the details from outside.
Information hiding
Keeping the internal data and implementation private and allowing access only through a public interface.
Interface
The set of public member functions through which the outside world uses an object.
Object model
A graphical representation of classes, objects and the relationships between them.
Association
A relationship between objects in which they use each other's services.
Aggregation
A weak 'has-a' relationship where the part can exist independently of the whole.
Composition
A strong 'has-a' relationship where the part's lifetime depends on the whole.
Inheritance
Deriving a new class from an existing one so that it acquires its members; an 'is-a' relationship.
Generalization
Extracting common features of several classes into a base class.
Specialization
Creating a more specific class from an existing class by adding or changing features.
Multiple inheritance
Deriving a class from more than one base class.
Constructor
A special member function with the class name and no return type, called automatically when an object is created.
Default constructor
A constructor that can be called with no arguments.
Copy constructor
A constructor that creates an object from another object of the same class, taking a reference parameter.
Destructor
A special member function named ~ClassName that cleans up when an object is destroyed; it cannot be overloaded.
Shallow copy
Copying member values as they are, so pointers end up sharing the same memory.
Deep copy
Copying the data a pointer refers to into newly allocated memory so objects do not share it.
this pointer
An implicit pointer to the calling object, available in non-static member functions.
Static member
A member shared by all objects of the class; it exists even when no object has been created.
Friend function
A non-member function that has been given access to a class's private and protected members.
Constant object
An object whose state cannot change after initialization; it can call only const member functions.
Operator overloading
Giving an existing operator a new meaning for a user defined type.
Scope resolution operator (::)
Links a name to its class or namespace, e.g. defining a member function outside the class.
Member initialization list
A list after the constructor header that initializes members before the constructor body runs.
Null pointer
A pointer that points to nothing, usually set to 0 and tested before it is used.
Global variable
A variable declared outside all functions that can be used anywhere in the program.
Local variable
A variable declared inside a function or block that can be used only there.
Accessor
A public member function that provides read access to a private data member.
Access specifier
A keyword (public, private, protected) that states which parts of a program may access a class member.
Data members
The data items of an object; together with member functions they make up a class.
Inline function
A function whose body the compiler substitutes at each call site to avoid call overhead.

No comments:

Post a Comment

Please give us your feedback & help us to improve this site.