Introduction to C++ An object-oriented language Unit - 01.
-
Upload
brianna-davidson -
Category
Documents
-
view
225 -
download
2
Transcript of Introduction to C++ An object-oriented language Unit - 01.
Introduction to Introduction to C++C++
An object-oriented languageAn object-oriented language
Unit - 01Unit - 01
2
Unit IntroductionUnit Introduction
This unit covers the basics of C++ This unit covers the basics of C++ languagelanguage
3
Unit ObjectivesUnit Objectives
After covering this unit you will After covering this unit you will understand…understand…
Introduction to C++Introduction to C++ Program structure in C++Program structure in C++ Data typesData types Specifiers and modifiers Specifiers and modifiers Scope and storage allocationScope and storage allocation OperatorsOperators FunctionsFunctions
4
IntroductionIntroduction
‘‘B’ languageB’ language ‘‘B’ expanded to ‘C’ languageB’ expanded to ‘C’ language The ‘C++’ programming languageThe ‘C++’ programming language
5
Header Files (.h)Header Files (.h)
An interface of an implementation to An interface of an implementation to the clientthe client
Main contents of a header fileMain contents of a header file Declarations of classes and structuresDeclarations of classes and structures Other header files or libraries to be Other header files or libraries to be
includedincluded Global variablesGlobal variables
6
Source Files (.cpp)Source Files (.cpp)
In general, implementation of the In general, implementation of the interface part (declared in .h file)interface part (declared in .h file)
.cpp file can also contain header file .cpp file can also contain header file contentscontents
Main contents of a source fileMain contents of a source file Implementation of class (and/or Implementation of class (and/or
structure) declared in header filestructure) declared in header file Can also have a main(), an entry point Can also have a main(), an entry point
to the executable programto the executable program
7
Executing C++ ProgramExecuting C++ Program
Search the included librariesSearch the included libraries Compile the related code into .obj Compile the related code into .obj
formform Link the complied code to an Link the complied code to an
executable codeexecutable code Execute the codeExecute the code
8
Hello World ProgramHello World Program// hello.cpp// hello.cpp
#include <iostream.h>#include <iostream.h>
#include “myfile.h”#include “myfile.h” // user defined header file// user defined header file
int gVariable = 100;int gVariable = 100; // global variables// global variables
void main () void main ()
{{
cout << “Hello World!”;cout << “Hello World!”; // printing Hello World on// printing Hello World on
// console// console
}}
9
NameSpacesNameSpaces
Solve naming problems in large Solve naming problems in large applicationsapplications
using and namespaceusing and namespace keywords are keywords are used to declare and define a name used to declare and define a name space e.g.space e.g.
using namespace std;using namespace std;
10
Example: NameSpacesExample: NameSpaces// create namespace 'NSfromAccount'// create namespace 'NSfromAccount'namespace NSfromAccount namespace NSfromAccount {{ int accountNumber = 2000;int accountNumber = 2000;};};
// create namespace 'NStoAccount'// create namespace 'NStoAccount'namespace NStoAccount namespace NStoAccount {{ int accountNumber = 3000;int accountNumber = 3000;};};
void main()void main(){{ // local variable // local variable int accountNumber = 100;int accountNumber = 100;
// using accountNumber of namespace 'NSfromAccount'// using accountNumber of namespace 'NSfromAccount' cout << NSfromAccount::accountNumber << endl; cout << NSfromAccount::accountNumber << endl;
11
Example: NameSpaces (contd.)Example: NameSpaces (contd.)
// using accountNumber of namespace 'NStoAccount'// using accountNumber of namespace 'NStoAccount' cout << NStoAccount::accountNumber << endl; cout << NStoAccount::accountNumber << endl;
// using local variable accountNumber// using local variable accountNumber cout << accountNumber << endl; cout << accountNumber << endl; }}
12
Data TypesData Types
Data Types provide a way you use a Data Types provide a way you use a memorymemory
Data Type have a storage size Data Type have a storage size associated with itassociated with it
C/C++ has the following data types:C/C++ has the following data types: charchar 8 bits 8 bits intint 16 bit 16 bit floatfloat single-precision single-precision double double-precisiondouble double-precision
13
Data Types (contd.)Data Types (contd.)
boolbool true/false statetrue/false state enumenum values given to values given to
symbols/meaningful wordssymbols/meaningful words
14
Example: Data TypesExample: Data Types#include <stdlib.h>#include <stdlib.h>
void main() void main()
{{
char characterVal = ‘a’;char characterVal = ‘a’;
int integerVal = 1;int integerVal = 1;
float floatVal = 2.3f;float floatVal = 2.3f;
double doubleVal = 3.567891;double doubleVal = 3.567891;
bool booleanVal = 1; bool booleanVal = 1; // true state// true state
enum ENumeratedVal = { ZERO, ONE, TWO };enum ENumeratedVal = { ZERO, ONE, TWO };
}}
15
SpecifiersSpecifiers
Specifiers modify the meaning of the Specifiers modify the meaning of the basic data typesbasic data types
Four types of specifiersFour types of specifiers longlong shortshort signedsigned unsignedunsigned
16
Specifiers (contd.)Specifiers (contd.)
Illegal specifier combinations are:Illegal specifier combinations are: long floatlong float short float short float short doubleshort double
17
Example: SpecifiersExample: Specifiers#include <stdlib.h>#include <stdlib.h>
void main() void main()
{{
int intVar = 10; int intVar = 10; // standard integer format// standard integer format
short int shortVar = 10; short int shortVar = 10; // takes less space// takes less space
short shortVar2 = 10; short shortVar2 = 10; // you may omit the int// you may omit the int
long int longVar = 10; long int longVar = 10; // takes more space than int// takes more space than int
long longVar2 = 10; long longVar2 = 10; // you may omit the int// you may omit the int
unsigned int uIntVar = 10; unsigned int uIntVar = 10; // no sign bit reserved// no sign bit reserved
signed int intVar2 = -10; signed int intVar2 = -10; // same as int (sign bit// same as int (sign bit // reserved by default)// reserved by default)
}}
18
ModifiersModifiers
Modifiers change the meaning, type, Modifiers change the meaning, type, scope or accessibility of the variable, scope or accessibility of the variable, function, structure or classfunction, structure or class
Modifiers supported by C/C++ are:Modifiers supported by C/C++ are: constconst staticstatic registerregister volatilevolatile friendfriend
19
Example: ModifiersExample: Modifiers#include <stdlib.h>#include <stdlib.h>
void main() void main()
{{
const int CONST_VAR = 10; const int CONST_VAR = 10;
// this variable’s value cannot be changed and is final// this variable’s value cannot be changed and is final
static char* s_StaticString = “Hello”; static char* s_StaticString = “Hello”;
/* this variable is available throughout the program/* this variable is available throughout the program
length and is equivalent to a global variable */length and is equivalent to a global variable */
volatile float volatileVar = 10.3; volatile float volatileVar = 10.3;
/* no compiler optimisation is done on the variable, as/* no compiler optimisation is done on the variable, as
‘ ‘volatile’, its value is supposed to change frequentlyvolatile’, its value is supposed to change frequently
friend requires class declaration, and will friend requires class declaration, and will
be discussed later in the training program */be discussed later in the training program */
}}
20
Scope and Storage Scope and Storage AllocationAllocation
Scope means where a variable can be Scope means where a variable can be accessibleaccessible
Storage allocation means the lifetime of Storage allocation means the lifetime of a variable and how the storage is a variable and how the storage is allocated by the compilerallocated by the compiler Global variablesGlobal variables Local variablesLocal variables Register variablesRegister variables Static variablesStatic variables External variablesExternal variables
21
Example: Variables with different scope and Example: Variables with different scope and lifetimelifetime
#include <iostream.h>#include <iostream.h>
int gVar1;int gVar1; // define global variable// define global variable
extern int geVar1;extern int geVar1; // declare an extern variable// declare an extern variable
static int sCount = 100;static int sCount = 100; // static global variable// static global variable
void f()void f()
{{
int x;int x; // local variable declaration// local variable declaration
x = 100;x = 100; // local variable definition// local variable definition
static int y = 200;static int y = 200; // local static variable// local static variable
cout << y++ << endl << x++ << gVar1++ << endl << geVar1++ << cout << y++ << endl << x++ << gVar1++ << endl << geVar1++ << endl << sCount++ << endl;endl << sCount++ << endl;
}}
int geVar1;int geVar1; // define an external variable// define an external variable
void main() void main()
{{
gVar1 = 300;gVar1 = 300;
f();f();
f();f();
}}
22
OperatorsOperators
Arithmetic Operators (+, -, *, /, =)Arithmetic Operators (+, -, *, /, =) Relational Operators (<, >, <=, >=, Relational Operators (<, >, <=, >=,
==, !=)==, !=) Logical Operators (&&, ||)Logical Operators (&&, ||) Bitwise Operators (&, |, ^, ~)Bitwise Operators (&, |, ^, ~) Shift Operators (<<, >>)Shift Operators (<<, >>) Unary Operators (-, ~)Unary Operators (-, ~) Ternary Operator (? :)Ternary Operator (? :)
23
Operators (contd.)Operators (contd.)
a = a < b ? b : a; a = a < b ? b : a; // this is equivalent to max operator// this is equivalent to max operator
Comma OperatorComma Operatora = (b++, c++, d++); a = (b++, c++, d++);
sizeofsizeof Operator Operatorcout << sizeof (long);cout << sizeof (long);
CastingCastinglong longVal = (long) intVal;long longVal = (long) intVal;
Operator PrecedenceOperator Precedence
24
Example: OperatorsExample: Operators#include <stdlib.h>#include <stdlib.h>
void main() void main()
{{
int a, b, c; int a, b, c; // declaration of variables// declaration of variables
b = 2;b = 2; // value assignment// value assignment
c = 3; c = 3;
a = (((b+c)*b)-c) / b;a = (((b+c)*b)-c) / b; // add, multiply, subtract// add, multiply, subtract
// etc.// etc.
if(((a < b) || (b >= c)) && (a > c)) if(((a < b) || (b >= c)) && (a > c)) // compare// compare
{ {
a = ~(b & ~c); a = ~(b & ~c);
}}
elseelse
{{
a >> b;a >> b; // a is right shifted b times// a is right shifted b times
cout << a;cout << a;
}}
25
Example: Operators Example: Operators (contd.)(contd.)
d = a;d = a;
a = a < b ? b : a; a = a < b ? b : a; // a is assigned the greater value // a is assigned the greater value // between a & b // between a & b
a = (b++, c++, d++); a = (b++, c++, d++); // comma and increment operations// comma and increment operations
long longVal = (long) a; long longVal = (long) a; // casting from int to long// casting from int to long
cout << sizeof(long); cout << sizeof(long); // displaying the size of long// displaying the size of long
} } // end main// end main
26
Type DefinitionType Definition
typedef suggests ‘type definition’ typedef suggests ‘type definition’ name aliasingname aliasing is a more accurate is a more accurate
descriptiondescriptiontypedef int* IntPtrType;typedef int* IntPtrType;
IntPtrType px, py; IntPtrType px, py; // p represents pointer type// p represents pointer type
Here int* is aliased to IntPtrTypeHere int* is aliased to IntPtrType
27
FunctionsFunctions
Functions have Functions have parametersparameters processingprocessing return valuesreturn values
Functions perform operations on the Functions perform operations on the parameters passed to it and returns a parameters passed to it and returns a value e.g.value e.g.returnVal FunctionName (functionParameters) returnVal FunctionName (functionParameters)
{{
// perform some operations on parameters passed// perform some operations on parameters passed
return returnVal;return returnVal;
}}
28
Parameter PassingParameter Passing
Parameters can be passed to a Parameters can be passed to a function in following waysfunction in following ways By ReferenceBy Reference By ValueBy Value
29
Example: FunctionExample: Function#include <stdlib.h>#include <stdlib.h>
void ByValue(int intVar) void ByValue(int intVar)
{{
intVar = 9; intVar = 9; // passed as 5, and changes to 9 locally// passed as 5, and changes to 9 locally
}}
void ByReference(int& intVar) void ByReference(int& intVar)
{{
intVar = 5;intVar = 5;
}}
void main() void main()
{{
int j = 2;int j = 2;
ByReference(j); ByReference(j); // j changes to 5// j changes to 5
ByValue(j); ByValue(j); // j remains at 5// j remains at 5
cout << j; cout << j; // displays 5// displays 5
}}
30
Unit SummaryUnit Summary
In this unit you have covered …In this unit you have covered … Introduction to C++Introduction to C++ Program structure in C++ Program structure in C++ Data typesData types Specifiers and modifiers Specifiers and modifiers Scope and storage allocationScope and storage allocation OperatorsOperators FunctionsFunctions