0% found this document useful (0 votes)
151 views

Introduction To C++: An Object - Oriented Language

C++ is a hybrid object-oriented language that is a superset of C. It was created by Bjarne Stroustrup at Bell Labs in the 1980s. C++ allows both procedural and object-oriented programming. Key concepts in C++ include data encapsulation, abstraction, inheritance, polymorphism, and exception handling. A C++ program goes through phases of editing, preprocessing, compiling, linking, loading, and executing.

Uploaded by

abhimnnit
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
151 views

Introduction To C++: An Object - Oriented Language

C++ is a hybrid object-oriented language that is a superset of C. It was created by Bjarne Stroustrup at Bell Labs in the 1980s. C++ allows both procedural and object-oriented programming. Key concepts in C++ include data encapsulation, abstraction, inheritance, polymorphism, and exception handling. A C++ program goes through phases of editing, preprocessing, compiling, linking, loading, and executing.

Uploaded by

abhimnnit
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

Introduction to C++

An Object – Oriented Language


C++
A superset of C
As an Object-Oriented Programming Language
Hybrid language
C-like style
Object-oriented style
Both

Created by Bjarne Stroustrup at Bell Labs in the 1980's and called C with
Classes.
Inherit all ANSI C directives
Inherit all C functions
You don’t have to write OOP programming in C++
Example :
// This program outputs the message
//
// Hello!
//
// to the screen

#include <iostream.h>

int main()
{
cout <<"Hello!"<< endl;
return 0;
}
Program: Average
#include <iostream>
using namespace std;

int main() {
int x;
int y;
cout <<"Enter two numbers \n";
cin >> x >> y;
cout <<"Their average is: ";
cout << (x + y)/2.0 << endl;
return 0;
}
Useful Concepts in C++
Data Encapsulation
Data Abstraction
Inheritance
Polymorphism
Operator overloading
Function templates
Virtual functions
Exception Handling
Phases of C++ Programs
Program is created in
1. Edit Editor Disk
the editor and stored
on disk.
Preprocessor Disk Preprocessor program
2. Preprocess processes the code.
Compiler creates
Compiler Disk object code and stores

3. Compile Linker
it on disk.
Linker links the object
Disk code with the libraries,
creates a.out and
4. Link Loader
Primary
Memory
stores it on disk

5. Load Disk ..
Loader puts program
in memory.
..
..

6. Execute Primary
Memory
CPU
CPU takes each
instruction and
executes it, possibly
.. storing new data
..
.. values as the program
executes.
Parts of a C++ Program
// sample C++ program comment

#include <iostream> preprocessor directive

using namespace std; which namespace to use


int main() beginning of function named main
{ beginning of block for main
cout << "Hello,
output statement
there!";
return 0; send 0 back to operating system
} end of block for main
Basics of a Typical C++ Environment
Input/output
cin
• Standard input stream
• Normally keyboard
cout
• Standard output stream
• Normally computer screen
cerr
• Standard error stream
• Display error messages
Stream Input/Output

Keyboard, Stream Input


Hello, World!
Disk file, etc.

Stream Output Video display,


Hello, World! Disk file, etc.
New I/O library
iostream header file library
#include <iostream> // No “.h” in front of standard
headers
using namespace std; // To prevent “std::” before
everything
contains definitions for several classes
istream, ostream, fstream, ios
and their associated objects
cin, cout, cerr, clog
Basic C++ Extension from C
Comments
/* You can still use the old comment style, */
/* but you must be // very careful about mixing them
*/
// It's best to use this style for 1 line or partial
lines
/* And use this style when your comment
consists of multiple lines */
cin and cout (and #include <iostream.h>)
cout << "hey";
char name[10];
cin >> name;
cout << "Hey " << name << ", nice name." << endl;
cout << endl; // print a blank line
Declaring variables almost anywhere
// declare a variable when you need it
for (int k = 1; k < 5; k++){
cout << k;
Some C++ Extensions to C
// Single Line Source Code Comments
Inline Functions
Function overloading
Reference parameters
Some New Operators in C++
>> Extraction Operator extracts data from input stream.

<< Insertion Operator inserts data into output stream.

:: Scope Resolution Operator used to:


1. Override the default scope of variables.
2. Specify the scope of member functions.
C++ - Advance Extension
C++ allows function overloading
In C++, functions can use the same names, within the
same scope, if each can be distinguished by its name and
signature.

The signature specifies the number, type, and order of the


parameters expressed as a comma separated list of
argument types.
OO Perspective
Let's look at the Rectangle through object oriented eyes:
Define a new type Rectangle (a class)
Data
• width, length
Function
• area()
Create an instance of the class (an object)
Request the object to return its area

In C++, rather than writing a procedure, we define a


class that encapsulates the knowledge necessary to
answer the question - here, what is the area of the
rectangle.
Sections of a class
Private
Public
Protected
Example Code
class Rectangle int area()
{ {
private: return width*length;
int width, length; }
public:
}
Rectangle(int w, int l)
main()
{
{
width = w; Rectangle rect(3,5);
length = l; cout<<rect.area()<<endl;
} }
Encapsulation
class Circle class Triangle
{ {
private: private:
int radius int a, b, c;
public: public:
Circle(int radius); Triangle (int a, int b, int c);

// The area of a circle // The area of a triangle


int area(); int area();
}; };
Tokens in C++
The smallest individual units in a program are
known as tokens. C++ has the following
tokens:
Keywords
Identifiers
Constants
Strings
Operators
Cont…
Keywords are explicitly reserved identifiers and
cannot be used as names for the program variables
or other user-defined program elements.
Identifiers refer to the names of variables,
functions, arrays, classes, etc. created by the
programmer.
Constants refer to fixed values that do not change
during the execution of a program.
Literal constants include integers, characters,
floating point numbers and strings. They don not
have memory locations.
Cont…
Variable names
Correspond to actual locations in computer's memory
Every variable has name, type, size and value
When new value placed into variable, overwrites
previous value
Reading variables from memory nondestructive
Constants and Type bool
Example of constants
const int size = 20;
double a[size];

Example of bool variable


bool flag;
flag = ( 3 < 5 );
cout << flag << endl;
cout << boolalpha << flag << endl;
const vs. #define
#define
no ;
C-style of naming constants goes here
#define NUM_STATES 50
Interpreted by pre-processor rather than
compiler
Does not occupy a memory location like a
constant variable defined with const
Instead, causes a textual substitution to occur. In
above example, every occurrence in program of
NUM_STATES will be replaced by 50
Multiple and Combined Assignment

The assignment operator (=) can be used >


1 time in an expression
x = y = z = 5;
Associates right to left
x = (y = (z = 5));
Done Done Done
3rd 2nd 1st
Basic data types
User-defined data types
Structure
Union
Class
Enumeration
Built-in type
Integral type (int, char)
Void
Floating type (float, double)
Derived type
Array
Function
Pointer
reference
Header Files
Header files are used for declarations.
Header files can be included for using their
corresponding .cpp files.
Header files can be included in a nested
structure.
Standard C header files have been renamed and
placed in namespaces.
e.g. <cstdlib>, <cctype>, etc.
Implicit Type Conversion
Operations are performed between operands of the
same type.
If not of the same type, C++ will automatically
convert the lower type to the higher type of the two.
This can impact the results of calculations.
Hierarchy of Data Types
Highest long double
double
float
unsigned long
long
unsigned int
Lowest int
Ranked by largest number they can hold
Type Coercion
Coercion: automatic conversion of an operand to
another data type
Promotion: converts to a higher type
usually automatic in C

Demotion: converts to a lower type


usually requires explicit casting
Coercion Rules
1. char, short, unsigned short are automatically
promoted to int.

2. When operating on values of different data types, the


lower one is promoted to the type of the higher one.

3. When using the = operator, the type of expression on


right will be converted to type of variable on left.
Explicit Type Conversion
Also called type casting
Used for manual data type conversion
Format
static_cast<type>(expression)
Example:
cout << static_cast<char>(65);
// Displays 'A'
More Type Casting Examples
char ch = 'C';
cout << ch << " is stored as "
<< static_cast<int>(ch);

gallons = static_cast<int>(area/500);

avg = static_cast<double>(sum)/count;
Older Type Cast Styles
double Volume = 21.58;
int intVol1, intVol2;
intVol1 = (int) Volume; // C-style
// cast
intVol2 = int (Volume); //Prestandard
// C++ style
// cast

static_cast is current standard


Overflow and Underflow
Occurs when assigning a value that is too large (overflow) or
too small (underflow) to be held in a variable.
Variable contains value that is ‘wrapped around’ the set of
possible values.

// Create a short int initialized to


// the largest value it can hold
short int num = 32767;

cout << num; // Displays 32767


num = num + 1;
cout << num; // Displays -32768
Handling Overflow and Underflow
Different systems handle the problem differently.
They may
display a warning / error message
display a dialog box and ask what to do
stop the program
continue execution with the incorrect value

Advanced programs can enable a trap on overflow


Scope resolution operator (::)
It is used to access the global variable or the
variable or with which the scope of variable
is attached.
It is also used to define the scope of a
member function to its class. (discussed
later)
Example
int a=10;
void main(){
{
int a=20;
{
Int a=30;
Cout<<“the value of a is :”<<a;
Cout<<“the global value of a is :”<<::a;
}
Cout<<“the value of a is :”<<a;
Cout<<“the value of a is :”<<::a;
}
Cout<<“the value of a is :”<<a;
}
Cont…
Output
30
10
20
10
10

You might also like