Object Oriented Programming · Unit 2 · 5 hrs
Basics of C++ programming
Exam-focused notes for Basics of C++ programming (Object Oriented Programming, CSC166): what the TU syllabus asks and how it has actually been tested, with 12 solved past questions from this unit.
Basics of C++ programming in short
This unit covers the mechanics of a C++ program: its four part structure, the character set and tokens it is written in, its data types and how one type converts into another, the preprocessor and namespace facilities that manage names, stream based input and output, dynamic memory management with new and delete, the control statements inherited from C, and C++'s function and pointer features.
What this unit covers
- C++ Program Structure
- Character Set and Tokens
- Data Type
- Type Conversion
- Preprocessor Directives
- Namespace
- Input/Output Streams and Manipulators
- Dynamic Memory Allocation with new and delete
- Control Statements
- Functions: Function Overloading, Inline Functions, Default Argument, Pass by Reference, Return by Reference, Scope and Storage Class
- Pointers: Pointer variables declaration & initialization, Operators in pointers, Pointers and Arrays, Pointer and Function
Functions
2080 · 10 marks
When inline functions may not work? Define and write syntax for default arguments. Write a program to display N number of characters by using default arguments for both parameters. Assume that the function takes two arguments, one character to be printed and other how many times the character to be printed respectively.[10]
Show solved answerHide answer
Answer: Inline Functions, Default Arguments, and Program
Part 1: When Inline Functions May NOT Work (3 marks)
The compiler may ignore the inline request and treat the function as a normal function in the following situations:
-
Function contains loops - If the inline function contains looping statements such as
for,while, ordo-while, the compiler will not inline it. -
Function contains static variables - If the function has static local variables declared inside it, it cannot be inlined.
-
Function is recursive - A recursive inline function (a function that calls itself) cannot be expanded inline.
-
Function contains switch or goto statements - Functions containing
switchorgotocontrol statements may not be inlined. -
Function is too large/complex - If the function body is too large, inlining it would increase code size significantly, so the compiler refuses to inline it.
-
Function returns a value and contains multiple return statements - In some cases, multiple return points prevent inlining.
Note: The
inlinekeyword is only a request to the compiler, not a command. The compiler has the final decision.
Part 2: Default Arguments - Definition and Syntax (3 marks)
Definition:
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function does not provide a value for that argument. It allows a function to be called with fewer arguments than it is defined to accept.
Key Rules:
- Default arguments must be specified from right to left (trailing arguments first).
- Once a default value is assigned to a parameter, all parameters to its right must also have default values.
- Default values are specified in the function declaration (prototype).
Syntax:
return_type function_name(datatype param1, datatype param2 = default_value);
Example of syntax with two default arguments:
void display(char ch = '*', int n = 10);
Here, if no arguments are passed, ch defaults to '*' and n defaults to 10.
Part 3: Program to Display N Number of Characters Using Default Arguments (4 marks)
#include <iostream>
using namespace std;
// Function declaration with default arguments
// ch = character to print (default: '*')
// n = number of times to print (default: 3)
void printChar(char ch = '*', int n = 3);
int main()
{
cout << "Using both default arguments (no arguments passed):" << endl;
printChar();
// Output: ***
cout << "\nUsing one argument (only character passed):" << endl;
printChar('#');
// Output: ###
cout << "\nUsing both arguments (no defaults used):" << endl;
printChar('@', 7);
// Output: @@@@@@@
cout << "\nUsing character '$' with 5 times:" << endl;
printChar('$', 5);
// Output: $$$$$
return 0;
}
// Function definition
void printChar(char ch, int n)
{
cout << "Character: " << ch << " | Printed " << n << " time(s): ";
for (int i = 1; i <= n; i++)
{
cout << ch;
}
cout << endl;
}
Output:
Using both default arguments (no arguments passed):
Character: * | Printed 3 time(s): ***
Using one argument (only character passed):
Character: # | Printed 3 time(s): ###
Using both arguments (no defaults used):
Character: @ | Printed 7 time(s): @@@@@@@
Using character '$' with 5 times:
Character: $ | Printed 5 time(s): $$$$$
Explanation of the Program:
| Function Call | ch used | n used | Source |
|---|---|---|---|
printChar() | '*' | 3 | Both defaults used |
printChar('#') | '#' | 3 | n default used |
printChar('@', 7) | '@' | 7 | No defaults used |
printChar('$', 5) | '$' | 5 | No defaults used |
Important Note: Default arguments are written in the function declaration/prototype, not in the definition. The compiler substitutes the default value when the argument is omitted in the function call.
2079 · 5 marks
What is inline function? Why it is used? Write a program to illustrate inline function. [5]
Show solved answerHide answer
Inline Function in C++
Definition
An inline function is a C++ enhancement feature in which the compiler replaces the function call with the actual body (definition) of the function at compile time, instead of making a regular function call at runtime.
To declare an inline function, the keyword inline is placed before the function definition.
Syntax:
inline return_type function_name(parameters) {
// function body
}
Why Inline Functions are Used
As stated in the notes:
"The inline functions are a C++ enhancement feature to increase the execution time of a program. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime."
The main reasons for using inline functions are:
- To increase execution speed: Eliminates the overhead of a function call (saving/restoring registers, jumping to function address, etc.)
- To avoid function call overhead: The function body is directly substituted at the point of call during compilation.
- Useful for small, frequently called functions: Where the overhead of a call is significant compared to the function body itself.
- Maintains readability: Code remains modular and readable like normal functions, but executes like direct code.
Program to Illustrate Inline Function
#include<iostream>
using namespace std;
// Inline function to calculate square of a number
inline int square(int x) {
return x * x;
}
// Inline function to calculate cube of a number
inline int cube(int x) {
return x * x * x;
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
// Compiler replaces these calls with actual code at compile time
cout << "Square of " << num << " = " << square(num) << endl;
cout << "Cube of " << num << " = " << cube(num) << endl;
return 0;
}
Sample Output
Enter a number: 4
Square of 4 = 16
Cube of 4 = 64
How It Works
When the compiler encounters square(num), instead of making a function call at runtime, it substitutes the code as:
// square(num) is replaced by:
num * num
This substitution happens at compile time, making execution faster by removing function call overhead.
Key Points to Remember
| Feature | Inline Function |
|---|---|
| Keyword used | inline |
| Substitution time | Compile time |
| Purpose | Increase execution speed |
| Best used for | Small, frequently called functions |
| Overhead removed | Function call overhead |
2078 · 5 marks
What is meant by pass by reference? How can we pass arguments by reference by using reference variable? Illustrate with example. [5]
Show solved answerHide answer
Pass by Reference in C++
Definition
Pass by reference is a method of passing arguments to a function where the address (location) of a variable is passed to the function. When a function is called by reference, the formal arguments become references to the actual arguments. This means any changes made to the formal parameters inside the function directly affect the actual arguments in the calling function.
In contrast, pass by value sends a copy of the data, so the original variable remains unchanged.
Passing Arguments by Reference Using Reference Variables
In C++, a reference variable is an alias (another name) for an existing variable. It is declared using the & symbol. When used as a function parameter, the formal parameter becomes a reference to the actual argument -- no copy is made, and changes inside the function reflect in the original variable.
Syntax:
return_type function_name(data_type ¶m1, data_type ¶m2);
Example: Swapping Two Numbers Using Pass by Reference
#include <iostream>
using namespace std;
// Function using reference variables as parameters
void swap(int &a, int &b) {
int temp;
temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap(x, y); // x and y are passed by reference
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
Output:
Before swap: x = 10, y = 20
After swap: x = 20, y = 10
Explanation
| Aspect | Detail |
|---|---|
int &a | a is a reference to the actual argument x |
int &b | b is a reference to the actual argument y |
Changes to a | Directly change x in main() |
Changes to b | Directly change y in main() |
| No copy made | Memory efficient; original values are modified |
Key Points
- The
&symbol in the parameter list makes the parameter a reference variable. - The formal argument and actual argument share the same memory location.
- No separate copy of the variable is created, unlike pass by value.
- This is useful when a function needs to modify the original variable or when passing large objects to avoid overhead of copying.
2076 · 5 marks
What is meant by return by reference? How can we return values by reference by using reference variable? Illustrate with example. [5]
2075 · 5 marks
What is the principle reason for using default arguments in the function? Explain how missing arguments and default arguments are handled by the function simultaneously? [5]
2075 · 5 marks
"An overloaded function appears to perform different activities depending the kind of data send to it." Justify the statement with appropriate example. [5]
Dynamic Memory Allocation with new and delete
2079 · 5 marks
How dynamic memory allocation is done using new and delete? Write program for illustrating use of new and delete. [5]
2076 · 5 marks
What is use of new and delete operators? Illustrate with example. What are advantages of new over malloc. [5]
Input/Output Streams and Manipulators
2078 · 5 marks
Write short notes on: a. Manipulators b. Protected Access Specifier [5]
2076 · 5 marks
Write short notes on:- Cascading of IO operation - Pure Virtual Function [5]
Pointers
2075 · 5 marks
Write a member function called reverse() that reverses a string (an array of character). Use a for loop that swaps the first and last characters, then the second and next-to-last character and so on. The string should be passed to reverse() as an argument. [5]
Type Conversion
2080.1 · 5 marks
Explain the significance of type conversion. How do we achieve dynamic memory allocation in C++? Explain with an example. [5]
Make Unit 2 stick
Practice CSC166 with flashcards & quizzes