INTRODUCTION C++
INTRODUCTION C++
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.
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 */
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.
A variable definition means to tell the compiler where and how much to create the storage for the
variable.
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:
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 = 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:
MISC OPERATORS
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.
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;
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.
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.
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}};
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>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
return 0;
}
SOME SPECIAL FUNCTION IN STRING:
1. strcpy(s1, s2);
Copies string s2 into string s1.
2. strcat(s1, s2);
3. strlen(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);
6. strstr(s1, s2);
1.
#include <iostream>
#include <string>
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
return 0;
}
2.
#include <iostream>
#include <string>
int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
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;
return 0;
}
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;
result = a + b;
return (result);
}
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
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>
int main ()
{
int var1;
char var2[10];
return 0;
}
2.
#include <iostream>
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
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.
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>
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>
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:
C++ INHERITANCE
#include <iostream>
// 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);
return 0;
}
INHERITANCES:
A c++ class can inherit members from more than one class and here is the extended syntax:
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>
// 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();
return 0;
}