Introduction to C++
C++ is a general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming.
C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features.
C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the early 1980's, and is based on the C language. The "++" is a syntactic construct used in C (to increment a variable), and C++ is intended as an incremental improvement of C. Most of C is a subset of C++, so that most C programs can be compiled (i.e. converted into a series of low-level instructions that the computer can execute directly) using a C++ compiler.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of object-oriented development:
- Encapsulation
- Data hiding
- Inheritance
- Polymorphism
Use of C++
- C++ is used by hundreds of thousands of programmers in essentially every application domain.
- In Adobe Systems All major applications are developed in C++: Photoshop & ImageReady, Illustrator, Acrobat, InDesign, GoLive
- C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts.
- Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++.
- Amazon.com, Facebook, Google, HP, IBM, Microsoft, Mozilla, Nokia & many more companies uses C++ language.
Advantages and Disadvantages:
Advantages
1. vendor-neutral: the C++ standard is the same in any platform or compiler
2. industrial (as opposed to academic): evolved to satisfy the needs of software engineers, not computer scientists
3. efficient. Compiles into highly optimized CPU-specific machine code with little or no runtime overhead.
4. multi-paradigm: allows the use and penalty-free mixing of procedural, OOP, generic programming, functional programming, etc
5. strictly statically typed (unlike Python for example): a large amount of logic (and sometimes even calculations) can be proved and performed at compile time, by the type checking/inferring system.
6. has deterministic memory management (as opposed to Java, C#, and other languages with garbage collectors): the life time of every object is known with absolute precision, which makes destructors useful and RAII possible.
Disadvantages
1. very complex! The learning curve is steep and takes a long time to climb, especially for those who know C or C# or other superficially similar languages
2. has the concept of "undefined behavior" (just like C) -- a large class of errors that neither compiler nor the runtime system is required to diagnose.
3. has some design flaws, although they are largely fixed by boost libraries and the new language standard.
4. lacks network and async I/O, graphics, concurrency, serialization, and many other facilities expected of modern languages, although that is also largely fixed by boost libraries and (as far as concurrency is concerned) the new language standard.
Structure of Program:
/* This Program prints Hello World on screen */
#include <iostream.h>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
1 . /* This program ... */
The symbols/* and*/ used for comment. This Comments are ignored by the compiler, and are used to provide useful information about program to humans who use it.
2. #include <iostream.h>
This is a preprocessor command which tells compiler to include iostream.h file.
3. using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library.
4. main()
C++ programs consist of one or more functions. There must be one and only one function called main. The brackets following the word main indicate that it is a function and not a variable.
5. { }
braces surround the body of the function, which may have one or more instructions/statements.
6. Cout<<
it is a library function that is used to print data on the user screen.
7. ''Hello World'' is a string that will be displayed on user screen
8. ; a semicolon ends a statement.
9. return 0; return the value zero to the Operating system.
Variables:
A variable in C++ is a name for a piece of memory that can be used to store information.
There are many types of variables, which determines the size and layout of the variable's memory;
Variable Names
we can use any combination of letters and numbers for Variable and function names but it must start with a letter.
We can use Underscore (_) as a letter in variable name and can begin with an underscore But Identifiers beginning with an underscore are reserved, And identifiers beginning with an underscore followed by a lower case letter are reserved for file scope identifiers Therefore using underscore as starting letter is not desirable.
Akki and akki are different identifiers because upper and lower case letters are treated as different identifiers
Variable Types
There are many 'built-in' data types in C.
short int -128 to 127 (1 byte)
unsigned short int 0 to 255 (1 byte)
char 0 to 255 or -128 to +127 (1 byte)
unsigned char 0 to 255 (1 byte)
signed char -128 to 127 (1 byte)
int -32,768 to +32,767 (2 bytes)
unsigned int 0 to +65,535 (2 bytes)
long int -2,147,483,648 to +2,147,483,647 (4 bytes)
unsigned long int 0 to 4,294,967,295 (4 bytes)
float single precision floating point (4 bytes)
double double precision floating point (8 bytes)
long double extended precision floating point (10 bytes)
Definition, Declaration & Initialization
Definition is the place where variable is created (allocated storage).
Declaration is a place where nature (type) of variable is stated, but no storage is allocated.
Initialization means assigning a value to the variable.
Variables can be declared many times, but defined only once. Memory space is not allocated for a variable while declaration. It happens only on variable definition.
Variable declaration
syntax
data_type variable_name;
example
int a, b, c;
char flag;
Variable initialization
syntax
data_type variable_name = value;
example
int a = 50;
char flag = 't';
external and static
initialisation done once only.
auto and register
initialisation done each time block is entered.
external and static variables cannot be initialised with a value that is not known until run-time; the initialiser must be a constant expression.
A variable that has not been assigned a value is called an uninitialized variable. Uninitialized variables are very dangerous because they cause intermittent problems (due to having different values each time you run the program). This can make them very hard to debug.
Variables Scope:
refers to where variables is declared.
It can be Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters or Outside of all functions which is called global variables.
Global variables
Global variable are declared outside any functions, usually at top of program. they can be used by later blocks of code:
int g; //global
int main(void)
{
g = 0;
}
Local variables
Variables that are declared inside a function or block are local variables.The scope of local variables will be within the function only.These variables are declared within the function and can't be accessed outside the function.
void main()
{
int g; //local
g=2;
cout << g;
}
Constants:
Constants refer to fixed values in the code that you can't change and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer literals, Floating-Pointliterals, Strings, Characters and Boolean Values.
Integer literals
An Integer literal can be a decimal, octal, or hexadecimal constant.
A prefix specifies the base or radix: 0x or 0X forhexadecimal, 0 for octal, and nothing for decimal.
Example
45 //decimal
0213 //octal
0x4b //hexadecimal
Floating-point literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You canrepresent floating point literals either in decimal form or exponential form.
Example
3.14159
314159E-5L
Boolean literals
There are two Boolean literals and they are part of standard C++ keywords:
A value of true representing true.
? A value of false representing false.
You should not consider the value of true equal to 1 and value of false equal to 0.
Character literals
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g.,'\u02C0').
Escape sequence & Meaning
There are several character escape sequences which can be used in place of a character constant or within a string.
\a alert (bell)
\b backspace
\f formfeed
\n newline
\r carriage return
\t tab
\v vertical tab
\ backslash
\? question mark
\' quote
\'' double quote
\ooo character specified as an octal number
\xhh character specified in hexadecimal
String literals
String literals are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separate them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, ""d""ear"
Defining Constants
There are two ways in C++ to define constants:
* Using #define preprocessor.
* Using const keyword.
The #define Preprocessor:
Following is the form to use #define preprocessor to define a constant:
#define identifier value
Example:
#include <iostream>
using namespace std;
#define WIDTH 5
#define LENGTH 10
The const Keyword:You can use const prefix to declare constants with a specific type as follows:
const type variable = value;
Example:
#include&ly;iostream>
using namespace std;
int main()
{
const int LENGTH =10;
const int WIDTH =5;
}
Variables storage classes:
The default class. Automatic variables are local to their block. Their storage space is reclaimed on exit from the block.
register
If possible, the variable will be stored in a processor register. May give faster access to the variable. If register storage is not possible, then the variable will be of automatic class.
Use of the register class is not recommended, as the compiler should be able to make better judgement about which variables to hold in registers, in fact injudicious use of register variables may slow down the program.
static
On exit from block, static variables are not reclaimed. They keep their value. On re-entry to the block the variable will have its old value.
extern
Allows access to external variables. An external variable is either a global variable or a variable defined in another source file. External variables are defined outside of any function. (Note: Variables passed to a function and modified by way of a pointer are not external variables)
static external
External variables can be accessed by any function in any source file which make up the final program. Static external variables can only be accessed by functions in the same file as the variable declaration.
Operators:
An operator is a symbol. Compiler identifies Operator and performs specific mathematical or logical operation.C provides following operators :
# Arithmetic Operators
# Logical Operators
# Increment and Decrement Operators
# Relational Operators
# Cast Operators
# Bitwise Operators
# Assignment Operators
# Misc
Arithmetic Operators
* multiplication
/ division
% remainder after division (modulo arithmetic)
+ addition
- subtraction and unary minus
Logical Operators
&& Called Logical AND operator. If both the operands are non-zero, then condition becomes true.
|| Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.
Increment and Decrement Operators
Increment and decrement operators are used to add or subtract 1 from the current value of oprand.
++ increment
-- decrement
Increment and Decrement operators can be prefix or postfix. In the prefix style the value of oprand is changed before the result of expression and in the postfix style the variable is modified after result.
For eg.
a = 9;
b = a++ + 5; /* a=10 b=14 */
a = 9;
b = ++a + 5; /* a=10 b=15 */
Relational Operators
== equal.
!= Not equal.
> < Greater than/less than
>= greater than or equal to
<= less than or equal to
Cast Operators
Cast operators are used to convert a value from one to another type.
(float) sum; converts type to float
(int) fred; converts type to int
Bitwise Operators
Bitwise operators performs operation on actual bits present in each byte of a variable. Each byte contain 8 bits, each bit can store the value 0 or 1
~ one's complement
& bitwise AND
^ bitwise XOR
| bitwise OR
<< left shift (binary multiply by 2)
>> right shift (binary divide by 2)
Assignment Operators
= assign
+= assign with add
-= assign with subtract
*= assign with multiply
/= assign with divide
%= assign with remainder
>>= assign with right shift
<<= assign with left shift
&= assign with bitwise AND
^= assign with bitwise XOR
|= assign with bitwise OR
For example,
a = a + 64; is same as
a += 64;
Misc
sizeof
The sizeof operator returns the size, in bytes, of a type or a variable.
You can compile and run the following program to find out how large your data types are:
cout << "bool:\t\t" << sizeof(bool) << " bytes";
bool: 1 bytes
Condition ? X : Y
Condition operator: If Condition is true ? then it returns value X : otherwise value Y
,
Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list
. (dot) and -> (arrow)
Member operators are used to reference individual members of classes, structures, and unions.
& Pointer operator: & returns the address of an variable. For example &a; will give actual address of the variable.
*Pointer operator: * is pointer to a variable. For example *var; will pointer to a variable var.
Arrays:
Array is a fixed size collection of similar data type items. Arrays are used to store and access group of data of same data type.
Arrays can of any data type. Arrays must have constant size. Continuous memory locations are used to store array.
It is an aggregate data type that lets you access multiple variables through a single name by use of an index. Array index always starts with 0.
Example for Arrays:
int a[5]; // integer array
char a[5]; // character(string) array
In the above example, we declare an array named a. When used in an array definition, the subscript operator ([]) is used to tell the compiler how many variables to allocate. In this case, we’re allocating 5 integers/character. Each of these variables in an array is called an element.
Types of Arrays:
# One Dimensional Array
# Two Dimensional Array
# Multi Dimensional Array
1 One Dimensional Array
Array declaration
int age [5];
Array initialization
int age[5]={0, 1, 2, 3, 4, 5};
Accessing array
age[0]; /*0_is_accessed*/
age[1]; /*1_is_accessed*/
age[2]; /*2_is_accessed*/
2 Two Dimensional Array
Two dimensional array is combination of rows n columns.
Array declaration
int arr[2][2];
Array initialization
int arr[2][2] = {{1,2}, {3,4}};
Accessing array
arr [0][0] = 1;
arr [0][1] = 2;
arr [1][0] = 3;
arr [1][1] = 4;
3 Multi Dimensional Array
C++ programming language allows programmer to create arrays of arrays known as multidimensional arrays.
For example:
float a[2][4][3];
Pointer to an array
Please go through pointers chapter first to understand this
An array name is a constant pointer to the first element of the array. Therefore, in the declaration:
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance:
double *p;
double balance[10];
p = balance;
It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].
Passing Array To Function
We can pass entire Arrays to functions as an argument.
For eg.
#include
void display(int a)
{
int i;
for(i=0;i < 4;i++){
cout << a[i];
}
}
int main(){
int c[]={1,2,3,4};
display(c);
//Passing array to display.
return 0;
}
Return array from functions
C++ does not allow to return an entire array as an argument to a function. However, You can return a pointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:
int * myFunction()
{
int c[]={1,2,3}
.
.
.
return c
}
Strings:
A string is simply an array of characters which is terminated by a null character '\0' which shows the end of the string.
Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.
This declaration and initialization create a string with the word "AKKI".
To hold the \0 (null character) at the end of the array, the size of array is one more than the number of characters in the word "AKKI".
char my_name[5] = {'A', 'K', 'K', 'I','\0'};
we can also write the above statement as follows:
char my_name[] = "AKKI";
C String functions
To use string functions programmer must import String.h header file.
String.h header file supports all the string functions in C language.
All the string functions are given below.
1 strcat ( ) Concatenates str2 at the end of str1.
2 strncat ( ) appends a portion of string to another
3 strcpy ( ) Copies str2 into str1
4 strncpy ( ) copies given number of characters of one string to another
5 strlen ( ) gives the length of str1.
6 strcmp ( ) Returns 0 if str1 is same as str2. Returns 0 if str1 > str2.
7 strcmpi ( ) Same as strcmp() function. But, this function negotiates case. ''A'' and ''a'' are treated as same.
8 strchr ( ) Returns pointer to first occurrence of char in str1.
9 strrchr ( ) last occurrence of given character in a string is found
10 strstr ( ) Returns pointer to first occurrence of str2 in str1.
11 strrstr ( ) Returns pointer to last occurrence of str2 in str1.
12 strdup ( ) duplicates the string
13 strlwr ( ) converts string to lowercase
14 strupr ( ) converts string to uppercase
15 strrev ( ) reverses the given string
16 strset ( ) sets all character in a string to given character
17 strnset ( ) It sets the portion of characters in a string to given character
18 strtok ( ) tokenizing given string using delimiter
Pointers:
Pointer is a variable that stores the address of another variable. They can make some things much easier, help improve your program's efficiency, and even allow you to handle unlimited amounts of data.
Pointer is used to allocate memory dynamically i.e. at run time.The variable might be any of the data type such as int, float, char, double, short etc.
Syntax :
To declare a pointer, we use an asterisk between the data type and the variable name
Pointers require a bit of new syntax because when you have a pointer, you need the ability to both request the memory location it stores and the value stored at that memory location.
data_type *ptr_name;
Example :
int *a; char *a;
Where, * is used to denote that ''a'' is pointer variable and not a normal variable.
In this context, the asterisk is not a multiplication
Key points to remember about pointers:
# Normal variable stores the value whereas pointer variable stores the address of the variable.
# The content of the pointer always be a whole number i.e. address.
# Always pointer is initialized to null, i.e. int *p = null.
# The value of null pointer is 0.
# & symbol is used to get the address of the variable.
# * symbol is used to get the value of the variable that the pointer is pointing to.
# If pointer is assigned to NULL, it means it is pointing to nothing.
# Two pointers can be subtracted to know how many elements are available between these two pointers.
# But, Pointer addition, multiplication, division are not allowed.
# The size of any pointer is 2 byte (for 16 bit compiler).
Since pointers only hold addresses, when we assign a value to a pointer, the value has to be an address. To get the address of a variable, we can use the address-of operator (&)
Example program for pointer:
#include
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
// prints address held in ptr, which is &q
cout << ptr;
/* display q's value using ptr variable */
cout << *ptr;
return 0;
}
The null pointer
Sometimes we need to make our pointers point to nothing. This is called a null pointer. We assign a pointer a null value by setting it to address 0:int *ptr;
ptr = 0;
// assign address 0 to ptr
or simply
int *ptr = 0;
// assign address 0 to ptr
C++ Pointer Arithmetic
As you understood pointer is an address which is a numeric value; therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -.
Example :
ptr++;
ptr--;
ptr+21;
ptr-10;
If a char pointer pointing to address 100 is incremented (ptr++) then it will point to memory address 101
C++ Pointers vs Arrays
Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing.
int main ()
{
int var[3] = {1, 2, 3};
int *ptr;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
return 0;
}
this code will return :
1
2
C++ Pointer to Pointer
A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value.int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
}
this code will return
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000
No comments:
Post a Comment