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

INTRODUCTION C++

C++ is an object-oriented programming language developed in 1979 at Bell Labs. It supports features like encapsulation, inheritance, polymorphism, and data hiding. Keywords in C++ are reserved words that cannot be used as variable names. Comments in C++ start with /* and end with */. C++ supports basic data types like char, int, float, and more complex types like classes. Variables in C++ are defined by specifying their type and optionally initializing them. Operators in C++ perform arithmetic, relational, logical, and bitwise operations. Assignment operators assign values.

Uploaded by

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

INTRODUCTION C++

C++ is an object-oriented programming language developed in 1979 at Bell Labs. It supports features like encapsulation, inheritance, polymorphism, and data hiding. Keywords in C++ are reserved words that cannot be used as variable names. Comments in C++ start with /* and end with */. C++ supports basic data types like char, int, float, and more complex types like classes. Variables in C++ are defined by specifying their type and optionally initializing them. Operators in C++ perform arithmetic, relational, logical, and bitwise operations. Assignment operators assign values.

Uploaded by

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

INTRODUCTION :

C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell
Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

OBJECT-ORIENTED PROGRAMMING

C++ fully supports object-oriented programming, including the four pillars of object-
oriented development:

 Encapsulation
 Data hiding
 Inheritance
 Polymorphism

C++ KEYWORDS:

 The following list shows the reserved words in C++. These reserved words may not be
used as constant or variable or any other identifier names.

asm else new this


auto enum operator throw
bool explicit
private true
break export protected try
case extern public typedef
catch false register typeid
reinterpret_c typena
char float
ast me
class for return union
unsigne
const friend short
d
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
wchar_
do long struct
t
double mutable switch while
dynamic_c namespa
template
ast ce
COMMENTS IN C++

Program comments are explanatory statements that you can include in the C++ code that you write
and helps anyone reading it's source code. All programming languages allow for some form of
comments.

C++ comments start with /* and end with */. For example:

/* This is a comment */

/* C++ comments can also


* span multiple lines
*/
C++ DATA TYPES

While doing programming in any programming language, you need to use various variables to store
various information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.

Type Typical Bit Width Typical Range

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 0 to 65,535

signed short int Range -32768 to 32767

long int 4bytes -2,147,483,648 to 2,147,483,647


signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character

VARIABLE DEFINITION IN C++:

A variable definition means to tell the compiler where and how much to create the storage for the
variable.

Some examples are:

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

OPERATORS IN C++

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provides the following types of
operators:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.

ARITHMETIC OPERATORS:

There are following arithmetic operators supported by C++ language:

Assume variable A holds 10 and variable B holds 20, then:


Operator Description Example
+ Adds two operands A + B will give 30
Subtracts second operand from the
- A - B will give -10
first
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
Modulus Operator and remainder of
% B % A will give 0
after an integer division
Increment operator, increases integer
++ A++ will give 11
value by one
Decrement operator, decreases integer
-- A-- will give 9
value by one
RELATIONAL OPERATORS:

There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


Checks if the values of two operands
== are equal or not, if yes then condition (A == B) is not true.
becomes true.
Checks if the values of two operands
!= are equal or not, if values are not equal (A != B) is true.
then condition becomes true.
Checks if the value of left operand is
> greater than the value of right operand, (A > B) is not true.
if yes then condition becomes true.
Checks if the value of left operand is
< less than the value of right operand, if (A < B) is true.
yes then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition
becomes true.
Checks if the value of left operand is
less than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition becomes
true.
LOGICAL OPERATORS:

There are following logical operators supported by C++ language

Assume variable A holds 1 and variable B holds 0, then:


Operator Description Example
Called Logical AND operator. If both
&& the operands are non-zero, then (A && B) is false.
condition becomes true.
Called Logical OR Operator. If any of
|| the two operands is non-zero, then (A || B) is true.
condition becomes true.
Called Logical NOT Operator. Use to
reverses the logical state of its operand.
! !(A && B) is true.
If a condition is true, then Logical NOT
operator will make false.
BITWISE OPERATORS:

Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ are as follows:

pqp&qp|qp^q
000 0 0
010 1 1
111 1 0
100 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then:

Operator Description Example


Binary AND Operator copies a bit to
& (A & B) will give 12 which is 0000 1100
the result if it exists in both operands.
Binary OR Operator copies a bit if it
| (A | B) will give 61 which is 0011 1101
exists in either operand.
Binary XOR Operator copies the bit if
^ (A ^ B) will give 49 which is 0011 0001
it is set in one operand but not both.
Binary Ones Complement Operator is (~A ) will give -61 which is 1100 0011 in
~ unary and has the effect of 'flipping' 2's complement form due to a signed
bits. binary number.
Binary Left Shift Operator. The left
operands value is moved left by the
<< A << 2 will give 240 which is 1111 0000
number of bits specified by the right
operand.
Binary Right Shift Operator. The left
operands value is moved right by the
>> A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.
ASSIGNMENT OPERATORS:

There are following assignment operators supported by C++ language:

Operator Description Example


Simple assignment operator, Assigns
C = A + B will assign value of A + B into
= values from right side operands to left
C
side operand
Add AND assignment operator, It adds
+= right operand to the left operand and C += A is equivalent to C = C + A
assign the result to left operand
Subtract AND assignment operator, It
subtracts right operand from the left
-= C -= A is equivalent to C = C - A
operand and assign the result to left
operand
Multiply AND assignment operator, It
multiplies right operand with the left
*= C *= A is equivalent to C = C * A
operand and assign the result to left
operand
Divide AND assignment operator, It
divides left operand with the right
/= C /= A is equivalent to C = C / A
operand and assign the result to left
operand
Modulus AND assignment operator, It
%= takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
bitwise exclusive OR and assignment
^= C ^= 2 is same as C = C ^ 2
operator
bitwise inclusive OR and assignment
|= C |= 2 is same as C = C | 2
operator

MISC OPERATORS

There are few other operators supported by C++ Language.

Operator Description
sizeof operator returns the size of a variable. For example,
sizeof
sizeof(a), where a is integer, will return 4.
Conditional operator. If Condition is true ? then it returns
Condition ? X : Y
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.
Member operators are used to reference individual members of
. (dot) and -> (arrow)
classes, structures, and unions.
Casting operators convert one data type to another. For
Cast
example, int(2.2000) would return 2.
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.

C++ LOOP TYPES


There may be a situation, when you need to execute a block of code several number of times. In
general statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.

while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
for loop
Execute a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
do...while loop
Like a while statement, except that it tests the condition at the end of the loop body.
1.#include <iostream>
using namespace std;

int main ()
{
// Local variable declaration:
int a = 10;

// while loop execution


while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}

return 0;
}

2.#include <iostream>
using namespace std;

int main ()
{
// for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout << "value of a: " << a << endl;
}

return 0;
}

3.#include <iostream>
using namespace std;

int main ()
{
// Local variable declaration:
int a = 10;

// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );

return 0;
}
4. for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.

C++ DECISION MAKING STATEMENTS


Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.

IF STATEMENT
An if statement consists of a boolean expression followed by one or more statements.
IF...ELSE STATEMENT
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.

SWITCH STATEMENT
A switch statement allows a variable to be tested for equality against a list of values.
NESTED IF STATEMENTS
You can use one if or else if statement inside another if or else if statement(s).
NESTED SWITCH STATEMENTS

You can use one swicth statement inside another switch statement(s).

C++ ARRAYS
C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.

type arrayName [ arraySize ];


TWO-DIMENSIONAL ARRAYS:
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y, you would write something as follows:

datatype arrayName[ x ][ y ];

#include <iostream>
using namespace std;

int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

// output each array element's value


for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}

return 0;
}

C++ STRINGS
The C-style character string originated within the C language and continues to be supported within C+
+. This string is actually a one-dimensional array of characters which is terminated by a null character
'\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

#include <iostream>

using namespace std;

int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}
SOME SPECIAL FUNCTION IN STRING:
1. strcpy(s1, s2);
Copies string s2 into string s1.

2. strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3. strlen(s1);

Returns the length of string s1.

4. strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5. strchr(s1, ch);

Returns a pointer to the first occurrence of character ch in string s1.

6. strstr(s1, s2);

Returns a pointer to the first occurrence of string s2 in string s1.

1.
#include <iostream>
#include <string>

Using namespace STD;

int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

return 0;
}
2.
#include <iostream>
#include <string>

using namespace std;

int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}

C++ FUNCTIONS
A function is a group of statements that together perform a task. Every c++ program has at least
one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function performs a
specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.

A c++ function definition consists of a function header and a function body. Here are all the
parts of a function:

 Return type: a function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function name: this is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters: a parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function body: the function body contains a collection of statements that define what
the function does.

#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);

cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2)
{
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
FUNCTION ARGUMENTS:

If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a
function:
Call Type Description
This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to
Call by value
the parameter inside the function have no effect on the
argument.
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
Call by pointer
actual argument used in the call. This means that changes made
to the parameter affect the argument.
This method copies the reference of an argument into the
formal parameter. Inside the function, the reference is used to
Call by reference
access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
#include <iostream>
using namespace std;

int sum(int a, int b=20)


{
int result;

result = a + b;

return (result);
}

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;

return 0;
}
result:
Total value is :300
Total value is :120

C++ POINTERS
C++ pointers are easy and fun to learn. Some c++ tasks are performed more easily with pointers,
and other c++ tasks, such as dynamic memory allocation, cannot be performed without them.
As you know every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator which denotes an address in
memory. Consider the following which will print the address of the variables defined:

1.
#include <iostream>

using namespace std;

int main ()
{
int var1;
char var2[10];

cout << "Address of var1 variable: ";


cout << &var1 << endl;

cout << "Address of var2 variable: ";


cout << &var2 << endl;

return 0;
}

2.
#include <iostream>

using namespace std;

int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}
C++ CLASSES AND OBJECTS

The main purpose of c++ programming is to add object orientation to the c programming
language and classes are the central feature of c++ that supports object-oriented programming
and are often called user-defined types.

A class is used to specify the form of an object and it combines data representation and methods
for manipulating that data into one neat package. The data and functions within a class are called
members of the class.

ACCESSING THE DATA MEMBERS:

The public data members of objects of a class can be accessed using the direct member access
operator (.). Let us try the following example to make the things clear:

#include <iostream>

using namespace std;

class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
THE DATA MEMBERS:

The public data members of objects of a class can be accessed using the direct member access
operator (.). Let us try the following example to make the things clear:

#include <iostream>

using namespace std;

class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210


Volume of Box2 : 1560

C++ INHERITANCE

One of the most important concepts in object-oriented programming is that of inheritance.


Inheritance allows us to define a class in terms of another class, which makes it easier to create
and maintain an application. This also provides an opportunity to reuse the code functionality
and fast implementation time.

#include <iostream>

using namespace std;

// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};

int main(void)
{
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}
INHERITANCES:

A c++ class can inherit members from more than one class and here is the extended syntax:

class derived-class: access baseA, access baseB....

Where access is one of public, protected, or private and would be given for every base class
and they will be separated by comma as shown above. Let us try the following example:

#include <iostream>

using namespace std;

// Base class Shape


class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Base class PaintCost


class PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
};

// Derived class
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};

int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

// Print the total cost of painting


cout << "Total paint cost: $" << Rect.getCost(area) << endl;

return 0;
}

You might also like