Lab Sheet 2
Additional Features in C++
1. Comments in C++
In C++, a new symbol for comment '//' (double slash) is introduced and is called a single-line comment. The content after // until the end of the line is treated as a comment.
// this is an example of a comment illustration
stdno=96; //no of student in BCT batch
C comment symbols '/*' and '*/' are also valid and can be used for multi-line comments. This commenting style is called a multiline comment
/*this is an example illustrating the multi-line
comment in C++ */
2. Output Statement
The statement
cout << "This is the first lab in C++";
causes the string "This is the first lab in C++" to be displayed on the screen. Here cout is the predefined object that represents the standard output stream in C++.
The operator '<<', insertion operator, has a simple interface, i.e., it is not necessary to specify the data type of the variable on its right. The insertion operator automatically works with any type of variable. Another advantage of this operator is that user-defined data types can also be used with this operator, which is not possible with the printf( ) function.
3. Input Statement
The following statement reads the value from the keyboard and places it in the variable size.
cin >> size;
The cin identifier represents the standard input device. The >> operator (extraction operator) takes the input from the device. The function is smart enough to interpret the input according to the data type of the variable that holds the value. If a variable size is an integer and the user types "25", the integer value 25 will be placed in size. If the variable size is a string, the string "25" will be placed in it.
4. Manipulators
Manipulators are special functions that are used with input/output statements to control the formatting of data. The most commonly used manipulators are endl and setw. The endl manipulator, when used in an output statement, causes a linefeed to be inserted. It has the same effect as using the newline character '\n' in C. For example
int lexp = 2000;
int cexp = 800;
int texp = 2500;
...
cout<<"Lodging"<<lexp<<endl;
cout<<"Clothing"<<cexp<<endl;
cout<<"Travels"<<texp<<endl;
.....
The output appears as
Lodging 2000
Clothing 800
Travels 2500
This is not the ideal output. The setw(n) manipulator eliminates this problem by specifying a minimum field width for the next output item. Since setw(n) is a parameterized manipulator, we need to include the <iomanip> header. The value is right-aligned within the specified field width by default. For example
#include<iomanip>
...
cout<<setw(10)<<"Lodging"<<setw(6)<<lexp<<endl;
cout<<setw(10)<<"Clothing"<<setw(6)<<cexp<<endl;
cout<<setw(10)<<"Travels"<<setw(6)<<texp<<endl;
.....
The output now becomes
ˍˍˍLodgingˍˍ2000
ˍˍClothingˍˍˍ800
ˍˍˍTravelsˍˍ2500
Here dashes ('ˍ') are just shown to represent spaces.
5. Namespace
The namespace feature in C++ allows us to specify a scope with a name. Actually, the namespace is a named scope. The namespace feature helps avoid name conflicts between identifiers defined in different parts of a program or in different libraries. A namespace is defined as follows.
namespace nsn
{
int item;
void showitem(int it)
{
cout<<it;
}
}
The elements from the namespace are used as
cout<<nsn::item;
or it can be accessed by including the particular element into our scope as
using nsn::item;
After inclusion, the statements
cout<<item; //correct, as it is included
showitem(item); //Error: showitem not in current scope
It can be made correct as
nsn::showitem(item); //Correct, fully qualified name used
We can also include everything from the namespace as
using namespace nsn;
After this inclusion, every element from the namespace can be used directly as
cout<<item; //correct
showitem(item); //correct
6. Pass by reference
Pass-by-reference allows a function to work directly with the original variable/object. When a reference (alias) of the variable/object is passed, the function works directly on the actual variable/object used in the call. This means that any changes made to the variable/object inside the function will reflect in the actual variable/object. The function prototype of the function that allows pass by reference is:
return_type function_name(datatype ¶m1_name, datatype ¶m2_name, ...);
For example
void swap (int &x, int &y)
{
int t;
t=x;
x=y;
y=t;
}
This function can be called as
swap(a,b); //reference of a and b is passed
7. Return by reference
The return by reference mechanism in C++ allows us to return the reference (alias) of a variable/object to the calling program. So the function call can be on the left side of the equal sign, and we can assign values to the return references. Since the local variables will not exist after returning, returning a reference to a local variable is dangerous and should be avoided.
For example
int x=5;
int& asgnx()
{
return x;
}
This function can be called as
asgnx()=7; //x is assigned with value 7
cout<<x; //displays 7
8. Structure with function
In C++, when creating a structure variable, the extra struct keyword is not necessary. The value or reference of the structure variable can be passed as an argument to a function. For example
struct Student
{
int roll;
char name[50];
};
...
void show(Student st)
{
cout<<"Roll no: "<<st.roll<<endl;
cout<<"Name: "<<st.name<<endl;
}
...
Student st1; //struct keyword not necessary when declaring.
...
show (st1); //function call, st1 is passed to function.
9. Overloaded function
Function overloading allows multiple functions to have the same name but different parameter lists. A specific function is called based on the argument passed, and it matches the defined function with parameters that match the argument list. The reason behind using overloaded functions is because of their convenience to use the same function name for different kinds of data or operations.
void convert(); //takes no argument
void convert(int n); //takes one argument of type int
void convert(float,int);
//takes two arguments of type float and int
It uses the number of arguments and their data types to distinguish one function from another. The function definition and call can be done as usual. Note that the return type does not distinguish overloaded functions.
10. Inline Function
We know that a function saves memory space but takes some extra time. If the functions are short, they may be inserted directly in the call location of the calling function. If the function is very short, the instructions necessary to call it may take up more space than inserting the function's code in the called location. The solution to this is the inline function. The call to the inline function in the source is almost the same as a normal function, but the compiler inserts the function's code instead of calling it. Besides, the source file remains well organized and easy to read, since the functions are shown as a separate entity. Very short functions, say one or two statements, are candidates to be inlined. The compiler is free to ignore the inline request if the function does not qualify for inline compilation.
For example.
inline float convert(int n)
{
return n*12.0;
}
Here all we need is the keyword inline in the function definition.
11. Default Arguments
A function can be called without specifying all its arguments. This won't work on just any function. To make a function accept missing arguments, it has to specify the default value of those missing arguments.
Let us see an example
void dearg(char ch = '?', int n = 25);
//declaration with default arguments
int main()
{
dearg();
dearg('<');
dearg('>',30);
return 0;
}
void dearg(char ch, int n)
{
...
}
Here the function dearg() takes two arguments. It is called three times from the main() function. The first time it is called with no arguments, the second time with one argument, and the third time with two. The first and second provide default arguments, which will be used if the calling function doesn't supply them. The values for default arguments follow an equal sign, which is placed directly after the name. If one argument is missing, it is assumed to be the last argument, as shown in the second function call. Default arguments must be specified from right to left.
For example.
void fun(int a, int b = 10); //Correct
void fun(int a = 10, int b);
//Error, incorrect default argument
Exercises
Use manipulators where it seems to be useful.
Write a program to create a structure to represent a date with members for month, day, and year. Create a display function that takes this structure as an argument and prints the date in the exact format: 2004/11/28. Make sure that date, month, and year are displayed with the required field width.
Write a program to convert feet to inches using an overloaded function named convertToInches(). Implement three versions of this function:
No argument: Prompts the user inside the function to enter the value in feet, performs the conversion, and displays the result.
One argument: Takes the number of feet as a value and returns the equivalent inches.
Two arguments: Takes the number of feet and an existing inches variable by reference, updates that reference variable directly with the calculation, and returns nothing (void).
Write a program with two namespaces: Square and Cube. In both namespaces, define an integer variable named num and a function named fun. The fun function in the Square namespace should return the square of an integer passed as an argument, while the fun function in the Cube namespace should return the cube of an integer passed as an argument. In the main() function, assign different integer values to num in each namespace. Then, compute and print the cube of the integer variable num of the Cube namespace using the fun function of the Cube namespace and the square of the integer variable num of the Square namespace using the fun function of the Square namespace.
Write a function that accepts two temperatures by reference, compares them, and returns a reference to the larger of the two numbers. In the main() function, call that to set the larger of the two numbers to a value entered by the user by using return by reference.
Assume that the employee will have to pay 10 percent income tax to the government. Write a program that asks the user to enter the employee salary. Use an inline function to calculate and return the net payment received by the employee from the company, then display the result.
Write a program that reads the previous year's monthly salaries and calculates and displays the updated monthly salaries for the Chief Executive Officer, Information Officer, System Analyst, and Programmer, which have been increased by 9, 10, 12, and 12 percent, respectively, this year. Pass the salary and increment percent to a function that returns the updated current salary using default arguments for salary (60,000) and percent increment (12). Display the updated salary of each employee.