2 Basics Of C Programming

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.

Basics of C++ programming: notes

C++ Program Structure

C++ was developed by Bjarne Stroustrup at AT&T Bell Laboratories in the early 1980s as an extension of C that added support for object oriented programming while keeping C's efficiency; the name plays on C's own increment operator ++, since C++ is meant as an incremented version of C. A C++ program is conventionally organized into four sections: the #include directives that bring in library declarations, the class declarations that describe the program's data types, the definitions of the member functions belonging to those classes, and finally the main() function that drives the program. In a larger project these sections are commonly split across separate files, class declarations in a header file, member function definitions in a source file, and the program that uses the class in a third file that includes the first two, which separates the abstract interface (the class definition) from its implementation and mirrors a client server relationship: the class with its member functions is the server offering services, and the code in main() that calls those services is the client.

#include <iostream>
using namespace std;

class Item {
    int number;
    float cost;
public:
    void setData(int n, float c) {
        number = n;
        cost = c;
    }
    void show() {
        cout << "Number: " << number << ", Cost: " << cost << endl;
    }
};

int main() {
    Item x;
    x.setData(7, 250.5);
    x.show();
    return 0;
}

Character Set and Tokens

The character set of C++ is the alphabet the compiler reads a program in: uppercase and lowercase letters, the digits 0 to 9, and special characters such as spaces, punctuation and operator symbols. A token is the smallest unit of a program the compiler treats as meaningful, comparable to a word in a sentence, and C++ recognizes six kinds: keywords, reserved words with a fixed meaning, always written in lowercase (C++ keeps the roughly 32 keywords of C and adds around 15 more of its own, for example class, new, delete, try and catch); identifiers, the programmer's own names for variables, functions and classes; constants, or literals, fixed values of numeric, character or string type; operators, symbols such as + and == that act on operands; and special symbols, or punctuators, { }, ( ), , and ;, that mark the structure of the program.

Data Type

C++ groups its data types into three categories. Basic (built in) types are int, char, float and double, to which the ANSI committee added bool and wchar_t; a void type says that a function returns nothing or takes no arguments. Typical sizes and ranges on a classic 16 bit compiler are:

TypeBytesRange
char1-128 to 127
int2-32768 to 32767
short int2-32768 to 32767
long int4-2147483648 to 2147483647
float4$3.4\times10^{-38}$ to $3.4\times10^{38}$
double8$1.7\times10^{-308}$ to $1.7\times10^{308}$

On most current 32 and 64 bit compilers int and float are both 4 bytes, since sizes scale with the machine's word size. Derived types, arrays, pointers and functions, are built out of the basic ones. User defined types are struct, union and enum, inherited from C, plus C++'s own class, which behaves like a built in type once declared and whose variables are called objects. An enum attaches names to a sequence of integers, starting at 0 by default:

enum Shape { CIRCLE, SQUARE, TRIANGLE };  // CIRCLE=0, SQUARE=1, TRIANGLE=2

One difference from C is worth noting for character arrays: in C, char str[3] = "xyz"; is accepted because the compiler is allowed to drop the terminating null character, but in C++ the array must be declared one element larger than the text it holds, char str[4] = "xyz";, to leave room for the automatic '\0'.

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 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:

  1. Function contains loops - If the inline function contains looping statements such as for, while, or do-while, the compiler will not inline it.

  2. Function contains static variables - If the function has static local variables declared inside it, it cannot be inlined.

  3. Function is recursive - A recursive inline function (a function that calls itself) cannot be expanded inline.

  4. Function contains switch or goto statements - Functions containing switch or goto control statements may not be inlined.

  5. 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.

  6. Function returns a value and contains multiple return statements - In some cases, multiple return points prevent inlining.

Note: The inline keyword 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 Callch usedn usedSource
printChar()'*'3Both defaults used
printChar('#')'#'3n default used
printChar('@', 7)'@'7No defaults used
printChar('$', 5)'$'5No 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.

Open this answer on its own page →

2079 · 5 marks

What is inline function? Why it is used? Write a program to illustrate inline function. [5]

Show solved 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

FeatureInline Function
Keyword usedinline
Substitution timeCompile time
PurposeIncrease execution speed
Best used forSmall, frequently called functions
Overhead removedFunction call overhead
Open this answer on its own page →

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 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 &param1, data_type &param2);

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

AspectDetail
int &aa is a reference to the actual argument x
int &bb is a reference to the actual argument y
Changes to aDirectly change x in main()
Changes to bDirectly change y in main()
No copy madeMemory 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.
Open this answer on its own page →

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]

Return by reference means that a function returns a reference (alias) to a variable rather than returning a copy of its value. When a function returns by reference, the caller receives direct access to the original variable, and the returned reference can be used as an lvalue (i.e., it can appear...

Open this answer on its own page →

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]

The principal reason for using default arguments in a function is to make function calls more flexible and convenient. A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function does not provide a value for that ar...

Open this answer on its own page →

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]

Function overloading is a feature of C++ that allows two or more functions to have the same name but different parameter lists (different number, type, or order of arguments). The compiler distinguishes between overloaded functions based on the type and number of arguments passed to them. As stat...

Open this answer on its own page →

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]

The process of allocating memory during runtime (execution time) of a program using the heap space of memory, to reduce wastage of memory, is called dynamic memory allocation. - new - memory allocation operator (allocates memory at runtime from heap) - delete - memory release operator (frees the ...

Open this answer on its own page →

2076 · 5 marks

What is use of new and delete operators? Illustrate with example. What are advantages of new over malloc. [5]

The new operator is used to dynamically allocate memory at runtime from the heap (free store). It allocates memory for a variable or object and returns a pointer to it. If allocation fails, it throws a badalloc exception. Syntax: The delete operator is used to free/deallocate memory that was prev...

Open this answer on its own page →

Input/Output Streams and Manipulators

2078 · 5 marks

Write short notes on: a. Manipulators b. Protected Access Specifier [5]

--- Manipulators are special functions used in C++ to format the output or manipulate the stream in a convenient way. They are used along with the insertion (<<) and extraction () operators. In the context of file access, each file has two associated pointers known as file pointers: - Input point...

Open this answer on its own page →

2076 · 5 marks

Write short notes on:- Cascading of IO operation - Pure Virtual Function [5]

--- Cascading of I/O operations refers to the technique of chaining multiple input or output operations together in a single statement using the insertion operator (<<) or extraction operator (). This is possible because in C++, the operators << and are overloaded to return a reference to the str...

Open this answer on its own page →

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]

A string in C++ is a character array. To reverse it, we swap the character at the first position with the character at the last position, then the second with the second-to-last, and so on, continuing until we reach the middle of the string. --- --- Suppose the input string is "HELLO" (length = 5...

Open this answer on its own page →

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]

--- Type conversion (typecasting) refers to changing an entity of one data type into another data type. It is used in computer programming to ensure variables are correctly processed by a function. - Ensures compatibility between different data types in an expression - Helps avoid loss of data du...

Open this answer on its own page →