Sei sulla pagina 1di 35

Object oriented Programming with C++

Module-I

1. Introduction
2. Procedure Oriented Programming
3. Object Oriented Programming Paradigm
4. Basic Concepts of OOP
5. Benefits of OOP
6. Object Oriented Languages
7. Features of OOP
8. How OOP Differ from POP
9. Applications of OOP
10. A Simple C++ Program
11. Structure of C++ Program
12. namespace scope

Introduction
C’ programming language is a Procedure – Oriented Programming (POP) wherein the
main emphasis is on data and functions. One serious drawback in this approach is that it does not

0
model real world problems very well. The main emphasis is to introduce a new programming
paradigm – Object Oriented Programming (OOP) and particularly this chapter describes about
what are the different its different features and what are the advantages of this new paradigm.

Programming Paradigms

Programming style is defined as a way of organizing the ideas on the basis of some
conceptual model of programming and using an appropriate language to write efficient programs.
The two main programming styles are:

 Procedure-Oriented
 Object Oriented.

No single programming style is best suited for all kinds of applications. For example,
Procedure-oriented programming would be best suited for the design of computation-intensive
problems and Object oriented programming style is best suited for a wide range of application. It
also serves as the architectural frame work in which other paradigms are employed.

Procedure Oriented Programming (POP)


Conventional programming, using high level languages such as COBOL, FORTRAN and
C are commonly known as procedure–oriented programming (POP). In this style the problem
is viewed as a sequence of things to be done such as reading, calculating and printing. A number
of functions are written to accomplish these tasks. The primary focus is on functions.

Main Program

Function - 1 Function - 2 Function - 3

1
Function – 4 Function - 5

Function - 6 Function - 7 Function - 8

Fig1 procedure oriented programming style.

Procedure oriented programming basically consists of writing a list of instructions in the


form of functions. While concentrating function, very little attention is given to the data that are
being used by various functions.
When a program contains many functions, many important data items are placed as
global so that they may be accessed by all the functions. Each function may have its own local
data. The global data are more at risk to an involuntary change by a function. Not only that it is
also very difficult to trace out what data is used by which function. While revising any of the
data structure, we need to revise the functions that access the data.
Another serious drawback with the procedural approach is that it does not model real world
problems very well.
Some characteristics exhibited by POP:
 Emphasis is on doing things (algorithms).
 Large programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

Object Oriented Programming Paradigm (OOP)


Object-Oriented Programming paradigm is the most recent concept among programming
paradigms. The major motivating factor in the invention of object-oriented approach is to remove
some of the flaws encountered in the procedural approach. OOP treats data as a critical element

2
in the program development and does not allow it to flow freely around the system. It ties data
more closely to the function that operate on it, and protects it from accidental modification from
outside functions. OOP allows decomposition of a problem into a number of entities called
objects and then builds data and function around these objects. The organization of data and
function in object-oriented paradigm is shown in fig. The data can be accessed only by the
functions associated with that object. However the functions of one object can access the
functions of other objects.
Some of the features of OOP:
 Emphasis is on data rather than procedure.
 Programs are divided into objects.
 Functions that operate on the data of an object are tied together in the data structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follows bottom-up approach in program design.
Object A Object B
Data Data

Function communication Function


s s

Object C
Data

Function
s

Fig 2:Organization of Data and Functions in OOP

Definition of OOP:

An object is a combination or collection of data and code designed to emulate a physical


or abstract entity. Each object has its own identity to distinguishable from other objects, a set of

3
properties and behavior.
Object oriented programming gives importance to relationships between objects rather
than implementation details. Hiding the implementation details within an object results in the
user being more concerned with an object’s relationship to the rest of the system, than the
implementation of the object’s behavior.

Basic Concepts of Object-Oriented Programming (OOP)

The following are some of the features used extensively in object-oriented programming.
They are:
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
1. Objects

In general, the object can be represented as a real thing entity that has an identity and
possessed some properties and behavior.
For example, an electric bulb is made by some company (identity) and it as some shape and
wattage (properties) and gives light (behavior).
Technically, objects are the basic run-time entities in an object-oriented system. They
may represent a person, a place, a bank account, a table of data or any item that the program has
to handle. The problem is analyzed in terms objects and the nature of communication between
them. The objects should be chosen in such a way they match closely with the real world objects.
When the program is executed, the objects interact by sending messages to one another.
For example, if “customer” and “account” are two objects in a program, then the customer object
may send a message to the account object requesting for the bank balance.
Every object will have data structures called attributes and behavior or operations that
manipulate the data. The different notations of an object uniting both the data and operations are

Total
shown in fig.3

STUDENT
Object : STUDENT
Total
DATA: Name
Date of Birth
Marks
Average

FUNCTIONS:
Total Display
Average
Display

Fig 3:Two ways of representing objects

2. Classes

We just discussed that objects contain both data and operations to manipulate the data.
Both the data and operations of an object put together with the help of a class and made them as
a user defined data type. In other sense, the objects are the variables of the class.
Once the class has been defined, we can create any number of objects belonging to that class. So,
a class is a collection of objects of similar type.
Example: In the class Person all the objects have similar data like Name, age, Sex and
operations like Speak, Listen, and walk. So boy and girl objects are grouped in to the Person
class.
Class Person
Data: Name, Age, Sex
Operations: Speak ( ), Listen ( ), Walk ( )
Person boy, girl; //objects of class Person

5
3. Data Abstraction and Encapsulation

The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of class. The data is not accessible
to the outside world, and only those operation or functions which are wrapped in the class can
access it. These functions provide the interface between the object’s data and the program. This
insulation of the data from direct access by the program is called data hiding or information
hiding.
Abstraction refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are defined as a
list of abstract data such as Name, age, Sex and operations to operate on these attributes. The
class encapsulates all the essential properties of the objects that are to be created. The attributes
are known as data members and operations are know an member functions or methods.
Since the classes use the concept of data abstraction, they are known as Abstract Data Type
(ADT).
4. Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects
of another class. It supports the concept of hierarchical classification. It allows the declaration
and implementation of one class to be based on an existing class.
For example, If the class Child inherits the all the features of class Parent, then the class Parent
referred as base class(super class) and the class child referred as derived class(sub class).
In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by deriving
a new class from the existing one. The new class will have the combined features of both the
classes.
Parent features
Base or Super class - Parent

Parent feature & Derived or sub class - Child


Child’s features

Fig 4: Inheritance

6
5. Polymorphism

Polymorphism is another important OOP concept. Polymorphism, a Greek term, means


the ability to take more than one form. An operation may exhibit different behaviors in different
instance. The behavior depends upon the types of data used in the operation.
For example, the operation addition can add two numbers but, the same operation when applied
on two strings, it concatenates.
The process of making an operator to exhibit different behaviors in different instances is
known as operator overloading. Similarly, a single function name can also behave differently
depending on the different number and different types of arguments and depending on the
context.
For example, the function Draw ( ) can be used to draw a circle, or a line or triangle depending
on where it is used. The process of using a single function to perform different tasks is known as
function overloading.

Shape

Draw ( )

Circle Object Box Object Triangle Object

Draw (circle) Draw (box) Draw (triangle)

Fig 5 Polymorphism

6. Dynamic binding

Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding (also known as late binding) means that the code associated with a
given procedure call is not known until the time of the call at run-time. It is associated with
polymorphism and inheritance.

7
7. Message passing

In conventional programming languages, a function is invoked on a piece of data


(function-driven communication), where as in OO languages, a message is sent to an object
(message driven communication).
In OO languages, the programming involves the following steps.
1. Creating classes that define objects and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another, The concept of message passing makes it easier to
talk about building systems that directly model or simulate their real-world counterparts.
A message for an object is a request for execution of a function. It invokes a function in
the receiving object that generates the desired result. It involves specifying the name of the
object, the name of the function (message) and the information to be sent.

Boy. Speaks (English);

Object message information

Benefits of OOP
OOP offers several benefits to both the program designer and the user. Object-orientation
contributes to the solution of many problems associated with the development and quality of
software products. The advantages are:
 Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
 We can build programs from the standard working modules that communicate with one
another.
 This leads to saving of development time and higher productivity.

8
 The principle of data hiding helps the programmer to build secure the programs.
 It is easy to partition the work in a project based on objects.
 Software complexity can be easily managed.
While it is possible to incorporate all these features in an object-oriented system, their
importance depends on the type of the project and the preference of the programmer.
Developing software that is easy to use makes it hard to build. It is hoped that the object-
oriented programming tools would help manage this problem.

Object Oriented Languages


The languages should support several of the OOP concepts to claim that they are object
oriented languages. Depending upon the features they support, they can be classified into the
following two categories:
1. Object-based programming languages.
2. Object-oriented programming languages.
1. Object-based programming: It is the style of programming that primarily supports
Encapsulation and object identity. Major features that are required for object based programming
are.
 Data encapsulation
 Data hiding and access mechanisms
 Automatic initialization and clear-up of objects
 Operator overloading
Languages that support programming with objects are said to be object-based programming
languages. They do not support inheritance and dynamic binding. Ada is a typical object-based
programming language.
2. Object-oriented programming: It is incorporates all of object-based programming features
along with two additional features, namely inheritance and dynamic binding.
Object Oriented features =object-based features + inheritance + dynamic binding
Languages that support these features include C++, Smalltalk, Object Pascal and java.

9
Features of OOP

Some of the features of OOP:


 Emphasis is on data rather than procedure.
 Programs are divided into objects.
 Functions that operate on the data of an object are tied together in the data structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follows bottom-up approach in program design.

How OOP differ from POP


Program and data are two basic elements of any computation. Among these, data plays an
important role and it can exist without a program, but a program has no relevance without data.
The high level languages stress on the algorithms used to solve a problem. When the
data defined as global, then data is accessible to all functions of a program without any
restriction. This method has reduced data security and integrity, since the entire data is available
to all the functions and any function can change any data.
Unlike the traditional methodology (POP), OOP emphasized on the data rather than the
algorithm. In OOPs data is encapsulated with the associated functions and this compartment is
called as object. In the OO approach, the problem is divided into objects, whereas in POP the
problem is divided into functions.
OO languages allow localization of data and code and restrict other objects from referring
to its local region. OOP is centered around the concepts of objects, encapsulation, inheritance,
polymorphism, message based communication, etc.
During the execution of a program, the objects interact with each other by sending
messages and receiving responses. For instance, in a program to perform withdrawals from an
account, a customer object can send a withdrawal message to a bank account object. An object
communicating with other objects need not be aware of the internal working of the objects with
which it interacts. The object’s internal structure is totally hidden from the user and this property

10
is called data/information hiding or data encapsulation.

Applications of OOP

Applications of OOP are beginning to gain importance in many areas. The most popular
application of OOP is in the area of user interface design such as windows. The other areas
include the following:
i) Real-time systems
ii) Simulation and modeling
iii) Object-oriented data bases
iv) Hypertext and hypermedia
v) AI and expert systems
vi) Neural networks and parallel programming
vii) Decision support and office automation systems
viii) CIM/CAM/CAD systems
The richness of OOP environment has enabled the software industry to improve not only the
quality of software systems but also its productivity.

Brief History of C++

C++ is a object-oriented programming language. It was developed by Bjarne Stroustrup


at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. It support
object-oriented programming features and still retain the power and elegance of C. Therefore
C++ is an extension of C with a major addition to the original C language. C++ is a superset of
C. Most of what we already discussed in C applies to C++ also. Therefore almost all C programs
are also C++ programs with few minor differences. The most important facilities that C++ adds
on to C are classes, inheritance, function overloading and operator overloading. These
features enable you to create abstract data types, inherit properties from existing data types and
support polymorphism, then making C++ a truly object-oriented language.

11
A Simple C++ Program

A simple example of a C++ program that prints a string on the screen.


Program 1: Printing a string on the screen
#include <iostream.h> //header file
int main() //main function
{
cout<<”Welcome to C++ language \n”; //C++ statement
return 0;
} //end of program
Output:
Welcome to C++ language
This program demonstrates several C++ features.

Features of a C++ Program

Like C, the C++ program is a collection functions such as main() as in above example.
Every program must have a main() and execution begins from main(). C++ is a free-form
language. Like C, the C++ statements terminate with semicolon.
Comments:

C++ introduces a new comment symbol //(double slash). Comments start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the program
and whatever follows till the end of the line is ignored. There is no closing symbol.
Ex.
//this is an example program

// for B1 learners

The C comments /* ….. */ are also valid and are more suitable for multiline comments.

Ex. /* this is an example program


For B1 learners */
Note: We can use either or both styles in our programs.
The iostream File:

12
The first line in the program

# include < iostream.h >

Causes the preprocessor to add the contents of the iostream file to the program. The
iostream file contains declarations for the identifiers ‘cout’ and ‘cin’ and the operators ‘<<’ and
‘>>’. The file should be included at the beginning of all programs that use input/output
statements.
Return Type of main ( ):

In C++, main() returns an integer type value to the operating system. Therefore, every
main() in C++ should end with a return (0) statement, otherwise, a warning or an error might
occur. Since main() returns an integer type value, return type for main() is explicitly specified as
int.
Example:
int main( ) //main return integer
{
----------;
-----------;
-----------;
return 0; //return zero statement
}

Input and output statements

Output Operator:

The syntax of cout statement

cout<<”Welcome to C++ language \n”; //one form of cout statement

The string in quotation marks to be displayed on the screen. The ‘cout’ is a predefined object that
represents the standard output stream (i.e., screen in this case) in C++. The operator ‘<<’ is called
the insertion or put to operator. It inserts (or sends) the contents of the variable on its right to the
object on its left. This corresponds to familiar printf() operation in C’.
Screen

13
cout << “C++”
Object Insertion Operator Variable

Fig 6:Output using insertion operator

The object ‘cout’ has a simple interface. If string represents a string variable, then following
statement will display its contents.
cout<<variable_name; //Another form cout statement
This statement prints the value of that particular variable_name on output screen.
Input Operator:

The syntax of cin statement:


cin>>variable_name; // cin is used for reads the value from keyboard

is an input statement and causes the program to wait for the user to type in a number. This
number keyed in is placed in the particular variable_name. The identifier ‘cin’ (pronounced
C’in) is also a predefined object in C++ that corresponds to the standard input stream (i.e., key
board in this case).
Object Extraction operator Variable

cin > 45.5


>

Keyboard
Fig 7: Input using extraction operator
The operator ‘>>’ is known as extraction or get from operator. It extracts (or takes) the value
from the keyboard and assigns it to the variable on its right. This corresponds to the familiar
scanf() operation in C’.
Cascading of input/output operators:

14
In the statement
cout<<”Another form of cout statement is:“<<variable_name<<”\n”;
we used insertion operator ‘<<’ repeatedly for printing the result. First we send the string
“Another form of cout statement is:“to cout and then send the value of ‘variable_name’. Finally,
it sends the new line character so that the next output will be in the new line. The multiple use of
‘<<’ in one statement is called cascading.
Similar to ‘<<” the extraction operator (‘>>”) can also cascade.
cin>>variable_name1>>variable_name2;
The values are assigned from left to right. i.e., in an input 10 20 , 10 will be assigned to
variable_name1 and 20 will be assigned to variable_name2.
Note: cin can read only one word and therefore we cannot use names with blank spaces.

Program 2:Write a program to input integer, float, char, and string using cin statement and
display using cout statement.

#include<iostream.h>
#include<conio.h>
int main( )
{
clrscr();
int i;
float f;
char ch;
char name[50];
cout<<”Enter the integer, float and character:”;
cin>>i>>f>>ch; //reading the values from keyboard
cout<<”Enter the string:”;
cin>>name;
cout<<”The values are:\n”;
cout<<” i = “<<i<<” f = “<<f<<” ch = “<<ch; //displaying the values on output screen

15
cout<<”\n name = “<<name;
getch();
return 0; // return zero statement
}
Output:
Enter the integer, float and character: 3 6.5 A
Enter the string: Radha
The values are:
i=3 f = 6.5 ch = A
name = Radha

Declaration of Variables:

All the variables must be declared before they are used in the program. Provided unlike in
C, in C++ you can declare the variables whenever there is a need for you any where in the
program even between the statements also.
Program 3: Write a program to find sum and average of two numbers.
# include < iostream.h >
int main()
{
float num1, num2; //declaration of variables
cout<<”Enter two numbers:”;
cin>>num1;
cin>>num2;
float sum; //declaration
sum=num1+num2;
cout<<”Sum is:”<<sum;
float average; //declaration
average=sum/2;
cout<<”Average is:”<<average;
return 0;
}

16
Output:
Enter two numbers: 3.3 5.3
Sum is: 8.6
Average is: 4.3
Note: The only disadvantage of this style of declaration is that we cannot see all the variables
used in a program at a glance.

Structure of C++ program

A typical program contains 4 sections as shown below.

Include files

Class declaration

Member functions definitions

Main function program

Structure of C++ program

It is a common practice to organize a program into three files. The class declarations are placed
in a header file and the definitions of member functions go into another file. This approach
enables the programmer to separate the abstract specification of the interface (class definition)
from the implementation details (member functions definition). Finally, the main program that
uses the class is placed in a third file which “includes” the previous two files as well as any other
files required.
Some of them(sections) are optional.
1) Include Files:
 Like C, C++ programs also depends upon some header files.
 Each header file has an extension of “.h”
 For example #include<iostream.h>

17
2) Class Declaration or Definition:
 A Class contains variables declaration, functions declaration/definition.
 The class declaration must be enclosed with curly braces ({ }) and terminated by a semi
colon(;).
Syntax:
class <class name>
{
Variables declaration; // called as data members (or) member variables
Function declaration/definition; // called as member functions
}; // End of class
3) Class function definitions:
 The class function definition can be done outside or inside the class declaration.
 If function is small then define inside the class.
 When the function is large then define outside the class. In this case prototype or
declaration of a function must be declared inside the class.
4) main( ) function:
Every C and C++ program execution starts from main( ) function, hence it is compulsory.

namespace scope

A namespace is a declarative region that provides a scope to the identifiers (the names of types,
functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and
to prevent name collisions that can occur especially when your code base includes multiple
libraries. All identifiers at namespace scope are visible to one another without qualification.
#include <iostream>

using namespace std;

// Variable created inside namespace


namespace first
{
int val = 500;
}

18
int main()
{
// Local variable
int val = 200;

// These variables can be accessed from


// outside the namespace using the scope
// operator ::
cout << first::val << '\n';
cout << val << '\n';

return 0;
}

Output:
500
200

C++ Tokens
A token is the smallest unit that can be processed by a c++ compiler. It can be categorized into
different types namely:-
keywords

identifier
TOKENS s
constants

strings

operators

Keywords (or reserved words):- These are the words used for special purposes or predefined
tasks. These words should be written in small letters or lowercase letters. Some of the keyword
used in c++ are int, float, char, double, long, void, for, while, do, if, else...

19
C++ Keyword List :

asm else operator template

auto enum private this

break extern protected throw

case float public try

catch for register typedef

char friend return union

class goto short unsigned

const if signed virtual

continue inline sizeof void

default int static volatile

delete long struct while

double new switch -

Keywords cannot be used for the –

1. Declaring Variable Name

2. Declaring Class Name

3. Declaring Function Name

4. Declaring Object Name


5. Constants are the items whose value cannot be changed during the program execution.

Identifiers:- It is a name used to represent a variable constant, array name, function name, class,
object etc. There are some rules while defining an identifier:-
i) The first character of identifier should be an alphabet or underscore. The rest can be letters or
digits or underscore.
ii) Special characters except underscore can’t be part of identifiers.
iii) Keywords can’t be used as identifiers however keywords written in uppercase form can be

20
used as identifiers.
iv) Lower case and upper case letters are distinct.
v) Maximum length of an identifier can be of 31 characters. However the length varies from one
version of compiler to another version.
Some valid examples:- sum, a1, a2, _1, _a, average, a_b, x123y...
Some invalid examples:- 1a, a-b, float

Constants:- A value which remain constant throughout the program execution is known as
constant. An identifier can be declared as a constant as illustrated below:-
i) # define N 20
ii) # define PI 3.14
iii) const int M=35; or const m=35;
Note:- When the constant identifier is of type integer, then keyword int is optional. As a default
the identifier is considered as integer. Only one value can be declared as constant at a time with
the keyword const
Variables:- An identifier whose value can be modified/ altered is known as a variable. A variable
can be declared as shown below.
int a;
float x;
char ch;
Here a is a variable of type integer, x is a variable of type float, where as ch is a
variable of type char. Values can be assigned with a, x & ch as shown below.
a=10; x=7.5; ch=’d’; a=a+5; x=x-4;

Literals:- The constant values used in c++ are known as literals, there are four type of literals
namely.
i) Integer constant:- A value written without fraction part is known as integer constant. Example:
25, -674, 0 etc.
ii) Floating constant:- A value written with fraction part is floating value. Value of this type can
be written with or without exponent form. Example: 2.34, -9.2154, 1.21E10

21
iii) Character constant:- A single character written within single quotation marks is known as
character constant. Example: ‘g’, ‘9’, ‘$’ etc
iv) String constant:- It is an array of characters enclosed in double quotation marks. Example:
“Shubham”, “03-aug-2009”. Double quotation mark is a delimiter which determines length of a
string.

Data types

In c++ a data type indicates what type of value can be assigned with an identifier. The data types
can be grouped into 3 types:-

a) Basic data type or built in data type:- This data type provided by the compiler can be used
to declare an identifier as constant or variable. There are 5 types of basic data types:-
i) int:- This datatype is used to assign a value without fraction. It needs 2 bytes of storage
space. Short int, signed int, unsigned int, long int are also part of integer used for different
purpose. Its range is -32768 to 32767
ii) float:- This datatype is used to assign a floating value written with or without
exponents. It needs 8 bytes of storage space. Its range is 1.7E-308 to 1.7E308. Its range can be

22
extended by using long double datatype.
iii) char:- This datatype deals with single character enclosed in single quotes. It uses 1
byte of memory space.
iv) void:- It represents no value i.e. an empty set. It is mainly used in functions to
indicate that these functions do not return any value.

b) Derived data type:- This type of data type can be derived from basic datatypes. Example: array,
pointers, references.
c) User defined datatype:- This type can be obtained by grouping inter related data. Example
structure, class, type def.

C++ User Defined Data Types


C++ allows you to use one or more data types, group them as one, to create a new data type as
you see fit. This technique of grouping different values is referred to as a class. C++ offers three
techniques of defining a new data type: a structure, a class, and a union. These are also referred
to as composite data types.

Structures

A structure is one or a group of variables considered as a (custom) data type. To create a


structure, use the struct keyword, followed by a name for the object, at least followed by a semi-
colon. Therefore, fundamentally, a structure can be created as:

struct <Name>{};

The struct keyword is required. The name of the structure follows the same rules we reviewed for
C++ names.

The section between the curly brackets is referred to as the body of the structure. Inside of this
body, you can declare at least one variable that would be used to define the structure. The
variable must be declared complete with a known data type, a name and the ending semi-colon.
Here is an example:

Eg:

23
struct students
{
char name[10]; //name of student
int SSN; // social security number
char cardtype[10];
float balance;
}

Unions

A union is a user-defined data or class type that, at any given time, contains only one object from
its list of members (although that object can be an array or a class type).

union [tag] { member-list } [declarators]; [union] tag declarators;

Parameters
Tag-The type name given to the union.
member-list
declarators- Declarator list specifying the names of the union.
Declaring a Union
Begin the declaration of a union with the union keyword, and enclose the member list in curly
braces:

24
// declaring_a_union.cpp

union DATATYPE // Declare union type

char ch;

int i;

long l;

float f;

double d;

} var1; // Optional declaration of union variable

Using a Union
A C++ union is a limited form of the class type. It can contain access specifiers (public,
protected, private), member data, and member functions, including constructors and destructors.
It cannot contain virtual functions or static data members. It cannot be used as a base class, nor
can it have base classes. Default access of members in a union is public.

A C union type can contain only data members.

In C, you must use the union keyword to declare a union variable. In C++, the union keyword is
unnecessary:

union DATATYPE var2; // C declaration of a union variable

DATATYPE var3; // C++ declaration of a union variable

A variable of a union type can hold one value of any type declared in the union. Use the member-
selection operator (.) to access a member of a union:

var1.i = 6; // Use variable as integer

var2.d = 5.327; // Use variable as double

You can declare and initialize a union in the same statement by assigning an expression enclosed
in braces. The expression is evaluated and assigned to the first field of the union.

25
Eg:

// using_a_union.cpp

#include <iostream>

union NumericType

int iValue;

long lValue;

double dValue;

};

int main()

union NumericType Values = { 10 }; // iValue = 10

printf_s("%d\n", Values.iValue);

Values.dValue = 3.1416;

printf_s("%f\n", Values.dValue);

Output:

10

3.141600

Classes

In object-oriented programming language C++, the data and functions (procedures to manipulate
the data) are bundled together as a self-contained unit called an object. A class is an extended
concept similar to that of structure in C programming language; this class describes the data
properties alone. In C++ programming language, class describes both the properties (data) and
behaviors (functions) of objects. Classes are not objects, but they are used to instantiate objects.

26
Features of Class:

Classes contain data known as members and member functions. As a unit, the collection of
members and member functions is an object. Therefore, this unit of objects makes up a class.

How to write a Class:


In C programming language, a structure is specified with a name. The C++ programming
language extends this concept. A class is specified with a name after the keyword class.

The starting flower brace symbol, { is placed at the beginning of the code. Following the flower
brace symbol, the body of the class is defined with the member functions data. Then the class is
closed with a flower brace symbol } and concluded with a semicolon; .

class example
{
data;
member functions;
……………
};
There are different access specifiers for defining the data and functions present inside a class.

Enum as Data type


Enumerated type declares a new type-name and a sequence of value containing identifiers which
has values starting from 0 and incrementing by 1 every time.

For Example :

enum day(mon, tues, wed, thurs, frid);


Here an enumeration of days is defined with variable d. mon will hold value 0, tue will have 1
and so on. We can also explicitly assign values, like, enum day(mon, tue=7, wed);.
Here, mon will be 0, tue is assigned 7, so wed will have value 8.

27
Storage Classes in C++
Storage classes are used to specify the lifetime and scope of variables. How storage is allocated
for variables and how a variable is treated by complier depends on these storage classes.

These are basically divided into 5 different types:

1. Global variables

2. Local variables
3. Register variables
4. Static variables
5. Extern variables

Global Variables: These are defined at the starting, before all function bodies and are available
throughout the program.
using namespace std;

int globe; // Global variable

void func();

int main()

.....

Local variables: They are defined and are available within a particular scope. They are also
called Automatic variable because they come into being when scope is entered and automatically
go away when the scope ends.The keyword auto is used, but by default all local variables are
auto, so we don't have to explicitly add keyword auto before variable declaration. Default value
of such variable is garbage.

Register variables: This is also a type of local variable. This keyword is used to tell the
compiler to make access to this variable as fast as possible. Variables are stored in registers to
increase the access speed. But you can never use or compute address of register variable and also
a register variable can be declared only within a block, that means, you cannot
have global or static register variables.

28
Static Variables: Static variables are the variables which are initialized & allocated storage only
once at the beginning of program execution, no matter how many times they are used and called
in the program. A static variable retains its value until the end of program.

void fun()
{
static int i = 10;
i++;
cout << i;
}
int main()
{
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13
}
As, i is static, hence it will retain its value through function calls, and is initialized only once at
the beginning.
Extern Variables: This keyword is used to access variable in a file which is declared & defined
in some other file, that is the existence of a global variable in one file is declared using
extern keyword in another file.

Dynamic Initialization of Variables


The process of initializing variable at the time of its declaration at run time is known as dynamic
initialization of variable. Thus in dynamic initialization of variable a variable is assigned value at
run time at the time of its declaration.

Example:
main()
{
Int a;
cout<<“Enter Value of a”;
cin>>a;
int cube = a * a * a;
}
In above example variable cube is initialized at run time using expression a * a * a at the time of
its declaration.

29
Reference Variables
A reference variable allows us to create an alternative name for already defined variable.

It is introduced in C++. Once you define a reference variable that references already defined
variable then you can use any of them alternatively in the program. Both refer to the same
memory location.
Thus if you change value of any of the variable it will affect both variables because one variable
reference to another variable.

The general syntax of creating reference variable is given below:

Data-type & Referace_Name = Variable_Name;

The reference variable must initialize at the time of declaration.

Example:
int count;
count = 5;
Int & incre = count;
Here,
We have already defined variable named count.
Then we create a reference variable named incre that refer to the variable count.Since both
variable refer to same memory location if you change value of variable count using following
statement:
count=count + 5;

Will change the value of variable count and incre to 10. The major use of reference variable is in
function. If we want to pass reference of the variable at the time of function call so that the
function works with original variable we can use reference variable.

30
Scope resolution operator in c++
Scope resolution operator(::) is used to define a function outside a class or when we want to use a
global variable but also has a local variable with same name.

C++ programming code


#include <iostream>
using namespace std;
char c = 'a'; // global variable

int main() {
char c = 'b'; //local variable

cout << "Local variable: " << c << "\n";


cout << "Global variable: " << ::c << "\n"; //using scope resolution operator

return 0;
}

Output of program:

Local variable: b
Global variable: a

Scope resolution operator in class


#include <iostream>
using namespace std;

class programming {
public:
void output(); //function declaration
};

// function definition outside the class


void programming::output() {
cout << "Function defined outside the class.\n";
}
int main() {

31
programming x;
x.output();
return 0;
}

Member Dereferencing Operators


C++ permits us to define the class members through pointers. In order to
achieve this, c++ provides a set of three pointer-to-member operators.

operator Function
::* To declare a pointer to a member of a class
* To access a member using object name and a pointer to that member
->* To access a member using a pointer to the object and a pointer to that
member
C++ Memory Management Operators

Need for Memory Management operators:


The concept of arrays has a block of memory reserved. The disadvantage with the concept of
arrays is that the programmer must know, while programming, the size of memory to be
allocated in addition to the array size remaining constant.

In programming there may be scenarios where programmers may not know the memory needed
until run time. In this case, the programmer can opt to reserve as much memory as possible,
assigning the maximum memory space needed to tackle this situation. This would result in
wastage of unused memory spaces. Memory management operators are used to handle this
situation in C++ programming language.

There are two types of memory management operators in C++:


new
delete
These two memory management operators are used for allocating and freeing memory blocks in
efficient and convenient ways.

32
new operator:
The new operator in C++ is used for dynamic storage allocation. This operator can be used to
create object of any type.
The general syntax of new operator in C++ is as follows:
pointer variable = new datatype;

delete operator:
The delete operator in C++ is used for releasing memory space when the object is no longer
needed. Once a new operator is used, it is efficient to use the corresponding delete operator for
release of memory.

The general syntax of delete operator in C++ is as follows:

delete pointer variable;

Example1:

#include <iostream>
using namespace std;
void main()
{
//Allocates using new operator memory space in memory for storing a integer datatype
int *a= new int;
*a=100;
cout << " The Output is:a= " << *a;
//Memory Released using delete operator
delete a;

}
Example 2:
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;

// memory allocation of num number of floats


ptr = new float[num];

33
cout << "Enter GPA of students." << endl;
for (int i = 0; i < num; ++i)
{
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}

cout << "\nDisplaying GPA of students." << endl;


for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << " :" << *(ptr + i) << endl;
}

// ptr memory is released


delete [] ptr;

return 0;
}

34

Potrebbero piacerti anche