C++ Progrmming Unit I
C++ Progrmming Unit I
Programming in C++
The main aim of OOP is to bind together the data and the functions that operate on them so that no other
part of the code can access this data except that function.
There are a few principle concepts that form the foundation of object-oriented programming:
(a) Object: Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class. An object is an identifiable entity
with some characteristics and behavior.
For instance, ‘Orange’ is an object. Its characteristics are: it is spherical shaped, its colour is orange
etc. Its behavior is: it is juicy and its tastes sweet-sour.
class person
{
char name[20];
int id;
public:
void getdetails( );
};
void main( )
{
person p1; // p1 is a object
}
(b) Class: A class is a group of objects that share common properties and relationships. It
represents a group of similar objects.
It is a user-defined data type, which holds its own data members and member functions, which can
be accessed and used by creating an instance of that class. A class is like a blueprint for an object.
No memory is allocated when a class is created. Memory is allocated only when an object is created,
i.e., when an instance of a class is created.
(c) Data Abstraction: Data abstraction is one of the most essential and important features of
object-oriented programming in C++. Abstraction means displaying only essential information and
hiding the background details.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car but he does not know the inner mechanism about how
on pressing accelerator the speed is actually increasing. That is what abstraction is.
(d) Data Encapsulation: Encapsulation is the most fundamental concept of OOP. It is the way of
combining both data and the functions that operate on that data under a single unit.
The wrapping up of data and functions (that operate on the data) into a single unit (called class) is
known as Encapsulation.
For example, in a company, departments access and work with their data on their own. One department
cannot access data of other department directly. Rather a request is made for the required data and the
data is handed over by the members of the requested department. Thus, it can be said that department
data and department employees are encapsulated into a single entity, “the department”.
(e) Inheritance: Inheritance is the capability of one class of things to inherit capabilities or
properties from another class.
The class, whose properties are inherited, is called Base Class or Super Class and the class that inherits
these properties, is called Derived Class or Sub Class.
Inheritance helps in reducing the overall code size of the program, which is an important concept in
object-oriented programming.
(f) Polymorphism: Polymorphism is the ability for a message or data to be processed in more than
one form. Polymorphism is a property by which the same message can be sent to objects of several
different classes.
The word Polymorphism is derived from two Greek words Poly which means many and morphos
which means forms. C++ provides three different types of polymorphism:
o Virtual Function
o Function Overloading
o Operator Overloading
(g) Binding: Binding refers to the process that is used to convert identifiers into machine language
addresses. There are two types of bindings:
• Early binding or static binding: Early binding means the compiler is able to directly
associate the identifier name (such as a function or variable name) with a machine address. In
other words, binding is performed at compile time.
• Late binding or dynamic binding: Dynamic binding refers to the case where compiler is not
able to resolve the call and the binding is done at runtime only.
(h) Message Passing: The process by which an object sends data to another object or asks the other
object to invoke a method is known as message passing. It is also known as interfacing.
Applications of OOP:
The main application areas of OOP are
• It is easy to model a real system as real objects are represented by programming objects in OOP.
• With OOP, programs are easy to understand.
• OOP offers classes reusability. Already created classes can be reused without having to write them
again. This saves time and cost of program.
• With OOP, programs are easier to test, manage and maintain.
• It helps to manage software complexity easily.
• OOP facilitates Quick Development as parallel development of classes is possible.
Disadvantages of OOP:
Although OOP has proved revolutionary in software development yet it has some disadvantages too. These
are
C++ Character Set: Character set is a set of valid characters that a language can recognize. A
character represents any letter, digit, or any other sign. The C++ has the following character set
Letters A-Z, a-z
Digits 0–9
Special Symbols + - / ( ) [ ] { } = < > & ^ % * # @ <= >=
White Space Blank Space, Horizontal tab (→), new line
Other Character C++ can process any of the 256 ASCII characters as data or as literals.
Tokens:
The smallest individual unit in a program is known as a Token. They are the basic building blocks of a C++
program. Tokens are useful for compiler to detect errors. C++ has the following tokens:
• Keywords
• Identifiers
• Constants (Literals)
• Punctuators
• Operators
Keywords:
Keywords are the words that convey a special meaning to the language compiler. These are reserved for special
purpose and must not be used as normal identifier names.
C++ supports 64 keywords. Few of them are as follows:
• Integer constants
• Character constants
• Floating point constants
• String constants
Data Types
C++ supports different types of data, each of which may be represented differently within a computer's
memory. Data type is used to determine what type of value a variable or a constant can contain throughout the
program.
In C++ language, it is compulsory to declare variables with their data type before using them in any statement.
Mainly data types are categorized into following categories:-
(a) Int (Integer):- Integer data type is used to store numeric values without any decimal
point. int keyword is used to refer integer data type. They generally require 2 bytes of memory for
their storage. The range of values that variables of this type can hold lies between -32,768 to
+32,767.
Syntax:
int variable_name;
Example:
int roll, marks, age;
roll = 15;
(b) Float:- Float data type is used to store numeric values with decimal point. float keyword is
used to refer integer data type. The storage size of float data type is 4 byte. The range of float data
type is from 3.4x10-38 to 3.4x1038. We can use upto 6 digits after decimal using float data type.
(c) Char (Character):- Character data type is used to store single character, within single quotes
e.g. 'a', 'z','e' etc. Storage size of char data type is 1. char keyword is used to refer character data
type.
Syntax:
char variable name;
Example:
char ch;
ch = ‘a’;
(d) Double:- Double data type is also same as float data type which allows upto 15 digits after
decimal and the range is from 1.7 x 10-308 to 1.7 x 10308 . The storage size of double data type is 8
bytes.
Syntax:
double variable_name;
Example:
double sal;
sal = 450.9876;
(e) Void:- Void data type is used to represent an empty value. It is used as a return type if a
function does not return any value.
Syntax:
void function_name( );
Example:
void sum( );
Data types that are derived from fundamental data types are called derived data types. Derived data
types don't create a new data type; instead, they add some functionality to the basic data types.
Two derived data type are - Array & Pointer.
(a) Array:- An array is a collection of variables of same type i.e. collection of homogeneous
data referred by a common name. In memory, array elements are stored in a continuous
location.
Syntax:
int array_name[size];
Example:
int age[20];
According to the rules of C++ language, 1st element of array is stored at location age[0] , 2nd
at age[1] & so on.
(b) Pointer:- A pointer is a special variable that holds a memory address (location in memory)
of another variable. The asterisk (*) sign is used to declare a pointer variable.
Syntax:
datatype * variable_name;
Example:
int a, *p;
p = &a;
Here, variable 'p' stores the address of variable 'a'.
User defined data type is used to create new data types. Different user defined data types are: class,
struct, union, enum.
(a) Struct (Structure):- A structure is a collection of different data types which are grouped
together. In memory, the entire structure variable is stored in sequence. struct keyword is used
to refer structure data type.
(b) Union:- Union is also like structure, i.e. collection of different data types which are
grouped together. In memory, union variables are stored in a common memory location.
Syntax:
union < tag name>
{
var1;
var2;
-----
};
Example:
union student
{
char name [20];
int roll;
float marks;
};
(c) Enum (Enumeration):- An enumeration data type is another user-defined type which
provided a way for attaching names to numbers. Enumeration are defined much like structures,
the keyword enum is used to refer enumeration type.
Syntax:
enum < tag name>
{
enumeration list
};
By default, the enumeration is assigned integer values starting with 0 for the first enumerator,
1 for the second, and so on. The value can over-ride the default by explicitly assigning integer
values to the enumerators.
enum colour
{
red = 5, green = 8, blue = 9
};
(d) Class:- A class represents a group of similar objects. A class is a way to bind the data
describing an entity and its associated functions together. To represent classes in C++,
it offers a user-defined data type called class.
Syntax:
class < class name>
{
private :
[variable declarations;]
[function declarations;]
public :
[variable declarations;]
[function declarations;]
};
Example:
class department
{
char name[20];
int num_emp;
char h_o_d[20];
public :
add( );
delete( );
print( );
};
(a) Arithmetic Operators: The arithmetic operators are used for mathematical calculations.
The arithmetic operators are binary operators that work with any basic type.
Addition +
Subtraction -
Multiplication *
Division /
Modulus % this operator produces the remainder.
For Example: Now suppose a and b are two operands of type integer then
Operation If a = 7 and b =3
a+b 10
a-b 4
a*b 21
a/b 2
a%b 1
(b) Relational Operators: The relational operators are used to check the relation between
two operands. It is used to make comparison between two operands. Relational operators are binary
operators and hence require two operands. The result of relational operation is a value that can only
be true or false according to the result of the comparison.
a<b False
a <= b False
a>b True
a >= b True
a == b False
a!=b True
(c) Logical Operators: Logical operators are used to combine one or more relational
expressions. In C++, there are three logical operators, logical AND (&&), logical OR (||) and
logical NOT (!). The logical AND and logical OR operators are binary operators whereas logical
NOT is an unary operator.
Logical AND (&&): The logical AND (&&) is a binary operator that evaluates to true if and
only if both of its operands (expressions) evaluate to true.
Result
Expression1 Expression2 (expression1 &&
expression2)
Logical OR (||): The logical OR (||) is a binary operator that evaluates to true if and only if either
of its operands (expressions) evaluate to true.
Result
Expression1 Expression2 (expression1 || expression2)
Result
Expression1 (!expression1)
True False
False True
(d) Assignment Operator: The assignment operator (=) is the most commonly used binary
operator in C++. It evaluates the operand on right hand side and then assigns the resulting value to
a variable on the left hand side. The right operand can be a variable, constant, function call or
expression.
(e) Conditional Operators: C++ offers a conditional operator (? :) that stores a value
depending upon a condition. This operator is ternary operator i.e, it requires three operands. The
general form of conditional operator (?:) is as follows:
If expression1 evaluates to true then the value of the whole expression is the value of
expression2, otherwise, the value of the whole expression is the value of expression3.
For example:
result = (marks>=50) ? ‘P’ : ‘F’ ;
In this example, if (marks>=50) is true than result is assigned value ‘P’ and if it is false than it
is assigned value ‘F’.
(f) Bitwise Operators: C++ provides extensive bit manipulation operators for programmers
who want to communicate directly with the hardware. These operators are used for testing bits or
shifting them either right to left or left to right. Following are the bitwise operators
Operator Meaning
| Bitwise OR
Bitwise One’s
~ Complement
Syntax:
sizeof(datatype or variable)
Example:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a;
float b;
char c;
cout<< “Integer :” << sizeof(a) << endl;
cout<< “Float :” << sizeof(b) << endl;
cout<< “Character :” << sizeof(char) << endl;
getch( );
}
Integer : 2
Float : 4
Character : 1
# include <iostream.h>
# include <conio.h>
void main( )
{
int amount = 456;
cout << “Global Variable:” << ::amount; << endl;
cout <<”Local Variable:” << amount;
getch( );
}
Operator
Operator Associativity
Category
Arithmetic
* (multiplication), /, %,+, - (subtraction) L→R
Operators
Bitwise Shift
& (bitwise AND), | (bitwise OR) L→R
Operators
Relational
<, <=, >=, > L→R
Operators
Conditional
?: R→L
Operators
The IF statement: The basic decision making statement used in most C++ programs is the if statement.
The different types of if statements are
(a) Simple if statement (b) If-else statement (c) Nested if statement (d) Else-if Ladder
The if statement is the most simple and powerful decision control statement which is used to
control the sequence of execution of statements. It is used to execute a statement or a statement block
only if the condition is true. No statement(s) is executed when the condition evaluates to false.
if(condition)
{
statement(s);
}
Example: To check if a number is greater than 25.
#include<iostream.h>
#include<conio.h>
void main( )
{
int a;
cout << ”Enter a number : ”;
cin >> a;
if(a > 25)
{
cout << “Number is greater than 25”;
}
getch( );
}
The if-else statement allows the programmer to execute a statement block following the if
keyword when the condition is true and execute a different statement block following the else
keyword when the condition is false. In other words, it is a two way branching statement.
if(condition)
{
statement(s);
}
else
{
statement(s);
}
#include<iostream.h>
#include<conio.h>
void main( )
{
int n;
clrscr( );
cout << ”Enter a number : ”;
cin >> n;
if(n%2 = = 0)
{
cout << “Number is Even”;
}
else
{
cout << “Number is Odd”;
}
getch( );
}
A nested if is an if that has another if in its if’s body or in its else’s body. The different ways
for representing nested if statements are
In an if statement, either there can be if statement(s) in its body-of-if or in its body-of-else or in both.
#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, c;
cout << “Enter the three numbers : ”;
cin >> a >> b >> c;
if(a > b)
{
if(a>c)
{
cin >> “A =” >> a >> “is greatest”;
}
else
{
cin >> “C =” >> c >> “is greatest”;
}
}
else
The else-if ladder is the most general way of writing a program involving multiple conditions.
if(condition1)
{
statement1;
}
else if(condition2)
{
statement2;
}
else if(condition3)
{
statement3;
}
.
.
else
{
statement;
}
The conditions are evaluated from the top to downward. As soon as the condition evaluates to
true, the statement associated with it is executed and the rest of the ladder is bypassed. If none
of the conditions are true, the final else gets executed.
#include<iostream.h>
#include<conio.h>
void main( )
The Switch statement: The switch statement is a multi-way decision making statement which selects
one of the several alternatives based on the value of an expression. The switch statement is mainly used to
replace multiple if-else statements.
switch(expression)
{
case constant1 : statement(s);
break;
case constant2 : statement(s);
break;
.
.
.
[default : statement(s);]
}
#include<iostream.h>
#include<conio.h>
void main( )
{
Switch If-else
It can handle only integer and character test. It can handle integer, character and floating-point tests.
It is preferred when large numbers of It is preferred when numbers of conditions are less.
conditions are involved.
In switch case label value must be a constant. In if two or more variables are to be compared.
• Global Variables
• Local variables
• Global Variables: Global variables are those, which are once declared and can be used throughout
the lifetime of the program by any class or any function. They must be declared outside the main( )
function.
For Example:
#include <iostream.h>
#include<conio.h>
int x; // Global variable declared
int main()
{
int a, b;
a = 10, b = 20;
x = a + b;
cout <<"The Sum is = "<< x;
getch( );
}
• Local Variables: Local variables are the variables which exist only between the curly braces, in
which it’s declared. Outside that they are unavailable and lead to compile time error.
For Example:
#include <iostream.h>
#include<conio.h>
int main()
{
int a, b, c; // Local Variables declared
a = 10, b = 20;
c = a + b;
cout <<"The Sum is = "<< c;
getch( );
}
Type Conversion:
The process of converting one predefined type into another is called Type conversion.
Type conversion is usually classified into two categories
(1) Implicit or Automatic Type Conversion
In the above expression, firstly the int value is converted to float. Then, this float value is multiplied
with another float value and result is a float value. Now as left hand side has data type double so
finally this float type is converted to double.
Explicit Type Conversion or Type Casting: An explicit type conversion is user defined that
forces an expression to be of specific type. The explicit conversion of an operand to a specific type is called
Type Casting.
Syntax:
(type) expression
Here type is a valid C++ data type to which the conversion is to be done.
For Example:
int m = 5;
int n = 9;
float c;
c = (float) m/n;
In the above formula if casting is not performed than the result of the expression gives
us 0 value but when the casting is done the above expression will converted into float
type that will result 0.555556 value.