0% found this document useful (0 votes)
1 views13 pages

Programming and Computation II

Chapter 15 introduces C++ as an enhancement of C, focusing on object-oriented and generic programming. It covers basic C++ features, including input/output operations, variable declarations, and the use of the C++ Standard Library. The chapter also explains references, parameter passing, and the importance of header files in organizing code.

Uploaded by

Osman Siddig
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views13 pages

Programming and Computation II

Chapter 15 introduces C++ as an enhancement of C, focusing on object-oriented and generic programming. It covers basic C++ features, including input/output operations, variable declarations, and the use of the C++ Standard Library. The chapter also explains references, parameter passing, and the importance of header files in organizing code.

Uploaded by

Osman Siddig
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Programming and Computation II :

Chapter 15 : C++ as a Better C – Introduction to Object Technology

In the first 14 chapters, you learned how to write programs using C and the
procedural programming style which is type of programming paradigm . Now, in
Chapters 15 to 23, you’ll start learning C++ and two new ways to program:

1. Object-oriented programming – using classes, objects, and features like


inheritance and polymorphism to build reusable code.
2. Generic programming – using templates to write flexible, reusable functions
and classes.

These chapters will focus on creating useful and reusable pieces of software called
classes.

15.2 C++ (Simplified)

• C++ builds on C by adding features—especially object-oriented programming


(OOP)—that make it easier to write better, more reusable programs.
• C wasn’t originally expected to become so popular. But as people needed more
from the language, instead of replacing C, C++ was created to improve it. Bjarne
Stroustrup at Bell Labs developed C++ and first called it “C with classes.” The
name C++ uses the ++ symbol (which means “increment” in C) to show it’s a
“step up” from C.
• Chapters 15–23 in this book will teach you the C++11 version, which is an official
standard approved by ANSI (in the U.S.) and ISO (worldwide). This book follows
that standard closely.
• C++ is a big language, so not everything is covered here. If you want to dive
deeper, you can read the full official standard:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf

15.3 A Simple Program: Adding Two Integers (Simplified)

This section shows a basic program that adds two numbers—just like one you saw
earlier in C. But now, it uses C++ features and highlights some key differences
between C and C++.

• C file names usually end with .c


• C++ file names can end with .cpp, .cxx, or .C (capital C)
• In this book, we use .cpp for C++ files

You’ll learn how C++ improves code readability and structure even in simple
programs.

15.3 A Simple Program: Adding Two Integers (Simplified)

15.3.1 C++ Addition Program

This program asks the user for two numbers, adds them, and prints the result.
It uses C++ input/output with std::cin and std::cout.

// fig15_01.cpp
// Addition program that displays the sum of two numbers.
#include <iostream> // Input/output library

int main()
{
std::cout << "Enter first integer: ";
int number1;
std::cin >> number1;

std::cout << "Enter second integer: ";


int number2;
std::cin >> number2;

int sum = number1 + number2; // Compute sum

std::cout << "Sum is " << sum << std::endl; // Display result
}

Output Example:

Enter first integer: 45


Enter second integer: 72
Sum is 117
15.3.2 <iostream> Header

• Required for input/output using std::cin and std::cout.


• It's part of the C++ standard library.

15.3.3 main Function

• Every C++ program starts at main().


• Must specify a return type (usually int).
• In modern C++, you don’t need return 0; at the end—it's assumed.

15.3.4 Variable Declarations

• Variables like number1, number2, and sum must be declared before use.
• You can declare variables almost anywhere in C++ (unlike C, where it must be
at the start of a block).

15.3.5 Input and Output

• std::cout << is used to print to the screen.


• std::cin >> is used to read from the keyboard.
• Think of std::cin >> number1; as: "cin gives a value to number1."

15.3.6 std::endl

• Adds a new line and flushes the output (immediately shows it on screen).
• Useful after prompts so the user sees them before typing.

15.3.7 Why std :: is Needed

• std:: means "from the standard library."


• You must write std::cout, std::cin, and std::endl unless you use a shortcut like
using namespace std; (introduced later).

15.3.8 Chaining Outputs

• You can chain multiple << operators:


• std::cout << "Sum is " << number1 + number2 << std::endl;
• This combines math and printing in one line.

15.3.9 return 0; Not Required

• If main() ends without return 0;, C++ assumes success.


• It's okay to omit it in modern C++.

15.3.10 Operator Overloading (Preview)

• In later chapters, you’ll learn to create your own types (classes).


• You can teach C++ how to use << and >> with your custom types—this is called
operator overloading.

15.4 C++ Standard Library (Simplified)

C++ programs are made of classes and functions. While you can write everything
yourself, most programmers use the C++ Standard Library, which already has many
useful parts built in.

✅ Two Things to Learn in C++:

1. The C++ language itself (syntax, rules, etc.)


2. How to use the Standard Library's classes and functions

The Standard Library comes with your C++ compiler. There are also other libraries
made by third-party developers that you can use.

💡 Software Tips

• 🧱 Tip 1: Use building blocks


Don’t “reinvent the wheel.” Use existing code (from libraries) when possible.
This is called software reuse, and it's a key part of object-oriented
programming.
• 🧱 Tip 2: Where your code comes from
When writing C++ programs, you'll often use:
o Classes/functions from the Standard Library
o Classes/functions you or your team create
o Classes/functions from third-party libraries

🎯 Why not write everything yourself?

• Pro: You understand it completely.


• Con: It takes more time and effort to build and maintain.

⚙ Performance Tip : Using Standard Library code is usually faster and more
efficient, because it's already optimized.
🌍 Portability Tip : Using the Standard Library makes your code portable (works on
different systems), since all C++ compilers include it.

15.5 Header Files (Simplified)

The C++ Standard Library is split into many parts. Each part has its own header
file.

🔹 What is a header file?

• A header file tells the compiler:


o What functions are available
o What classes and types exist
o What constants you can use

It’s like a guide that helps your program understand how to connect with existing
tools from the library or from other code.

✅ Example

To use input/output features like std::cout, you include:

#include <iostream>

⚠ Note on .h Files Older C++ used header files like:

#include <iostream.h>

These “.h” headers are outdated. Modern C++ uses headers without .h, like
<iostream> C++ Standard Library Headers :-
🛠 Custom Header Files in C++

You can create your own header files to organize and reuse your code
(like functions or class definitions).

🔹 How to name them:

• Use the .h extension (example: square.h)

🔹 How to include them in your program:

Use #include with double quotes, like this:

#include "square.h"

This tells the compiler to look in your current project folder for
square.h.

✅ Why use custom headers?

• Keeps your code organized


• Makes it easier to reuse functions across multiple files
• Helps split large programs into smaller, manageable parts
🔹 What is an Inline Function?

An inline function is a small function whose code is inserted directly into where it's
called, instead of jumping to another location in memory.
This helps avoid the slight delay of calling a function—so it's faster, especially for
small, frequently used functions.

✅ Why Use It?

• Faster execution (less overhead from function calls).


• Good for very short functions.
• Saves time at runtime but might make the program a bit larger.

⚠ Important Points:

• Add the keyword inline before the function definition.


• Place the function before you use it in the program.
• Inline functions are often put in header files.

Example Code (Simplified):


15.7 C++ Keywords :-

In C++, keywords are special words that the programming language reserves for its
own use. These words have predefined meanings and cannot be used as identifiers
(like variable names or function names). Keywords are divided into different
categories based on their use and whether they are common between C and C++ or
specific to C++.

Here’s a simplified breakdown of the different types of keywords:

1. Keywords Common to C and C++

These keywords are used in both C and C++ programming languages, and they have
the same meaning in both. Some examples include:

• int (for integer variables)


• return (to return a value from a function)
• if (for conditional statements)
• for (for loops)

2. Keywords Unique to C++

These are keywords that are only used in C++, not in C. They were introduced to
support the new features in C++, such as object-oriented programming (OOP). Some
examples:

• class (used to define classes in C++)


• public, private (used to control access to class members)
• new (used for dynamic memory allocation)
• delete (used to deallocate memory)

3. Keywords Added in C++11

C++11 introduced some new keywords to support modern features like concurrency
and auto-type deduction. Some examples of these newer keywords:
• auto (lets the compiler automatically deduce the type of a variable)
• nullptr (a better way to represent a null pointer)
• constexpr (for constant expressions, used in more advanced programming)
• thread (used for multi-threading)

15.8 References and Reference Parameters

This section explains references and reference parameters in C++, which are ways
to pass arguments to functions more efficiently than pass-by-value. Let’s break it
down simply:

1. Pass-by-Value:

• In pass-by-value, when you pass an argument to a function, a copy of that


argument is created. Changes made to the copy do not affect the original
argument.
• Problem: For large data, copying the data takes time and uses memory, which
can be inefficient.

2. Pass-by-Reference:

• In pass-by-reference, instead of passing a copy of the argument, the function


gets access to the original data.
• Benefit: It avoids the overhead of copying large data and allows the function
to modify the original data.
• Risk: It can accidentally change the original data, which can lead to errors.

3. Reference Parameters:

• To pass an argument by reference, you use the & symbol in the function
declaration. This makes the parameter a reference (alias) to the argument,
meaning changes in the function affect the original variable.
• Example:
• void increase(int &x) {
• x++; // This modifies the original x from the caller
• }

4. Pass-by-Value vs. Pass-by-Reference:

• Pass-by-value: Copies the argument, and changes inside the function do not
affect the original data.
• Pass-by-reference: Allows the function to directly modify the original data.
5. Using References for Efficiency:

• When you pass large objects (like arrays or large structs), passing them by
reference (instead of copying them by value) is more efficient.
• You can also pass a constant reference (using const &), which allows for
passing large objects without modifying them and without the overhead of
copying.

6. References as Aliases:

• A reference can be used as an alias (another name) for a variable.


• Example:
• int count = 10;
• int &ref = count; // ref is an alias for count
• ref++; // This modifies count
• Once a reference is initialized, it cannot point to another variable. It's tied to
the original variable.

7. Returning References:

• Returning a reference from a function can be risky if it refers to a local


variable. Once the function ends, the local variable no longer exists, and the
reference becomes invalid (a dangling reference).
• To safely return a reference, the variable should be static or exist outside
the function.

8. Common Errors:

• Uninitialized References: If you don’t initialize a reference when you declare


it, it causes an error.
• Reassigning a Reference: You can’t change what a reference points to once
it’s initialized.
• Returning a Reference to a Local Variable: Returning a reference to a local
variable causes a logic error since the variable will no longer exist once the
function ends.

9. Error Messages:

• Compilers will give different error messages if you do something wrong with
references, such as not initializing them or returning references to local
variables.
In Summary:

• References allow you to pass arguments by reference (so the function can
modify the original data), and they are more efficient than copying large
data.
• Using references carefully is important to avoid unwanted changes to the
data and errors like dangling references.

15.9 Empty Parameter Lists

In C++, functions can be defined without parameters. There are two ways to define
a function with no parameters:

1. Using void:
2. void print(void);

This indicates that the function print does not take any arguments and does
not return a value.

3. Using empty parentheses:


4. void print();

This also means that the function print takes no arguments.

Both of these are equivalent in C++.

Key Points:

• In C++, an empty parameter list means the function does not accept any
arguments.
• In C, an empty parameter list means that no argument checking is done, and
the function can accept any arguments. This is different from C++ behavior,
which expects no arguments when the list is empty.

Portability Tip:

• C programs that use an empty parameter list might cause errors when
compiled in C++ because C++ expects that the function has no parameters,
whereas C allows for any parameters to be passed without checking.

You might also like