Question: CA04 Functions in C++ Part 1: Your first software library Create three files: lib.h , lib.cpp and client.cpp . The header file lib.h contains extern

CA04 Functions in C++

Part 1: Your first software library

Create three files: lib.h, lib.cpp and client.cpp. The header file lib.h contains

extern int foo; void print_foo(); void print(int); 

The source code file lib.cpp #includes lib.h, defines print_foo() to print the value of foo using cout, and print(int i) to print the value of i using cout.

The source code file client.cpp #includes lib.h, defines main() to set the value of foo to 7 and print it using print_foo(), and to print the value of 99 using print(). Note that client.cpp does not #include iostream.h, as it doesn't directly use any of those facilities.

Deliverable: lib.cpp, lib.h, client.cpp

Part 2: pass by value, pass by reference, pass by const reference

Write the swap() function below. It should have the body

void swap(int a, int b) { int temp; temp = a ; a = b; b = temp; } 

where a and b are the names of the arguments.

Next, try calling the swap function like this:

int x = 7, y = 9 ; swap(x, y); swap(7, 9); const int cx = 7, cy = 9 ; swap(cx, cy) ; swap(7.7, 9.3) ; double dx = 7.7, dy = 8.2 ; swap( dx, dy ); swap( dx, dy ) ; 
  1. Did the functions and calls compile? Why? If the swap compiled, print the value of the arguments after the call to see if they were actually swapped. Write your answer to these questions in a comment block above the function definition.
  2. Now copy the swap function definition, changing its first line to swap_r( int&, int& ), and repeat the exercise.
  3. Now copy the swap function definition again, this time changing its first line to swap_cr( const int&, const int& ), and repeat the exercise.

Deliverable: one single source file, with three function definitions, and answers in comment blocks

Part 3: namespaces

First, read about namespaces in lecture 6 (functions). Then, write a program using a single file containing three namespaces X, Y and Z so that the following main() works correctly:

int main() { X::var = 7; X::print(); // print X's var using namespace Y; var = 9 ; print(); // print Y's var { using Z::var; using Z::print; var = 11; print(); // print Z's var } print(); // print Y's var X::print(); // print X's var } 

Each namespace needs to define a variable called var and a function called print() that outputs the appropriate var using cout.

Deliverable: one single source file, namespace.cpp

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!