Introduction to C++ : Object Oriented Technology, Advantages of OOP, Input- output in
C++, Tokens, Keywords, Identifiers, Data Types C++, Derives data types. The void data
type, Type Modifiers, Typecasting, Constant
1. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
UNIT – 1
[Introduction to C++ : Object Oriented Technology, Advantages of OOP, Input- output in C++, Tokens,
Keywords, Identifiers, Data Types C++, Derives data types. The void data type, Type Modifiers,
Typecasting, Constant, Operator, Precedence of Operators, Strings.]
Object Oriented Technology
Object Oriented Technology, also known as OOP, is a computer science term which is used to
describe a computer application that is composed of multiple objects which are connected to each
other. In other words, Object Oriented programming is a programming style that is associated with
the concept of Class, Objects and various other concepts revolving around these two, like
Inheritance, Polymorphism, Abstraction, Encapsulation etc.
OOP treats data as a critical element in the program development and does not allow it to flow
freely around the system. It ties data more closely to the functions that operate on it and protects it
from accidental modifications from outside functions. OOP allows decomposition of a problem into
number of entities called objects and then builds data and functions around these objects. The
organization of data and functions in OOPS is shown below.
The data of an object can be accessed only by the functions associated with that object. However,
functions of one object can access the functions of other objects.
Provided By Shipra Swati, PSTC, Vaishali, Bihar
2. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
Basic Concepts of Object oriented Programming
1. Class: A class is a user defined data type. A class is a logical abstraction. It is a template that
defines the form of an object. A class specifies both code and data. It is not until an object of
that class has been created that a physical representation of that class exists in memory.
When you define a class, you declare the data that it contains and the code that operates on
that data. Data is contained in instance variables defined by the class known as data
members, and code is contained in functions known as member functions. The code and data
that constitute a class are called members of the class.
2. Object: An object is an identifiable entity with specific characteristics and behavior. An
object is said to be an instance of a class. Defining an object is similar to defining a variable
of any data type. Space is set aside for it in memory.
3. Encapsulation: Encapsulation is a programming mechanism that binds together code and
the data it manipulates, and that keeps both safe from outside interference and misuse. C+
+’s basic unit of encapsulation is the class. Within a class, code or data or both may be
private to that object or public. Private code or data is known to and accessible by only
another part of the object. That is, private code or data cannot be accessed by a piece of the
program that exists outside the object. When code or data is public, other parts of your
program can access it even though it is defined within an object. Typically, the public parts
of an object are used to provide a controlled interface to the private elements of the object.
This insulation of the data from direct access by the program is called data hiding.
4. Data abstraction: In object oriented programming, each object will have external interfaces
through which it can be made use of. There is no need to look into its inner details. The
object itself may be made of many smaller objects again with proper interfaces. The user
needs to know the external interfaces only to make use of an object. The internal details of
the objects are hidden which makes them abstract. The technique of hiding internal details in
an object is called data abstraction.
5. Inheritance: Inheritance is the mechanism by which one class can inherit the properties of
another. It allows a hierarchy of classes to be build, moving from the most general to the
most specific. When one class is inherited by another, the class that is inherited is called the
base class. The inheriting class is called the derived class. In general, the process of
inheritance begins with the definition of a base class. The base class defines all qualities that
will be common to any derived class. . In OOPs, the concept of inheritance provides the idea
of reusability. In essence, the base class represent the most general description of a set of
traits. The derived class inherits those general traits and adds properties that are specific to
that class.
6. Polymorphism: Polymorphism (from the Greek, meaning “many forms”) is a feature that
allows one interface to be used for a general class of actions. The specific action is
determined by the exact nature of the situation. The concept of polymorphism is often
expressed by the phrase “one interface, multiple methods.” This means that it is possible to
design a generic interface to a group of related activities. This helps reduce complexity by
allowing the same interface to be used to specify a general class of action. It is the
compiler’s job to select the specific action as it applies to each situation.
Provided By Shipra Swati, PSTC, Vaishali, Bihar
3. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
In compile time polymorphism, the compiler is able to select the appropriate function for a
particular call at compile time. In C++, it is possible to use one function name for many
different purposes. This type of polymorphism is called function overloading.
Polymorphism can also be applied to operators. In that case, it is called operator
overloading.
In run time polymorphism, the compiler selects the appropriate function for a particular call
while the program is running. C++ supports a mechanism known as virtual functions to
achieve run time polymorphism.
Advantages of OOP
Object Oriented Programming has great advantages over other programming styles:
• Simplicity: Software objects model real world objects, so the complexity is reduced and the
program structure is very clear.
• Code Reuse and Recycling: Objects created for Object Oriented Programs can easily be
reused in other programs.
• Design Benefits: Large programs are very difficult to write. Object Oriented Programs force
designers to go through an extensive planning phase, which makes for better designs with
less flaws. In addition, once a program reaches a certain size, Object Oriented Programs are
actually easier to program than non-Object Oriented ones.
• Modularity: Each object forms a separate entity whose internal workings are decoupled
from other parts of the system.
• Modifiability: It is easy to make minor changes in the data representation or the procedures
in an OO program. Changes inside a class do not affect any other part of a program, since
the only public interface that the external world has to a class is through the use of methods.
• Extensibility: adding new features or responding to changing operating environments can be
solved by introducing a few new objects and modifying some existing ones.
• Software Maintenance: Programs are not disposable. Legacy code must be dealt with on a
daily basis, either to be improved upon (for a new version of an exist piece of software) or
made to work with newer computers and software. An Object Oriented Program is much
easier to modify and maintain than a non-Object Oriented Program. So although a lot of
work is spent before the program is written, less work is needed to maintain it over time.
Provided By Shipra Swati, PSTC, Vaishali, Bihar
4. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
OOPS Disadvantages
Object Oriented Programming has several disadvantages which made it unpopular in the early
years.
• Size: Object Oriented programs are much larger than other programs. In the early days of
computing, space on hard drives, floppy drives and in memory was at a premium. Today we
do not have these restrictions.
• Effort: Object Oriented programs require a lot of work to create. Specifically, a great deal of
planning goes into an object oriented program well before a single piece of code is ever
written. Initially, this early effort was felt by many to be a waste of time. In addition,
because the programs were larger (see above) coders spent more time actually writing the
program.
• Speed: Object Oriented programs are slower than other programs, partially because of their
size. Other aspects of Object Oriented Programs also demand more system resources, thus
slowing the program down.
C++
C++ is an object oriented programming language. It was developed by Bjarne Stroustrup in 1979 at
Bell Laboratories in Murray Hill, New Jersey. He initially called the new language "C with
Classes." However, in 1983 the name was changed to C++.
C++ is a superset of C. Stroustrup built C++ on the foundation of C, including all of C’s features,
attributes, and benefits. Most of the features that Stroustrup added to C were designed to support
object-oriented programming .These features comprise of classes, inheritance, function overloading
and operator overloading. C++ has many other new features as well, including an improved
approach to input/output (I/O) and a new way to write comments.
C++ is used for developing applications such as editors, databases, personal file systems,
networking utilities, and communication programs. Because C++ shares C’s efficiency, much high-
performance systems software is constructed using C++.
The general structure of C++ program with classes is shown as:
1. Documentation Section
2. Preprocessor Directives or Compiler Directives Section
3. Global Declaration Section
4. Class declaration or definition
5. Main C++ program function called main ( )
Except adding compiler directive (header files) and using main(), rest parts are optional and depend
on the requirement.
Input- output in C++
For input and output '>>' and '<<' operator is used respectively.
The output statement causes the strings in quotation marks to be displayed on the screen and is
written as following:
Provided By Shipra Swati, PSTC, Vaishali, Bihar
5. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
cout << “the strings to be displayed as output”;
cout : pre-defined object that represents the the standard output stream (Screen in this case). It
works similar to printf().
<< : insertion operator or put to operator
*** << operator is also used as bit-wise left shift operator depending on the context. This is an
example of operator overloading, an important aspect of polymorphism.
The input statement causes the program to wait for the user to enter relevant values for any
number and is written as following:
cin >> variable1;
cin : pre-defined object that represents the the standard input stream (Keyboard in this case).
>> : extraction operator or get from operator. This corresponds to familiar scanf() function.
*** >> operator is also overloaded like << operator. >> is used as bit-wise right shift operator.
A Simple C++ Program
#include<iostream.h>
#include<conio.h>
int main() {
clrscr();
cout<< “Hello World”;
getch();
return 0;
}
CODE EXPLANATION
#include<iostream.h> Lines beginning with a hash sign ( # ) are directives read and interpreted
by what is known as the preprocessor. They are special lines interpreted
before the compilation of the program itself begins. In this case, the
directive #include <iostream.h>, instructs the preprocessor to include a
section of standard C++ code, known as header iostream that allows to
perform standard input and output operations, such as writing the output
of this program to the screen.
#include<conio.h> This line instructs compiler to include header file <conio.h>, which
handles console related functions.
int main() The execution of all C++ programs begins with the main function,
regardless of where the function is actually located within the code.
{ The open brace ( { ) indicates the beginning of main 's function definition
clrscr(); This function clears the screen.
cout<< “Hello World”; This statement causes the string in quotation marks to be displayed on the
screen
getch(); This function holds the screen and is defined in <conio.h>.
return 0; This causes zero to be returned to the calling process (which is usually the
operating system). Returning zero indicates that the program terminated
normally. Abnormal program termination should be signaled by returning
a nonzero value.
} The closing brace ( } ) indicates end of main ().
Provided By Shipra Swati, PSTC, Vaishali, Bihar
6. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
Tokens
A token is the smallest element of a C++ program that is meaningful to the compiler. It is a group of
characters that logically belong together. Tokens supported in C++ can be categorised as follows:
• keywords
• identifiers
• variable
• constants
• operators
• special characters
• Strings
Keywords
Keywords are also known as reserved words of the language. They have a specific meaning for the
C++ compiler and should be used for giving specific instructions to the computer. They cannot be
used for any other purpose other than that specified by the C++ language. C++ is a case-sensitive
language, and it requires that all keywords be in lowercase. The keywords supported by C++
language are shown below, some of them were also available in C.
Provided By Shipra Swati, PSTC, Vaishali, Bihar
7. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
Identifiers
Identifiers are names that are given to various program elements, such as variables, functions and
arrays. They are fundamental requirement of any language. Each language has its own rules for
naming these identifiers, which are given below:
1. Name can be formed by using alphabets, digits or underscore (_) characters.
2. Name must begin with an alphabet or underscore character.
3. The name can not start with a digit.
4. Keywords cannot be used as the name of identifiers because they have some predefined
meaning in the language.
5. Identifiers are case sensitive, i.e. upper case and lower case letters are distinct.
6. In C++, there is no limit to the length of an identifier, and at least the first 1024 characters
are significant, unlike C, where only first 32 characters were recognized in an identifier
name.
Data Types C++
Data type defines size and type of values that a variable can store along with the set of operations
that can be performed on that variable. Data type representation is machine specific in C++. In C++,
it is mainly divided into following types:
• Built-in / Primitive Data Types: These data types are built-in or predefined data types and
can be used directly by the user to declare variables. example: int, char , float, bool etc.
Primitive data types available in C++ are:
• Integer: Keyword used for integer data types is int. Integers typically requires 4
bytes of memory space and ranges from -2147483648 to 2147483647.
• Character: Character data type is used for storing characters. Keyword used for
character data type is char. Characters typically requires 1 byte of memory space
and ranges from -128 to 127 or 0 to 255.
• Boolean: Boolean data type is used for storing boolean or logical values. A boolean
variable can store either true or false. Keyword used for boolean data type is bool.
Provided By Shipra Swati, PSTC, Vaishali, Bihar
Class
8. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
• Floating Point: Floating Point data type is used for storing single precision floating
point values or decimal values. Keyword used for floating point data type is float.
Float variables typically requires 4 byte of memory space.
• Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating
point data type is double. Double variables typically requires 8 byte of memory
space.
The void data type
• void: Void means without any value. void datatype represents a valueless entity. Two
normal usage of void are:
▪ to specify the return type of a function, when it is not returning any value,
▪ to indicate an empty argument list to a function.
For example: void func1(void)
Another use of void is in the declaration of generic pointers, which is a special type
of pointer that can be pointed at objects of any data type. A void pointer is declared
like a normal pointer, using the void keyword as the pointer’s type. Example:
#include<iostream>
using namespace std;
int main(){
void *v;
int *i;
float f =2.3;
v=&f;
cout<<"Address of f: "<<&f<<"nValue assigned to v: "<<v<<endl;
//i=&f; // error: cannot convert ‘float*’ to ‘int*’ in assignment
return 0;
}
• Wide Character: Wide character data type is also a character data type but this data
type has size greater than the normal 8-bit datatype. Represented by wchar_t. It is
generally 2 or 4 bytes long.
Type Modifiers
Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in data
types to modify the length of data that a particular data type can hold. Data type modifiers
available in C++ are:
• Signed
• Unsigned
• Short
• Long
CODING ASSIGNMNT 1:
Students are supposed to find out the size of all primitive data types with and without type
modifiers.
Provided By Shipra Swati, PSTC, Vaishali, Bihar
9. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
Derives data types
• Derived Data Types: Data types that are derived from the built-in data types are known as
derived data types. The various derived data types provided by C++ are arrays, functions,
and pointers.
• Array: An array is a set of elements of the same data type that are referred to by the
same name. All the elements in an array are stored at contiguous (one after another)
memory locations and each element is accessed by a unique index or subscript value.
The subscript value indicates the position of an element in an array.
• Function: A function is a self-contained program segment that carries out a specific
well-defined task. In C++, every program contains one or more functions which can
be invoked from other parts of a program, if required.
• Pointer: A pointer is a variable that can store the memory address of another
variable. Pointers allow to use the memory dynamically. That is, with the help of
pointers, memory can be allocated or de-allocated to the variables at run-time, thus,
making a program more efficient.
• User-Defined Data Types: Various user-defined data types provided by C++ are structures,
unions, enumerations and classes.
• Structure, Union andClass: Structure and union are the significant features of C
language. Structure and union provide a way to group similar or dissimilar data types
referred to by a single name. However, C++ has extended the concept of structure
and union by incorporating some new features in these data types to support object
-oriented programming.
C++ offers a new user-defined data type known as class, which forms the basis of
object-oriented programming. A class acts as a template which defines the data and
functions that are included in an object of a class. Classes are declared using the
keyword class. Once a class has been declared, its object can be easily created.
• Enumeration: An enumeration is a user-defined data type where we specify a set of
values for a variable and the variable can only take one out of a small set of possible
values. These values are actually integral constants. To define an enumeration,
keyword enum is used.
enum season { spring, summer, autumn, winter };
Here, the name of the enumeration is season. And, spring, summer, autumn and
winter are values of type season. By default, spring is 0, summer is 1, autumn is 2
and winter is 3. You can change the default value of an enum element during
declaration (if necessary), like given below:
enum season {
spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
OR
enum color {red, blue=4, green=8};
enum color {red=5, blue, green};
Provided By Shipra Swati, PSTC, Vaishali, Bihar
10. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
In the first case, red is 0 by default. In the second case, blue is 6 and green is 7. Note that the
subsequent initialized enumeratators are larger by one than their predecessors.
Simple Example of enumeration:
#include <iostream>
using namespace std;
enum direction {East, West, North, South};
int main(){
direction dir;
dir = South;
cout<<dir<<endl;
int c = East; //Valid operation
cout<<c<<endl;
// dir = 1; //error: invalid conversion from ‘int’ to ‘direction’
return 0;
}
Why use enum in C++
• Enums are used only when we expect the variable to have one of the possible set of values,
for example, we have a dir variable that holds the direction. Since we have four directions,
this variable can take any one of the four values, if we try to assign a another random value
to this variable, it will throw a compilation error. This increases compile-time checking and
avoid errors that occurs by passing in invalid constants.
• Another important place where they are used frequently are switch case statements, where
all the values that case blocks expect can be defined in an enum. This way we can ensure
that the enum variable that we pass in switch parenthesis is not taking any random value that
it shouldn’t accept.
CODING ASSIGNMNT 2:
Study “typedef” and implement it for any simple example as per your understanding.
Variable (Token of C++)
A variable is a named area in memory used to store values during program execution. Variables are
run time entities and its value can be changed during the execution of the program. A variable has a
symbolic name and can be given a variety of values. When a variable is given a value, that value is
actually placed in the memory space assigned to the variable. All variables must be declared before
they can be used. The general form of a declaration is:
type variable_list;
Here, type must be a valid data type plus any modifiers, and
variable_list may consist of one or more identifier names separated by commas.
Here are some declarations:
int i,j,l;
short int si;
unsigned int ui;
double balance, profit, loss;
A variable can be assigned with a value during its declaration. The assignment operator ( = ) is used
in this case. The following syntax shows how a variable is initialize.
Datatype VariableName = constant value;
Otherwise, user can be prompted to enter the variable value during execution with the help of cin
object.
Provided By Shipra Swati, PSTC, Vaishali, Bihar
11. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
Constants (Tokens of C++)
Constants refer to fixed values that do not change during the execution of a program. Constants are
data storage locations. They cannot change in the course of running the program. C++ has two types
of constants literal constants and symbolic constants.
• Literal constants: A literal constant is just a value. For example, 10 is a literal constant. It
does not have a name, just a literal value. We cannot use 10 to store another integer value
and its value cannot be altered. The literal constant does not hold memory location.
Depending on the type of data, literal constants are of the following types shown with
examples–
Remember that a character constant is always enclosed with single quotation mark, whereas
a string constant is always enclosed with a double quotation mark. Another point to
remember is that an octal integer constant is always starts with 0 and a hexadecimal integer
constant with 0x.
• Symbolic constant : A symbolic constant is defined in the same way as variable. However,
after initialization of constants the assigned value cannot be altered. The constant can be
defined in the following three ways :
a) # define: The # define preprocessor directive can be used for defining constants as
• # define Maximum 100
• # define PI 3.142
• # define AGE 30
In the above example Maximum, PI, AGE symbolic constants contains the value
100, 3.142 and 30 and here it is not mentioned whether the type is int, float or char.
Every time when the preprocessor finds the word Maximum, PI, AGE, it will just
substitute it with the values 100, 3.142 and 30 respectively.
b) The const keyword: he syntax of defining variables with the const keyword is
shown below :
const [data type] variable name = constant value;
Provided By Shipra Swati, PSTC, Vaishali, Bihar
12. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
The following program demonstrates the use of #define and const –
#include<iostream>
using namespace std;
#define PI 3.142
const int MAX=5;
int main ( )
{
float radius, area;
cout<<"Enter the radius :";
cin>> radius;
area=PI*radius*radius;
cout<< "Area of the circle ="<<area <<"n";
cout<<"constant max value is: "<<MAX<<endl;
// PI=3; //Invalid
// MAX=10; //error: assignment of readonly variable ‘MAX’
}
In the above program the statement
area = PI * radius * radius;
is translated by the preprocessor as
area = 3.142 * radius * radius;
and calculated result is stored in the variable ‘area’ which is displayed in the next
statement.
MAX variable contains the constant value 5 and same is displayed.
c) The enum keyword: It is explained earlier in the user-defined data type section.
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. All C operators are valid in C++. The detailed description is provided in seperate
document for C operators for ease of reading. All the codes should be experimented by students
using C++ syntax. Following operators other than >> and << are available in C++:
Typecasting
Typecasting is the concept of converting the value of one type into another type. For example, you
might have a float that you need to use in a function that requires an integer.
• Implicit conversion: Almost every compiler makes use of what is called automatic
typecasting. It automatically converts one type into another type. If the compiler converts a
type it will normally give a warning. For example this warning: conversion from ‘double’ to
‘int’, possible loss of data. The problem with this is, that you get a warning (normally you
Provided By Shipra Swati, PSTC, Vaishali, Bihar
13. OBJECT ORIENTED PROGRAMMING NOTES UNIT-1
want to compile without warnings and errors) and you are not in control. With control we
mean, you did not decide to convert to another type, the compiler did. Also the possible loss
of data could be unwanted.
• Explicit conversion: The C++ language have ways to give you back control. This can be
done with what is called an explicit conversion.
The C++ language has four typecast operators:
• static_cast
• reinterpret_cast
• const_cast
• dynamic_cast
These operators will be discussed after finishing basic oops concepts.
Type Conversion
The Type Conversion is that which automatically converts the one data type into another with the
consideration of storage. For example we can't store a float into int because a float is greater than
int. When a user can convert the one data type into then it is called as the type casting.
The type Conversion is performed by the compiler but a casting is done by the user for example
converting a float into int. When we use the Type Conversion then it is called the promotion.
In the type casting when we convert a large data type into another then it is called as the demotion.
When we use the type casting then we can loss some data.
Provided By Shipra Swati, PSTC, Vaishali, Bihar