[go: up one dir, main page]

0% found this document useful (0 votes)
47 views55 pages

An Overview of Object-Oriented Programming in C++

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 55

CST-1203

Programming in C++

Lecture 1
An Overview of Object-Oriented Programming in C++

Faculty of Computer Science 1


History

• C programming language by Dennis Ritchie at AT&T Bell Labs


(between 1969 ~ 1973)

• C++ by Bjarne Stroustrup in 1983

2
Faculty of Computer Science
Definitions of programming
• Conventional definitions
 A plan for solving a problem on a computer
 Specifying the order of a program execution
• modern programs often involve millions of lines of code
• manipulation of data is central

• Definition from another domain (academia)


 A … program is an organized and directed accumulation of resources
to accomplish specific … objectives …

• The definition we’ll use


 Specifying the structure and behavior of a program, and testing that
the program performs its task correctly and with acceptable
performance
• Never forget to check that “it” works
Faculty of Computer Science 3
just state
what the
machine is
to do

Faculty of Computer Science 4


Why is programming hard?
 We want “the machine” to do complex things
• Computers are nitpicking, unforgiving, dumb beasts
 The world is more complex than we’d like to believe
• So we don’t always know the implications of what we want

“Programming is understanding”
• When you can program a task, you understand it
• When you program, you spend significant time trying to
understand the task you want to automate

Programming is part practical, part theory


• If you are just practical, you produce non-scalable
unmaintainable hacks.
• If you are just theoretical, you produce toys.

Faculty of Computer Science 5


Program
• A precise sequence of steps to solve a particular problem.

Faculty of Computer Science 6


Software
• Software is a collection of programs running on some computer.
• Software == one or more programs

Faculty of Computer Science 7


People and Computers

• Computers
– built by people for the use of people.
– a very generic tool; use for an unimaginable range of tasks
– takes a program to make it useful to someone

Faculty of Computer Science 8


Computer Science

• The systematic study of computing systems and computation.


• The study of the theoretical foundations of information and
computation and their implementation and application in
computer systems.

Faculty of Computer Science 9


Programming Language

• A set of symbols, codes and words used to write a program


• An artificial languages created to tell the computer what to do
• Use vocabulary and a set of rules (grammar/syntax) to write
programs

Machine Fortran Assembly


Language
BASIC Language
COBOL
Visual Basic C and C++ Pascal
Smalltalk Ada
Faculty of Computer Science
Java 10
11
Programming Languages Types

12
Faculty of Computer Science
Compilers and Interpreters

• An interpreter translates source code one line at a time and executes


the instruction
– Example of an interpreted language: BASIC;
• A compiler is a program that changes source code to object code, all
in one shot.
– Example of a compiled language: C
13
Faculty of Computer Science
Computer are Everywhere

• Our civilization runs on software


– Most engineering activities involve software
• Computers and software play key roles
– Watches
– Ships
– Aircraft
– Telecommunications
– energy
– PC/tablet/workstation
– Medicine

Faculty of Computer Science 14


Screens and no screens
• Most programs do not run on things that look like a PC
– a screen, a keyboard, a box under the table

• Same model computer with different


I/O (input/output) systems
• Input systems are the four buttons
(more easily seen on the right-hand
watch)
• Radio receiver is used for
synchronization with very high-
precision “atomic” clocks.
• Most of the programs controlling these
two computers are shared between
them.

Faculty of Computer Science 15


Ships

 Monitoring
 Engine
• Design
 Hull design
• Construction
 Pumps
• Management

Faculty of Computer Science 16


Aircraft

 Signal processing
• Communication  “Gadget” control
• Control  Monitoring
• Display

Faculty of Computer Science 17


Phones

• Voice quality  Switching


• User interfaces  Reliability
• Billing
• Mobility  Provisioning
• Web browsing  Images

Faculty of Computer Science 18


Energy

• Control  Communications
• Monitoring  Visualization
• Analysis  Manufacturing
• Design

Faculty of Computer Science 19


Medicine

• the pulses they send out are controlled by a computer


• sophisticated algorithms are applied to recognize as a (three-
dimensional) image of the relevant part of a human body
• help steady the surgeon’s “hand” to allow for more delicate work
• a “robotic” system can be operated remotely

Faculty of Computer Science 20


PC/tablet/workstation

• There’s a lot more to computing than games, word processing,


browsing, and spreadsheets!

Faculty of Computer Science 21


Where is C++ Used?
• Just about everywhere

Mars rovers, animation, graphics, Photoshop, GUI, OS, compilers,


slides, chip design, chip manufacturing, semiconductor tools, etc.

Faculty of Computer Science 22


Structured Programming
• Dividing a program into functions and modules
• Limiting visibility of variables
• Structured programming languages - developed to improve
software development
o well-structured and organized
o forbid the use of goto statements
o use three fundamental control structures
» Sequence, Selection, Repetition

Faculty of Computer Science 23


Structured Design
• Structured programming implements structured design
• Three fundamental types of control structures:
 Sequence control structure – Instructions are executed in the
order in which they appear
 Selection control structures – The program branches to
different instructions depending on whether a condition is met;
IF…THEN…ELSE
 Repetition control structure – The program repeats the same
instructions over and over; DO-WHILE and DO-UNTIL

Faculty of Computer Science 24


What Can a Procedural Program
Do?
• A linear, procedural program is structured to instruct a
computer:
 Read Input
 Calculate
 Store data
 Write Output
 Work in a sequential progression (Sequence)
 Compare and branch (Selection)
 Iterate or Loop (Repetition)

Faculty of Computer Science 25


Problems with Structural
Programming
• Functions have unrestricted access to global data.
• Unrelated functions and data provide a poor model of the real
world.

Faculty of Computer Science 26


Structured programming
languages
• C
• C++ (structured/OO)
• PHP
• Ruby
• PERL
• Algol
• Pascal
• PL/I
• Ada

Faculty of Computer Science 27


Why C++ ?
• Precisely and comprehensively defined by an ISO standard
 Standard is almost universally accepted
 The most recent standard in ISO C++ 2014
• Available on almost all kinds of computers
• Programming concepts using C++ can be used fairly directly in
other languages
 C, Java, C#, and (less directly) Fortran

Faculty of Computer Science 28


Structure of a C+ + Program
• Programs are a sequence of instructions or statements.
• These statements form the structure of a C++ program.
• C++ program structure is divided into various sections,
namely, headers, class definition, member functions
definitions and main function.

Faculty of Computer Science 29


Typical C++ Environment
Program is created in
Editor Disk the editor and stored
on disk.

Preprocessor Preprocessor program


Disk
processes the code.
Compiler creates
Compiler Disk object code and stores
it on disk. Phases of C++ Programs:
Linker links the object  Edit
Linker Disk code with the libraries,  Preprocess
creates a.out and
Primary
stores it on disk  Compile
Memory
Loader  Link
 Load & Execute
Loader puts program
in memory.
Disk

Primary
Memory
CPU CPU takes each
instruction and
executes it, possibly
storing new data
.
values as the program 30
.
executes.
Faculty of Computer Science 31
Important Terms
• A source program (.cpp file type) consists of the program
statements comprising a C++ or other programming language
program.

• An object program (.obj file type) is the result of compiling


a source program.

• Header files (.h file type) contain constant, variable, and


function declarations needed by a program.

• An executable program is a program that can be run by a


computer.
Faculty of Computer Science 32
Important Terms
• Linking adds code from libraries to your file. Collects the
object code from all files in the workspace and puts them into
one executable program.

• A compiler is a program that translates a source program into


an object program.

• An interpreter is a program that translates individual source


program statements, one at a time, into executable statements.
Each statement is executed immediately after translation.

Faculty of Computer Science 33


A First Program
// …

int main() // main() is where a C++ program starts


{
cout << "Hello, world!\n"; // output the 13 characters Hello, world!
// followed by a new line
return 0; // return a value indicating success
}

// quotes delimit a string literal


// NOTE: “smart” quotes “ ” will cause compiler problems.
// make sure your quotes are of the style " "
// \n is a notation for a new line

Faculty of Computer Science 34


What is namespace?
• A namespace permits grouping of various entities like classes,
objects, functions and various C++ tokens, etc., under a single name.
– For example, both cout and cin , along with some useful tokens like endl, are
defined inside of std for use.

• Different users can create separate namespaces and thus can use
similar names of the entities.
• Avoids compile-time error that may exist due to identical-name
conflicts.
• In modern C++, all of the functionality in the C++ standard
library is now defined inside namespace std (short for standard).

Faculty of Computer Science 35


How to access entities of a
namespace?

• By specifying the using directive


using namespace std;
cout<<"Hello World";

• By specifying the full member name


std: :cout<<"Hello World";

• By specifying the using declaration


using std:: cout;
cout<<"Hello World"; 36
Statement styles
Modern C++ compilers
• As soon as the new-style header is included, its contents are
included in the std namespace.
#include<iostream>
using namespace std;
Old compilers
• May not support these statements.
• The statements are replaced by this single statement.
#include<iostream.h>

Faculty of Computer Science 37


A First Program – complete
// a first program:

#include <iostream> // get the library facilities needed for now


using namespace std;
int main() // main() is where a C++ program starts
{
cout << "Hello, world!\n"; // output the 13 characters Hello, world!
// followed by a new line
return 0; // return a value indicating success
}

// note the semicolons; they terminate statements


// braces { … } group statements into a block
// main( ) is a function that takes no arguments ( ) and returns an int (integer value)
to indicate success or failure

Faculty of Computer Science 38


Example 1: Hello World Program
Without using namespace std; Using namespace std;
• If you write for example cout <<;
you'd have to put std::cout <<;

#include <iostream> #include <iostream>


using namespace std;
int main() int main()
{ {
cout << "Hello World";
std::cout << "Hello World";
system("pause");
system("pause"); return 0;
return 0;
} }

39
Hello, world! Program
 Its purpose is to help you get used to your tools
• Compiler
• Program development environment
• Program execution environment
 Type in the program carefully
• After you get it to work, please make a few mistakes to see how the
tools respond; for example
 Forget the header
 Forget to terminate the string
 Misspell return (e.g., retrun)
 Forget a semicolon
 Forget { or }
 … 40
Compilation and Linking
C++ source code
C++ compiler
Object code

Executable program
linker
Library Object code

• Write C++ source code (in principle, human readable)


• The compiler translates source code into object code (sometimes called
machine code)
 Object code is simple enough for a computer to “understand”
• The linker links your code to system code needed to execute
 E.g., input/output libraries, operating system code, and windowing
code
• The result is an executable program
 E.g., a .exe file on windows or an a.out file on Unix
41
Linking
(.cpp file)
source code
compiler
(.h files)
(.obj file)
object code
linked to
libraries
object code from
other source files executable
file

Faculty of Computer Science 42


Hello, world! Program : Compilation and Linking

Faculty of Computer Science 43


Clear Output Screen
• Depends on compilers and Operating System, we can use one of
the following method depending on the compiler.
– Using clrscr() - For TurboC Compiler
– Using system("cls") - For TurboC Compiler
– Using system("clear") - For gcc/g++ compiler in Linux

• #include <cstdlib> (programming in C++)


• system("cls"); // (for windows)
• system("clear"); // (for GNU/Linux)
Example 2 ClearScreen

#include<iostream>
using namespace std;
int main()
{
cout<<"Hello World ! ! !\n";
system("pause");
system("cls");
}
Print numbers

#include <iostream> // for std::cout


int main()
{
std::cout << 4; // print 4 to c
onsole
return 0;
}

Faculty of Computer Science 46


• To print more than one thing on the same line, the insertion
operator (<<) can be used multiple times in a single statement to
concatenate (link together) multiple pieces of output.

#include <iostream> // for std::cout


int main()
{
std::cout << "Hello" << " world!";
return 0;
}

Faculty of Computer Science 47


What would you expect this
program to print?

#include <iostream> // for std::cout


int main()
{
std::cout << "Hi!";
std::cout << "My name is Alex.";
return 0;
}

Faculty of Computer Science 48


std::endl
• To print separate lines of output to the console
• To tell the console when to move the cursor to the next line.
• Two jobs:
– it moves the cursor to the next line
– it “flushes” the output (makes sure that it shows up on the screen
immediately)
#include <iostream> // for std::cout and std::endl
int main()
{
std::cout << "Hi!" << std::endl;
std::cout << "My name is Alex." << std::endl;
return 0;
}
‘\n’ character moves the cursor to the next line, but doesn’t do the redundant
flush, so it performs better.
Faculty of Computer Science 49
Terms that you need to understand

// #include
<< library
C++ linker
comment main()
compiler object code
compile-time error output
cout program
executable source code
function statement
header IDE

Faculty of Computer Science 50


Exercises

• Change the program to output the two lines


Hello, programming!
Here we go!

Faculty of Computer Science 51


/*
* Compute the factorial of n, with n=20. Run the program and
* n! = 1*2*3*...*n observe the output
*/ produced:
#include <iostream>
using namespace std;
int main() {
The Factorial of 20 is -
int n = 20; // To compute factorial of n 2102132736
int factorial = 1; // Initialize the product to 1
int i = 1;
while (i <= n) {
factorial = factorial * i;
i++;
}
cout << "The Factorial of " << n << " is " << factorial << endl;
return 0;
}
Faculty of Computer Science 52
References
• Bjarne Stroustrup, “Programming: Principles and Practice Using C++”, Second Edition,
First printing, May 2014
• Robert Lafore, Object-Oriented Programming in C++, Fourth Edition, First Printing:
December 2001
• Joyce Farrell, Object-Oriented Programming Using C++, Fourth Edition, © 2009 Course
Technology, Cengage Learning
• http://ecomputernotes.com/cpp/introduction-to-oop/structure-of-a-cpp
• https://www.learncpp.com/cpp-tutorial/introduction-to-iostream-cout-cin-and-endl/

Faculty of Computer Science 53


A Second Program
// modified for Windows console mode:

#include <iostream> // get the facilities for this course

int main() // main() is where a C++ program starts


{
cout << "Hello, world!\n"; // output the 13 characters Hello, world!
// followed by a new line
keep_window_open(); // wait for a keystroke
return 0; // return a value indicating success
}

// without keep_window_open() the output window will be closed immediately before


you have a chance to read the output (on Visual C++ 20xx)
// Defined keep_window_open() in std_lib_facilities.h to simplify writing simple text
programs
// If not, download it from our support site www.stroustrup.com/Programming.

Faculty of Computer Science 54


keep_window_open()
• #include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { char ch;
cin>>ch; }
• #include "std_lib_facilities.h"

Faculty of Computer Science 55

You might also like