Unit 1: C++ Programming Basics and Functions - Subjective Questions
CSE202 — Object Oriented Programming • Practice Questions with Detailed Answers
20 questions
Define object-oriented programming (OOP). Explain its fundamental concepts and name some commonly used OOP languages.
Object-oriented programming (OOP) is a programming paradigm in which a program is organized around objects that combine data and the functions that operate on that data.
The fundamental concepts of OOP are:
- Class: A user-defined blueprint that specifies the data members and member functions of objects.
- Object: An instance of a class with its own state and behavior.
- Encapsulation: Binding data and functions into a single unit and controlling access to them.
- Abstraction: Showing essential features while hiding implementation details.
- Inheritance: Creating a new class from an existing class to reuse and extend its behavior.
- Polymorphism: Allowing the same interface or function name to represent different operations.
- Dynamic binding: Selecting the function to execute at runtime, commonly through virtual functions.
- Message passing: Objects communicate by invoking one another's member functions.
Common OOP languages include C++, Java, C#, Python, Ruby, and Smalltalk. C++ is a multi-paradigm language because it supports procedural, object-oriented, and generic programming.
Compare the procedural programming paradigm with the object-oriented programming paradigm.
The two paradigms differ as follows:
| Procedural programming | Object-oriented programming |
|---|---|
| The program is divided into functions or procedures. | The program is divided into classes and objects. |
| It generally follows a top-down design approach. | It generally follows a bottom-up design approach. |
| Data and functions are usually maintained separately. | Data and related functions are encapsulated in a class. |
| Global data may be accessible to many functions. | Access specifiers protect data from unauthorized access. |
| It provides limited support for data hiding. | It supports data hiding and abstraction. |
| Reuse is mainly achieved through functions. | Reuse is achieved through functions, classes, inheritance, and polymorphism. |
| It is suitable for small and algorithm-oriented programs. | It is suitable for large, complex, and evolving systems. |
| Examples include C and Pascal. | Examples include C++, Java, and C#. |
OOP generally improves modularity, maintainability, security, extensibility, and code reuse, while procedural programming can be simpler for small computational tasks.
Explain how cin and cout are used to read and write data in C++. Also describe the role of the extraction and insertion operators.
C++ performs standard console input and output through stream objects declared in the <iostream> header.
cin: Represents the standard input stream, normally the keyboard.cout: Represents the standard output stream, normally the screen.- Extraction operator
>>: Extracts formatted data from an input stream and stores it in a variable. - Insertion operator
<<: Inserts data into an output stream.
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
int age;
string name;
cout << "Enter name and age: ";
cin >> name >> age;
cout << "Name: " << name << ", Age: " << age << '\n';
return 0;
}Multiple operations can be chained because each operator returns the stream itself. For example, cin >> name >> age is processed from left to right.
Important points:
cin >> namestops reading a string at whitespace;getline(cin, name)reads an entire line.coutcan display constants, variables, expressions, and function results.- Input failure can be detected using
cin.fail()or by testing the stream directly. - Stream formatting can be controlled using flags and manipulators.
Describe the important features of C++ input/output streams. How do stream states help in handling input errors?
A stream is a sequence of bytes flowing between a program and an input or output source.
Important features of C++ streams include:
- Device independence: The same stream-based interface can be used for consoles, files, and strings.
- Type safety: Operators process values according to their data types.
- Extensibility: The
<<and>>operators can be overloaded for user-defined classes. - Formatted I/O: Width, precision, number base, alignment, and fill characters can be controlled.
- Chaining: Several input or output operations can be combined in one expression.
- Buffering: Output may be stored temporarily before being sent to a device.
- Error reporting: Streams maintain state flags instead of requiring each operation to return a separate error code.
The main stream-state functions are:
good(): Returns true when no error flag is set.eof(): Indicates that the end of input has been reached.fail(): Indicates a logical or formatting failure, such as entering text for an integer.bad(): Indicates a serious input/output failure.clear(): Resets the error flags.ignore(): Discards unwanted characters from the input buffer.
A robust input loop may use if (cin >> value) to accept valid input. After invalid input, cin.clear() restores the stream and cin.ignore(...) removes the invalid characters.
Explain the creation of a class and its objects in C++. How are public and private class members accessed?
A class is a user-defined type that groups data members and member functions. An object is an instance of that class.
Example:
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
void setDimensions(double l, double w) {
length = l;
width = w;
}
double area() const {
return length * width;
}
};
int main() {
Rectangle r;
r.setDimensions(5.0, 3.0);
cout << r.area();
}Key points are:
- Members declared under
privatecan normally be accessed only by member functions and friends of the class. - Members declared under
publiccan be accessed from outside the class through an object. - The dot operator, as in
r.area(), accesses a member through an object. - The arrow operator, as in
ptr->area(), accesses a member through a pointer to an object. - Members declared under
protectedare available to the class and its derived classes. - Members of a C++ class are private by default.
This controlled interface supports encapsulation and prevents external code from directly placing an object in an invalid state.
Distinguish among structures, unions, enumerations, and classes in C++.
These user-defined types serve different purposes:
| Type | Main purpose | Memory and members | Access behavior |
|---|---|---|---|
struct |
Groups related data and functions | Every non-static data member has separate storage | Members and base classes are public by default |
class |
Models encapsulated objects | Every non-static data member has separate storage | Members and base classes are private by default |
union |
Stores one of several alternative values | All non-static data members share the same memory location | Members are public by default |
enum |
Defines a set of named integral constants | Stores one value selected from the enumerator set | It does not organize ordinary data members like a class |
Further distinctions:
- In C++, both structures and classes can have constructors, member functions, static members, access specifiers, and inheritance. Their primary language-level difference is their default access.
- A union's size is sufficient for its largest member, subject to alignment. Writing one member generally makes it the active member, so reading an unrelated inactive member is normally invalid.
- An unscoped
enummay expose enumerator names to its surrounding scope and convert to an integer. - An
enum classprovides scoped enumerator names and stronger type safety.
Thus, classes and structures model records or objects, unions model shared-storage alternatives, and enumerations model a fixed set of named values.
Compare inline and non-inline member functions. Show how each can be defined in C++.
An inline member function is a function for which the compiler is permitted to replace a call with the function body. A non-inline member function is called through the normal function-call mechanism unless the compiler independently optimizes it.
Example:
class Counter {
private:
int value;
public:
int getValue() const { // implicitly inline
return value;
}
void setValue(int v); // declaration only
};
void Counter::setValue(int v) { // normally non-inline definition
value = v;
}Main differences:
- A member function defined inside the class definition is implicitly inline.
- A function defined outside the class can be requested as inline using
inline. - Inline functions are suitable for small, frequently called operations.
- Non-inline definitions are preferable for long or complex functions and can reduce code duplication in generated machine code.
- Inline expansion can remove call overhead but may increase executable size.
- The
inlinekeyword is a request, not a command; the compiler decides whether to expand a call. - Modern C++ also uses
inlineto permit identical definitions in multiple translation units, which is important for functions defined in header files.
What are static data members and static member functions? Explain their properties with a suitable C++ example.
A static data member belongs to the class as a whole rather than to each individual object. Therefore, only one shared copy exists for the class.
A static member function also belongs to the class and can be called without creating an object.
#include <iostream>
using namespace std;
class Employee {
private:
static int count;
public:
Employee() {
++count;
}
static int getCount() {
return count;
}
};
int Employee::count = 0;
int main() {
Employee e1, e2;
cout << Employee::getCount();
}Properties include:
countis shared by allEmployeeobjects.- A static data member normally requires one definition outside the class, as shown by
int Employee::count = 0;. - In modern C++, an
inline staticdata member can be initialized inside the class. - A static member function can be called using the class name, such as
Employee::getCount(). - It has no
thispointer because it is not associated with a particular object. - It can directly access only static members of the class.
- Static members are useful for object counts, shared configuration, identifiers, and class-wide utility operations.
Explain functions with default arguments in C++. State the rules and possible ambiguities associated with default arguments.
A default argument is a value automatically supplied by the compiler when the caller omits the corresponding argument.
#include <iostream>
using namespace std;
void display(int value, int width = 5, char fill = ' ') {
cout.width(width);
cout.fill(fill);
cout << value;
}
int main() {
display(25); // width = 5, fill = ' '
display(25, 8); // fill = ' '
display(25, 8, '*');
}Rules include:
- Default arguments are normally specified in a function declaration.
- After a parameter receives a default value, all parameters to its right must also have defaults, unless defaults were already supplied in an earlier declaration.
- Arguments can be omitted only from right to left.
- A default value should be specified only once in a given scope.
- The compiler substitutes the default argument at the call site.
- Default arguments may be used with ordinary functions, constructors, and member functions.
An ambiguity can arise when default arguments interact with overloading. For example, if both show(int) and show(int, int = 0) exist, the call show(5) matches both functions and is ambiguous. Such overlapping interfaces should be avoided.
Define an inline function. Discuss its advantages, limitations, and the circumstances in which the compiler may avoid inline expansion.
An inline function is a function declared with the inline specifier or defined inside a class definition. The compiler may replace a function call with the function's body.
inline int square(int x) {
return x * x;
}Possible advantages are:
- It can eliminate function-call overhead.
- It is convenient for small, frequently executed functions.
- Unlike a macro, it provides type checking, normal scope rules, and predictable argument evaluation.
- Its definition can be placed in a header and included in multiple translation units under the one-definition rules for inline entities.
Limitations include:
- Repeated expansion may increase executable size.
- Large inline functions can reduce instruction-cache efficiency.
- Editing an inline definition in a header may require recompiling all dependent source files.
- The keyword does not guarantee expansion.
A compiler may avoid expansion when the function is large or complex, when optimization is disabled, when a call is made through a function pointer, or when expansion provides no performance benefit. Recursive functions can sometimes be partially expanded, but unrestricted recursive expansion is impossible because the recursion depth is not generally known at compile time.
What are manipulator functions in C++? Explain commonly used manipulators with examples.
Manipulators are functions or stream helpers used with << and >> to control input/output behavior and formatting. Many parameterized manipulators are declared in <iomanip>.
Common manipulators include:
endl: Inserts a newline and flushes the output buffer.setw(n): Sets the minimum width of the next formatted field.setfill(ch): Sets the character used to fill unused field positions.setprecision(n): Controls floating-point precision.fixed: Uses fixed-point notation.scientific: Uses scientific notation.leftandright: Control field alignment.hex,oct, anddec: Select the integer number base.boolalpha: Displays Boolean values astrueorfalse.ws: Consumes leading whitespace from an input stream.
Example:
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
double price = 12.5;
cout << fixed << setprecision(2);
cout << left << setw(10) << setfill('.') << "Price";
cout << right << setw(8) << price << '\n';
cout << hex << 255 << '\n';
}Some manipulators, such as fixed and setfill, persist until changed. Others, such as setw, normally affect only the next formatted value.
Explain function overloading in C++. How does the compiler resolve overloaded calls, and what combinations cannot be used to overload functions?
Function overloading allows multiple functions in the same scope to have the same name but different parameter lists.
int area(int side);
int area(int length, int width);
double area(double radius);The functions differ in the number or types of their parameters. During overload resolution, the compiler:
- Collects visible functions with the required name.
- Removes candidates that cannot accept the supplied arguments.
- Compares the required conversions.
- Selects the unique best match.
An exact type match is generally preferred over a promotion, and a promotion is generally preferred over a broader standard conversion.
Important restrictions are:
- Functions cannot be overloaded only by changing their return type.
- Parameter names do not affect a function's signature.
- Top-level
conston a value parameter does not create a distinct overload; for example,f(int)andf(const int)represent the same parameter type for overloading. - Default arguments do not form part of the function signature and may cause ambiguous calls.
- Similar conversions can make a call ambiguous, such as when two overloads require equally ranked conversions.
Member functions may also be overloaded based on appropriate const, reference, and parameter qualifications.
Describe the scope rules of C++. Explain local, global, class, namespace, and block scope, and show how the scope-resolution operator is used.
Scope determines the region in which a declared name can be used.
Major forms of scope include:
- Block scope: A name declared inside
{}is available from its declaration to the end of that block. - Function parameter scope: A parameter is available within its function definition.
- Global or namespace scope: A name declared outside functions and classes is available in its namespace, subject to declaration visibility and linkage rules.
- Class scope: A member name belongs to its class and is accessed using an object, a pointer, or the class name where appropriate.
- Function scope: Labels used with
gotohave function scope.
A declaration in an inner scope can hide a declaration with the same name in an outer scope.
#include <iostream>
using namespace std;
int value = 10;
class Sample {
public:
static int value;
void show();
};
int Sample::value = 20;
void Sample::show() {
int value = 30;
cout << value << ' '; // local: 30
cout << Sample::value << ' '; // class static member: 20
cout << ::value; // global: 10
}The scope-resolution operator :: is used to access a global name hidden by a local declaration, qualify namespace members, define class members outside the class, and access static class members.
What is a friend function? Explain its characteristics, benefits, and risks with an example.
A friend function is a non-member function that is granted access to the private and protected members of a class by a friend declaration.
#include <iostream>
using namespace std;
class Box {
private:
double width;
public:
explicit Box(double w) : width(w) {}
friend double totalWidth(const Box& a, const Box& b);
};
double totalWidth(const Box& a, const Box& b) {
return a.width + b.width;
}Characteristics include:
- It is declared with
friendinside the class. - It is not a member function and therefore has no
thispointer. - It is called like an ordinary function, such as
totalWidth(b1, b2). - It can access private and protected members through objects or references.
- Friendship is granted by the class and is not inherited automatically.
- Friendship is not reciprocal or transitive.
- A function can be a friend of more than one class.
Friend functions are useful for symmetric binary operators and operations that require coordinated access to multiple classes. However, excessive use weakens encapsulation and increases coupling, so a public member interface should be preferred when it expresses the operation cleanly.
Explain a friend class in C++. How does it differ from a friend function, and what rules govern friendship?
A friend class is a class whose member functions are permitted to access the private and protected members of another class.
class Engine {
private:
int temperature = 90;
friend class Diagnostic;
};
class Diagnostic {
public:
int readTemperature(const Engine& e) const {
return e.temperature;
}
};Here, every member function of Diagnostic may access private and protected members of Engine.
Differences are:
- A friend function grants access to one specific non-member function or member function.
- A friend class grants access to all member functions of the named class.
- Friend-class access is broader and therefore should be used carefully.
Rules of friendship include:
- Friendship must be explicitly declared by the class granting access.
- Friendship is not reciprocal: if
Diagnosticis a friend ofEngine,Engineis not automatically a friend ofDiagnostic. - Friendship is not transitive: a friend of
Diagnosticdoes not automatically become a friend ofEngine. - Friendship is not inherited by derived classes.
- A friend declaration does not make the friend a member of the granting class.
Friend classes are useful for tightly related helper, builder, testing, serialization, or diagnostic classes, but they increase coupling.
Define a reference variable in C++. Explain its declaration, initialization, uses, and important restrictions.
A reference variable is an alias for an existing object. It is declared using & as part of the type.
int value = 10;
int& ref = value;
ref = 25; // value also becomes 25Important properties are:
- A reference must normally be initialized when it is declared.
- After initialization, it remains bound to the same object; assigning another value changes the referred object rather than rebinding the reference.
- Access through a reference uses ordinary variable syntax and does not require explicit dereferencing.
- A non-const lvalue reference, such as
int&, cannot normally bind to a temporary or a const object. - A const lvalue reference, such as
const int&, can bind to a const object and may extend the lifetime of a temporary. - A valid reference is intended to refer to an object; it is not used as a nullable handle in the way a pointer can be.
Common uses include:
- Passing arguments without copying.
- Allowing a function to modify the caller's object.
- Returning access to an existing object.
- Implementing operators and range-based loops efficiently.
References improve readability, but returning a reference to a local automatic variable is invalid because that variable is destroyed when the function returns.
Differentiate among call by value, call by address, and call by reference in C++. Give an example of each and discuss their effects on the caller's variables.
The three parameter-passing techniques differ in what is transferred to the function.
void byValue(int x) {
++x;
}
void byAddress(int* x) {
if (x != nullptr) {
++(*x);
}
}
void byReference(int& x) {
++x;
}They can be called as follows:
int n = 10;
byValue(n); // n remains 10
byAddress(&n); // n becomes 11
byReference(n); // n becomes 12Comparison:
| Technique | Parameter receives | Call syntax | Effect on caller | Null possibility |
|---|---|---|---|---|
| Call by value | A copy of the argument | byValue(n) |
Direct changes affect only the copy | Not applicable |
| Call by address | The object's address | byAddress(&n) |
Dereferenced changes affect the original | Pointer may be null |
| Call by reference | An alias to the object | byReference(n) |
Changes affect the original | A valid reference is expected to be bound |
Call by value is simple and isolates the caller's variable but may copy large objects. Passing by pointer expresses optional or address-based access but requires pointer checks and dereferencing. Passing by reference provides direct, readable access. For large read-only objects, const Type& avoids copying while preventing modification.
Explain recursion using an ordinary function. Write a recursive function for factorial and trace the evaluation of factorial(4).
Recursion occurs when a function calls itself directly or indirectly to solve a smaller instance of the same problem. A correct recursive solution needs:
- A base case that terminates recursion.
- A recursive case that moves the problem toward the base case.
For a non-negative integer , factorial is defined as:
C++ implementation:
unsigned long long factorial(unsigned int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}Trace of factorial(4):
Each call creates an activation record on the call stack. Missing or unreachable base cases can cause stack overflow. Factorial also overflows fixed-width integer types for sufficiently large values.
Describe recursion using a member function. Design a class containing a recursive function to calculate the sum of the first natural numbers.
A member function can call itself in the same way as an ordinary function. During a call through an object, each non-static member-function invocation has access to the same object's state through this.
For , the sum can be defined recursively as:
#include <stdexcept>
class NaturalNumberCalculator {
public:
long long sum(int n) const {
if (n < 0) {
throw std::invalid_argument("n must be non-negative");
}
if (n == 0) {
return 0;
}
return n + sum(n - 1);
}
};For an object calculator, calculator.sum(4) evaluates as:
Important points:
- The base case
n == 0stops the recursion. - The recursive call is made as
sum(n - 1);this->sum(n - 1)would be equivalent. - The function is marked
constbecause it does not change object state. - Input validation prevents recursion from moving indefinitely toward negative values.
- The result can also be computed directly as , which is more efficient for this particular problem.
Design a C++ class named BankAccount that demonstrates encapsulation, console input/output, an inline member function, a non-inline member function, and a static data member.
One possible design is:
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string holder;
double balance;
static int accountCount;
public:
BankAccount() : balance(0.0) {
++accountCount;
}
double getBalance() const { // inline member function
return balance;
}
void read(); // non-inline definitions
void display() const;
static int getAccountCount() {
return accountCount;
}
};
int BankAccount::accountCount = 0;
void BankAccount::read() {
cout << "Enter account holder: ";
getline(cin >> ws, holder);
cout << "Enter balance: ";
cin >> balance;
}
void BankAccount::display() const {
cout << "Holder: " << holder << '\n';
cout << "Balance: " << balance << '\n';
}Explanation:
holderandbalanceare private, so direct external access is prevented.getBalance()is defined inside the class and is implicitly inline.read()anddisplay()are declared inside but defined outside usingBankAccount::.accountCounthas one shared copy for all objects.getAccountCount()is static and can be called asBankAccount::getAccountCount().getline(cin >> ws, holder)consumes leading whitespace and then reads a complete name.
In production code, read() should also validate stream state and prevent invalid balances according to the application's rules.
Define object-oriented programming (OOP). Explain its fundamental concepts and name some commonly used OOP languages.
Object-oriented programming (OOP) is a programming paradigm in which a program is organized around objects that combine data and the functions that operate on that data.
The fundamental concepts of OOP are:
- Class: A user-defined blueprint that specifies the data members and member functions of objects.
- Object: An instance of a class with its own state and behavior.
- Encapsulation: Binding data and functions into a single unit and controlling access to them.
- Abstraction: Showing essential features while hiding implementation details.
- Inheritance: Creating a new class from an existing class to reuse and extend its behavior.
- Polymorphism: Allowing the same interface or function name to represent different operations.
- Dynamic binding: Selecting the function to execute at runtime, commonly through virtual functions.
- Message passing: Objects communicate by invoking one another's member functions.
Common OOP languages include C++, Java, C#, Python, Ruby, and Smalltalk. C++ is a multi-paradigm language because it supports procedural, object-oriented, and generic programming.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →