C++ Progrmming Unit I
C++ Progrmming Unit I
Programming in C++
(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. There can be more than one
instance of an object. An object is an identifiable entity with some characteristics and behavior. It
represents an entity that can store data and its associated functions.
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.
(b) Class: A class is a group of objects that share common properties and relationships. It
represents a group of similar objects.
Thus a Class represents a set of individual objects. Characteristics of an object are represented in a
class as Properties. The actions that can be performed by objects become functions of the class and is
referred to as Methods.
For example, consider a Class of Cars under which Santro Xing, Alto and WaganR represent
individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture,
Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the associated
actions i.e., object functions like Start, Move, Stop form the Methods of Car Class.
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: Abstraction refers to the act of representing essential features without
including the background details or explanation between them.
(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.
When using Data Encapsulation, data is not accessed directly, it is only accessible through the
functions present inside the class. These functions are called member functions in C++.
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
(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
Advantages of OOP:
The main advantages 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.
• 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:
Constants (Literals):
Constants are the data items that never change their value during a program. Every constant used in a C++
program has a type that is determined by its form and a value. Its value is set when the program is written,
and it retains this value throughout the program’s existence.
• 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.
(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.
Syntax:
float variable name;
Example:
float per, area;
per = 20.75;
(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’;
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.
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.
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.
Syntax:
struct < structure name>
{
var1;
var2;
-----
-----
};
Example:
struct student
{
char name [20];
int roll;
float marks;
};
(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;
(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
};
Example:
enum colour
{
red, blue, green, yellow
};
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 :
Example:
class department
{
char name[20];
int num_emp;
char h_o_d[20];
public :
add( );
delete( );
print( );
};
department sales, accounts, import;
Operators:
An operator is a special symbol that tells the complier to perform specific mathematical or logical operation
on one or more operands where an operand can be a variable, constant or an expression.
In C++, an operator can either be unary, binary or ternary. If an operator operates on single operand then it is
termed as unary operator. If an operator operates on two operands, it is called binary operator. The operator
that works with three operands is called ternary operator.
The various operators available in C++ are
(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.
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.
For Example: Now suppose a and b are two operands of type integer then
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.
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)
Logical NOT (!): The logical NOT (!) is an unary operator. The logical NOT operator reverses
the value of the expression i.e., if the expression is true, then !expression is false, and vice versa.
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.
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 Exclusive
^ 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
(i) Scope Resolution Operator (: :) : The operator (: :) is known as scope resolution operator.
It has been introduced to access an item that is outside the current scope i.e. it is used to access
the global variables. This operator is also used in distinguishing class members and defining class
methods.
# 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
Bitwise Shift
& (bitwise AND), | (bitwise OR) L→R
Operators
Relational
<, <=, >=, > L→R
Operators
Conditional
?: R→L
Operators
Assignment
=, +=, -= etc. 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
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);
}
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
#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)
{
cout << “A =” << a << “is greatest”;
}
else
{
cout << “C =” << c <<“is greatest”;
}
}
else
{
if(b>c)
{
cout << “B =” << b << “is greatest”;
}
else
{
cout << “C =” << c <<“is greatest”;
}
}
getch( );
}
The else-if ladder is the most general way of writing a program involving multiple
conditions.
if(condition1)
{
statement1;
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( )
{
int a, b, c;
cout << “Enter the three numbers : ”;
cin >> a >> b >> c;
if(a > b && a>c)
{
cout << “A =” << a << “is greatest”;
}
else if(b>a && b>c)
{
cout << “B =” << b << “is greatest”;
}
else
{
cout << “C =” << c <<“is greatest”;
}
getch( );
}
switch(expression)
{
case constant1 : statement(s);
break;
case constant2 : statement(s);
break;
.
.
.
.
[default : statement(s);]
}
#include<iostream.h>
#include<conio.h>
void main( )
{
char c;
clrscr( );
cout << “Enter the character in capital letters: ”;
cin >> c;
switch(c)
{
Case ‘A’ : cout << “Character is Vowel”;
break;
Case ‘E’ : cout << “Character is Vowel”;
break;
Case ‘I’ : cout << “Character is Vowel”;
break;
Case ‘O’ : cout << “Character is Vowel”;
break;
Case ‘U’ : cout << “Character is Vowel”;
break;
default : cout << “Character is not vowel”;
}
getch( );
}
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.
Scope of Variables: All the variables have their area of functioning, and out of that boundary they
don't hold their value, this boundary is called scope of the variable. There are mainly two types of variable
scopes:
• 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;
• 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
(2) Explicit Type Conversion or Type Casting
Implicit or Automatic Type Conversion: The conversion of data type which is carried out
automatically by the compiler without programmer intervention is called implicit type conversion. When
two data items (variables) of different data types are encountered in the same expression, then the lower
type variable is converted to the higher type variable before the operation proceeds.
The hierarchy of data types is as follows
long double →double →float →long int →int →char
For Example:
int a = 10;
float b = 2.5;
double d;
d = a * b;
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.
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.