0% found this document useful (0 votes)
151 views56 pages

OOPS Study Material Unit 1&2-2-1-1 PDF

The document discusses the topics covered in 5 units of an Object Oriented Programming course using C++. Unit I introduces OOP concepts like objects, classes, inheritance, polymorphism and overloading. It also covers basic C++ concepts. Unit II discusses classes, objects, constructors, destructors and operator overloading. Unit III covers arrays and operator overloading. Unit IV discusses inheritance, memory management and pointers. Unit V introduces virtual functions, friend functions and templates. The textbook and reference books for the course are also listed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
151 views56 pages

OOPS Study Material Unit 1&2-2-1-1 PDF

The document discusses the topics covered in 5 units of an Object Oriented Programming course using C++. Unit I introduces OOP concepts like objects, classes, inheritance, polymorphism and overloading. It also covers basic C++ concepts. Unit II discusses classes, objects, constructors, destructors and operator overloading. Unit III covers arrays and operator overloading. Unit IV discusses inheritance, memory management and pointers. Unit V introduces virtual functions, friend functions and templates. The textbook and reference books for the course are also listed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

CS2T5 - OBJECT ORIENTED PROGRAMMING USING C++

UNIT- I
Need for object oriented programming, Characteristics of object oriented language -
objects, classes, Inheritance, Reusability, creating new data types, Polymorphism
and overloading. C++ programming basics Data types, Manipulators, Cin, Cout,
Type conversion, arithmetic operators, Loops and decisions.

UNIT- II
Class and objects : A simple class, C++ Objects as physical Objects, C++ Objects as
Data Types, Constructors, destructors, objects as function arguments,overloaded
constructors, member functions defined outside the class, inline functions,
Returning objects from Functions.

UNIT – III
Arrays : Defining & accessing Array elements, arrays as class member data, array of
Objects.Operator Overloading : Overloading Unary Operators, Operator Arguments,
Return Values, nameless Temporary objects, postfix notations. Overloading Binary
Operators - Arithmetic operators, Concatenating Strings, Multiple overloading
Comparison operators, Arithmetic Assignment Operators.

UNIT- IV
Inheritance-Derived class and base class, derived class constructors, overriding
member functions, Class Hierarchies, Abstract base class, Public and private
inheritance, Levels of inheritance, Multiple inheritance. Memory management new
and delete operator, a string class using new, Pointers to Objects Referring to
Members, another Approach to new, An array of pointers to Objects.

UNIT- V
Virtual Functions, Pure virtual functions, Late Binding, Abstract Classes, Virtual
base classes. Friend Functions Friend Classes, Friends for functional Notation.
Static Functions , investigating destructors. Assignment and copy initialization-
overloading the assignment operator, the copy constructor, the this pointer.
Templates - function templates, class template, File Handling-Introduction to
graphics

TEXT BOOKS:

1. Object Oriented Programming in Microsoft C++ - Robert Lafore,Galgotia


Publication Pvt Ltd.

2. Let us C++ - Yaswant Kanitkar( for templates) ,BPB Publication

REFERENCE BOOKS:

1. Object Oriented Programming in C++ - E. Balaguruswamy, Tata Mcgraw Hill.

2. Teach yourself C++ - Herbertsehildt, OSBORNE/MH


UNIT- I
Introduction of C++

C++ is an 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. Stroustrup,
an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both the
languages and create a more powerful language that could support object-oriented
programming features and still retain the power and elegance of C. The result was C++.

C+ + is a superset of C. Almost all c programs are also C++ programs. However, there are a
few minor differences that will prevent a c program to run under C++ complier. We shall see
these differences later as and when they are encountered. The most important facilities that
C++ adds on to C care classes, inheritance, function overloading and operator overloading.
These features enable creating of abstract data types, inherit properties from existing data
types and support polymorphism, thereby making C++ a truly object-oriented language.

Need for object oriented programming


Object Oriented Paradigm

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 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 function. 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 programs is shown in fig.1.3. The data of an object can
be accessed only by the function associated with that object. However, function of one object
can access the function of other objects.

Some of the features of object oriented programming are:

• Emphasis is on data rather than procedure.


• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.

Object-oriented programming is the most recent concept among programming paradigms and
still means different things to different people.

Advantages of OOP

Object-Oriented Programming has the following advantages:


1. OOP provides a clear modular structure for programs which makes it good for
defining abstract datatypes where implementation details are hidden and the unit
has a clearly defined interface.
2. OOP makes it easy to maintain and modify existing code as new objects can be
created with small differences to existing ones.
3. OOP provides a good framework for code libraries where supplied software
components can be easily adapted and modified by the programmer. This is
particularly useful for developing graphical user interfaces.

Basic Concepts of Object Oriented Programming

It is necessary to understand some of the concepts used extensively in object-oriented


programming. These include:

• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing

We shall discuss these concepts in some detail in this section.

Objects

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.
They may also represent user-defined data such as vectors, time and lists. Programming
problem is analyzed in term of objects and the nature of communication between them.
Program objects should be chosen such that they match closely with the real-world
objects. Objects take up space in the memory and have an associated address like a record
in Pascal, or a structure in c.

When a program is executed, the objects interact by sending messages to one another. Foe
example, if “customer” and “account” are to object in a program, then the customer object
may send a message to the count object requesting for the bank balance. Each object
contain data, and code to manipulate data. Objects can interact without having to know
details of each other’s data or code. It is a sufficient to know the type of message
accepted, and the type of response returned by the objects. Although different author
represent them differently fig 1.5 shows two notations that are popularly used in object-
oriented analysis and design.

Classes

We just mentioned that objects contain data, and code to manipulate that data. The entire set
of data and code of an object can be made a user-defined data type with the help of class. In
fact, objects are variables of the type class. Once a class has been defined, we can create any
number of objects belonging to that class. Each object is associated with the data of type class
with which they are created. A class is thus a collection of objects similar types. For
examples, Mango, Apple and orange members of class fruit. Classes are user-defined that
types and behave like the built-in types of a programming language. The syntax used to
create an object is not different then the syntax used to create an integer object in C. If fruit
has been defines as a class, then the statement

Fruit Mango;
Will create an object mango belonging to the class fruit.

Data Abstraction and Encapsulation

The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data and encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those 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 explanation. Classes use the concept of abstraction and are defined as a
list of abstract attributes such as size, wait, and cost, and function operate on these attributes.
They encapsulate all the essential properties of the object that are to be created. The attributes
are some time called data members because they hold information. The functions that operate
on these data are sometimes called methods or member function.

Inheritance

Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification. For example, the bird,
‘robin’ is a part of class ‘flying bird’ which is again a part of the class ‘bird’. The principal
behind this sort of division is that each derived class shares common characteristics with the
class from which it is derived as illustrated in fig 1.6.

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 feature of both the
classes. The real appeal and power of the inheritance mechanism is that it

Allows the programmer to reuse a class i.e almost, but not exactly, what he wants, and to
tailor the class in such a way that it does not introduced any undesirable side-effects into
the rest of classes.

Polymorphism

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


the ability to take more than on form. An operation may exhibit different behavior is
different instances. The behavior depends upon the types of data used in the operation.
For example, consider the operation of addition. For two numbers, the operation will
generate a sum. If the operands are strings, then the operation would produce a third
string by concatenation. The process of making an operator to exhibit different behaviors
in different instances is known as operator overloading. Fig. 1.7 illustrates that a single
function name can be used to handle different number and different types of argument.
This is something similar to a particular word having several different meanings
depending upon the context. Using a single function name to perform different type of
task is known as function overloading.

Polymorphism plays an important role in allowing objects having different internal


structures to share the same external interface. This means that a general class of
operations may be accessed in the same manner even though specific action associated
with each operation may differ. Polymorphism is extensively used in implementing
inheritance.

Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response
to the call. Dynamic 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. A function call associated with a polymorphic reference depends on the dynamic
type of that reference.

Consider the procedure “draw” in fig. 1.7. by inheritance, every object will have this
procedure. Its algorithm is, however, unique to each object and so the draw procedure will be
redefined in each class that defines the object. At run-time, the code matching the object
under current reference will be called.

Message Passing

An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic
steps:
1. Creating classes that define object 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 procedure, and therefore will invoke a
function (procedure) in the receiving object that generates the desired results. Message
passing involves specifying the name of object, the name of the function (message) and the
information to be sent. Example:

Object has a life cycle. They can be created and destroyed. Communication with an object
is feasible as long as it is alive.

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 new technology promises greater programmer productivity, better
quality of software and lesser maintenance cost.
The principal advantages are:

• Through inheritance, we can eliminate redundant code extend the use of existing
• Classes.
• We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of development time and higher productivity.
• The principle of data hiding helps the programmer to build secure program that can not
be invaded by code in other parts of a programs.
• It is possible to have multiple instances of an object to co-exist without any interference.
• It is possible to map object in the problem domain to those in the program.
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables us to capture more detail of a model can
implemental form.
• Object-oriented system can be easily upgraded from small to large system.
• Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
• 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. There
are a number of issues that need to be tackled to reap some of the benefits stated above. For
instance, object libraries must be available for reuse. The technology is still developing and
current product may be superseded quickly. Strict controls and protocols need to be
developed if reuse is not to be compromised.

Object Oriented Language

Object-oriented programming is not the right of any particular languages. Like structured
programming, OOP concepts can be implemented using languages such as C and Pascal.
However, programming becomes clumsy and may generate confusion when the programs
grow large. A language that is specially id designed to support the OOP concepts makes it
easier to implement them.

The languages should support several of the OOP concepts to claim that they are object-
oriented. Depending upon the features they support, they can be classified into the following
two categories:
1. Object-based programming languages, and
2. Object-oriented programming languages.

Object-based programming is the style of programming that primarily supports


encapsulation and object identity. Major feature 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 the objects-based programming
languages. They do not support inheritance and dynamic binding. Ada is a typical object-
based programming language.
Object-oriented programming language incorporates all of object-based programming
features along with two additional features, namely, inheritance and dynamic binding.
Object-oriented programming can therefore be characterized by the following statements:
Object-based features + inheritance + dynamic binding

Application of OOP

OOP has become one of the programming buzzwords today. There appears to be a great deal
of excitement and interest among software engineers in using OOP. Applications of OOP are
beginning to gain importance in many areas. The most popular application of object-oriented
programming, up to now, has been in the area of user interface design such as window.
Hundreds of windowing systems have been developed, using the OOP techniques.
Real-business system are often much more complex and contain many more objects with
complicated attributes and method. OOP is useful in these types of application because it can
simplify a complex problem. The promising areas of application of OOP include:

• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems

The object-oriented paradigm sprang from the language, has matured into design, and has
recently moved into analysis. It is believed that the richness of OOP environment will
enable the software industry to improve not only the quality of software system but also
its productivity. Object-oriented technology is certainly going to change the way the
software engineers think, analyze, design and implement future system.

Application of C++

C++ is a versatile language for handling very large programs; it is suitable for virtually any
programming task including development of editors, compilers, databases, communication
systems and any complex real life applications systems.

• Since C++ allow us to create hierarchy related objects, we can build special object-
oriented libraries which can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get closed to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to be
implemented, it is very easy to add to the existing structure of an object.
• It is expected that C++ will replace C as a general-purpose language in the near future.

Simple C++ Program

Let us begin with a simple example of a C++ program that prints a string on the screen.
This simple program demonstrates several C++ features.

Program feature

Like C, the C++ program is a collection of function. The above example contain only one
function main(). As usual execution begins at main(). Every C++ program must have a
main(). C++ is a free form language. With a few exception, the compiler ignore carriage
return and white spaces. Like C, the C++ statements terminate with semicolons.
Comments

C++ introduces a new comment symbol // (double slash). Comment start with a double slash
symbol and terminate at the end of the line. A comment may start anywhere in the line, and
whatever follows till the end of the line is ignored. Note that there is no closing symbol.

The double slash comment is basically a single line comment. Multiline comments can be
written as follows:

// This is an example of
// C++ program to illustrate
// some of its features
The C comment symbols /*,*/ are still valid and are more suitable for multiline comments.

The following comment is allowed:

/* This is an example of
C++ program to illustrate
some of its features
*/
Output operator

The only statement in program is an output statement. The statement Cout<<”C++ is better
than C.”;

Causes the string in quotation marks to be displayed on the screen. This statement introduces
two new C++ features, cout and <<. The identifier cout(pronounced as C out) is a predefined
object that represents the standard output stream in C++. Here, the standard output stream
represents the screen. It is also possible to redirect the output to other output devices. The
operator << is called the insertion or put to operator.

The iostream File

We have used the following #include directive in the program:


#include <iostream>
The #include directive instructs the compiler to include the contents of the file enclosed
within angular brackets into the source file. The header file iostream.h should be included at
the beginning of all programs that use input/output statements.

Namespace

Namespace is a new concept introduced by the ANSI C++ standards committee. This defines
a scope for the identifiers that are used in a program. For using the identifier defined in the
namespace scope we must include the using directive, like
Using namespace std;
Here, std is the namespace where ANSI C++ standard class libraries are defined. All ANSI
C++ programs must include this directive. This will bring all the identifiers defined in std to
the current global scope. Using and namespace are the new keyword of C++.
Return Type of main()

In C++, main () returns an integer value to the operating system. Therefore, every main () in
C++ should end with a return (0) statement; otherwise a warning an error might occur. Since
main () returns an integer type for main () is explicitly specified as int. Note that the default
return type for all function in C++ is int. The following main without type and return will run
with a warning:

More C++ Statements

Let us consider a slightly more complex C++ program. Assume that we should like to read
two numbers from the keyboard and display their average on the screen. C++ statements to
accomplish this is shown in below program

Variables

The program uses four variables number1, number2, sum and average. They are declared as
type float by the statement.

float number1, number2, sum, average;


All variable must be declared before they are used in the program.
Input Operator

The statement cin >> number1;

Is an input statement and causes the program to wait for the user to type in a number. The
number keyed in is placed in the variable number1. The identifier cin (pronounced ‘C in’) is a
predefined object in C++ that corresponds to the standard input stream. Here, this stream
represents the keyboard.

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 fig 1.8. This corresponds to a
familiar scanf() operation. Like <<, the operator >> can also be overloaded.

Cascading of I/O Operators

We have used the insertion operator << repeatedly in the last two statements for printing
results.

The statement
Cout << “Sum = “ << sum << “\n”;

First sends the string “Sum = “ to cout and then sends the value of sum. Finally, it sends the
newline character so that the next output will be in the new line. The multiple use of << in
one statement is called cascading. When cascading an output operator, we should ensure
necessary blank spaces between different items. Using the cascading technique, the last two
statements can be combined as follows:

Cout << “Sum = “ << sum << “\n”


<< “Average = “ << average << “\n”;
This is one statement but provides two line of output. If you want only one line of output, the
statement will be:
Cout << “Sum = “ << sum << “,”
<< “Average = “ << average << “\n”;

The output will be:

Sum = 14, average = 7


We can also cascade input iperator >> as shown below:

Cin >> number1 >> number2;

The values are assigned from left to right. That is, if we key in two values, say, 10 and 20,
then 10 will be assigned to munber1 and 20 to number2.

An Example with Class

• One of the major features of C++ is classes. They provide a method of binding together data
and functions which operate on them. Like structures in C, classes are user-defined data
types.
The program define person as a new data of type class. The class person includes two
basic data type items and two function to operate on that data. These functions are called
member function. The main program uses person to declare variables of its type. As
pointed out earlier, class variables are known as objects. Here, p is an object of type
person. Class object are used to invoke the function defined in that class.

Structure of C++ Program

A typical C++ program would contain four sections as shown in fig below This section may
be placed in separate code files and then compiled independently or jointly. It is a common
practice to organize a program into three separate 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 from the
implementation details (member function definition). Finally, the main program that uses the
class is places in a third file which “includes: the previous two files as well as any other file
required.

This approach is based on the concept of client-server model as shown in fig. 1.10. The class
definition including the member functions constitute the server that provides services to the
main program known as client. The client uses the server through the public interface of the
class.
The client-server model
Creating new datatypes: Enumerations (enum)

Enumerations create new data types to contain something different that is not limited to the
values fundamental data types may take. Its form is the following:

enum enumeration_name {
value1,
value2,
value3,
.
.
} object_names;

For example, we could create a new type of variable called colors_t to store colors with the
following declaration:

enum colors_t {black, blue, green, cyan, red, purple, yellow, white};

Notice that we do not include any fundamental data type in the declaration. To say it
somehow, we have created a whole new data type from scratch without basing it on any other
existing type. The possible values that variables of this new type color_t may take are the
new constant values included within braces. For example, once the colors_tenumeration is
declared the following expressions will be valid:
1 colors_t mycolor;
2
3 mycolor = blue;
4 if (mycolor == green) mycolor = red;
Enumerations are type compatible with numeric variables, so their constants are always
assigned an integer numerical value internally. If it is not specified, the integer value
equivalent to the first possible value is equivalent to 0 and the following ones follow a +1
progression. Thus, in our data type colors_t that we have defined above, black would be
equivalent to 0, blue would be equivalent to 1, green to 2, and so on.

We can explicitly specify an integer value for any of the constant values that our enumerated
type can take. If the constant value that follows it is not given an integer value, it is
automatically assumed the same value as the previous one plus one. For example:

1 enum months_t { january=1, february, march, april,


2 may, june, july, august,
3 september, october, november, december} y2k;

In this case, variable y2k of enumerated type months_t can contain any of the 12 possible
values that go from januaryto december and that are equivalent to values
between 1 and 12 (not between 0 and 11, since we have made januaryequal to 1).
Data types -Primitive Built-in Types:

C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types −
Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double

Valueless void

Wide character wchar_t

Several of the basic types can be modified using one or more of these type modifiers −
 signed
 unsigned
 short
 long
The following table shows the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.

Type Typical Bit Width Typical Range

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int Range 0 to 65,535

signed short int Range -32768 to 32767


long int 4bytes -2,147,483,648 to 2,147,483,647

signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character

The size of variables might be different from those shown in the above table, depending on
the compiler and the computer you are using.
Following is the example, which will produce correct size of various data types on your
computer.

#include <iostream>
using namespace std;

int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;

return 0;
}

This example uses endl, which inserts a new-line character after every line and << operator
is being used to pass multiple values out to the screen. We are also using sizeof() operator to
get size of various data types.
When the above code is compiled and executed, it produces the following result which can
vary from machine to machine –

Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
Manipulators:

endl is the line feed operator in C++. It acts as a stream manipulator whose purpose is to feed
the whole line and then point the cursor to the beginning of the next line. We can use \n (\n is
an escape sequence) instead of endl for the same purpose.
setw Manipulator

This manipulator sets the minimum field width on output.


Syntax:
setw(x)
Example:
/*
* File: main.cpp
* Author: Gautam
* Created on October 16, 2011, 12:58 PM
*/#include <iostream>
#include <iomanip>
using namespace std;

int main() {

float basic, ta,da,gs;


basic=10000; ta=800; da=5000;
gs=basic+ta+da;
cout<<setw(10)<<"Basic"<<setw(10)<<basic<<endl
<<setw(10)<<"TA"<<setw(10)<<ta<<endl
<<setw(10)<<"DA"<<setw(10)<<da<<endl
<<setw(10)<<"GS"<<setw(10)<<gs<<endl;
return 0;
}
Type Casting:

A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator.

The most general cast supported by most of the C++ compilers is as follows
(type) expression
Where type is the desired data type.
#include <iostream>
using namespace std;

main() {
double a = 21.09399;
float b = 10.20;
int c ;

c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ;

c = (int) b;
cout << "Line 2 - Value of (int)b is :" << c << endl ;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Line 1 - Value of (int)a is :21
Line 2 - Value of (int)b is :10

Operators in C++:

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by C++ language. Assume variable A
holds 10 and variable B holds 20, then

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the A - B will give -10


first

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of B % A will give 0


after an integer division

++ Increment operator, increases A++ will give 11


integer value by one
-- Decrement operator, decreases A-- will give 9
integer value by one

Relational Operators

There are following relational operators supported by C++ language. Assume variable A
holds 10 and variable B holds 20, then
Operator Description Example

== Checks if the values of two operands (A == B) is not true.


are equal or not, if yes then condition
becomes true.

!= Checks if the values of two operands (A != B) is true.


are equal or not, if values are not
equal then condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right
operand, if yes then condition
becomes true.

< Checks if the value of left operand is (A < B) is true.


less than the value of right operand, if
yes then condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of
right operand, if yes then condition
becomes true.

<= Checks if the value of left operand is (A <= B) is true.


less than or equal to the value of right
operand, if yes then condition
becomes true.

Logical Operators

There are following logical operators supported by C++ language. Assume variable A holds
1 and variable B holds 0, then

Operator Description Example

&& Called Logical AND operator. If both (A && B) is false.


the operands are non-zero, then
condition becomes true.
|| Called Logical OR Operator. If any of (A || B) is true.
the two operands is non-zero, then
condition becomes true.

! Called Logical NOT Operator. Use to !(A && B) is true.


reverses the logical state of its
operand. If a condition is true, then
Logical NOT operator will make
false.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ are as follows
p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then

Operator Description Example

& Binary AND Operator copies a bit to (A & B) will give 12 which is 0000
the result if it exists in both operands. 1100

| Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011


exists in either operand. 1101

^ Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011
it is set in one operand but not both. 0001
~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100
unary and has the effect of 'flipping' 0011 in 2's complement form due to a
bits. signed binary number.

<< Binary Left Shift Operator. The left


operands value is moved left by the A << 2 will give 240 which is 1111
number of bits specified by the right 0000
operand.

>> Binary Right Shift Operator. The left


operands value is moved right by the A >> 2 will give 15 which is 0000
number of bits specified by the right 1111
operand.

Assignment Operators

There are following assignment operators supported by C++ language

Operator Description Example

= Simple assignment operator, Assigns


C = A + B will assign value of A +
values from right side operands to left
B into C
side operand.

+= Add AND assignment operator, It adds


right operand to the left operand and C += A is equivalent to C = C + A
assign the result to left operand.

-= Subtract AND assignment operator, It


subtracts right operand from the left
C -= A is equivalent to C = C - A
operand and assign the result to left
operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left
C *= A is equivalent to C = C * A
operand and assign the result to left
operand.

/= Divide AND assignment operator, It


divides left operand with the right
C /= A is equivalent to C = C / A
operand and assign the result to left
operand.

%= Modulus AND assignment operator, It


C %= A is equivalent to C = C %
takes modulus using two operands and
A
assign the result to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2


>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment


C ^= 2 is same as C = C ^ 2
operator.

|= Bitwise inclusive OR and assignment


C |= 2 is same as C = C | 2
operator.

Misc Operators

The following table lists some other operators that C++ supports.
Sr.No Operator & Description

1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is
integer, and will return 4.

2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X
otherwise returns value of Y.

3 ,
Comma operator causes a sequence of operations to be performed. The value of
the entire comma expression is the value of the last expression of the comma-
separated list.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of classes,
structures, and unions.

5 Cast
Casting operators convert one data type to another. For example, int(2.2000)
would return 2.

6 &
Pointer operator & returns the address of a variable. For example &a; will give
actual address of the variable.

7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a
variable var.
Operators Precedence in C++

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

There may be a situation, when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths. A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most of the
programming languages

C++ programming language provides the following type of loops to handle looping
requirements.

Sr.No Loop Type & Description

1 while loop
Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.

2 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop
body.

4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’
loop.
Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.C++ supports the
following control statements.

Sr.No Control Statement & Description

1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.

3 goto statement
Transfers control to the labeled statement. Though it is not advised to use goto
statement in your program.

The Infinite Loop

A loop becomes infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that form the ‘for’
loop are required, you can make an endless loop by leaving the conditional expression
empty.

#include <iostream>
using namespace std;

int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}

When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the ‘for
(;;)’ construct to signify an infinite loop.

NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.

Decision making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false. Following is the general form of a typical decision
making structure found in most of the programming languages
C++ programming language provides following types of decision making statements.

Sr.No Statement & Description

1 if statement
An ‘if’ statement consists of a boolean expression followed by one or more
statements.

2 if...else statement
An ‘if’ statement can be followed by an optional ‘else’ statement, which executes
when the boolean expression is false.

3 switch statement
A ‘switch’ statement allows a variable to be tested for equality against a list of
values.

4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’
statement(s).
The ? : Operator

We have covered conditional operator “? :” in previous chapter which can be used to


replace if...else statements. It has the following general form

Exp1 ? Exp2 : Exp3;

Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then
Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then
Exp3 is evaluated and its value becomes the value of the expression.
UNIT- II

Classes and Objects

The main purpose of C++ programming is to add object orientation to the C programming
language and classes are the central feature of C++ that supports object-oriented
programming and are often called user-defined types.

A class is used to specify the form of an object and it combines data representation and
methods for manipulating that data into one neat package. The data and functions within a
class are called members of the class.

C++ Class Definitions

When you define a class, you define a blueprint for a data type. This doesn't actually define
any data, but it does define what the class name means, that is, what an object of the class
will consist of and what operations can be performed on such an object.

A class definition starts with the keyword class followed by the class name; and the class
body, enclosed by a pair of curly braces. A class definition must be followed either by a
semicolon or a list of declarations. For example, we defined the Box data type using the
keyword class as follows

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

The keyword public determines the access attributes of the members of the class that
follows it. A public member can be accessed from outside the class anywhere within the
scope of the class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.

Define C++ Objects

A class provides the blueprints for objects, so basically an object is created from a class. We
declare objects of a class with exactly the same sort of declaration that we declare variables
of basic types. Following statements declare two objects of class Box

Box Box1; // Declare Box1 of type Box


Box Box2; // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.
Accessing the Data Members

The public data members of objects of a class can be accessed using the direct member
access operator (.). Let us try the following example to make the things clear

#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result

Volume of Box1 : 210


Volume of Box2 : 1560

It is important to note that private and protected members can not be accessed directly using
direct member access operator (.). We will learn how private and protected members can be
accessed.
INTRODUCTION TO FUNCTION

Functions are the building blocks of C++ programs where all the program activity occurs.
Function is a collection of declarations and statements.

Need for a Function

Monolethic program (a large single list of instructions) becomes difficult to understand. For
this reason functions are used. A function has a clearly defined objective (purpose) and a
clearly defined interface with other functions in the program. Reduction in program size is
another reason for using functions. The functions code is stored in only one place in memory,
even though it may be executed as many times as a user needs.

The following program illustrates the use of a function:

//to display general message using function


#include<iostream.h>
include<conio.h>
void main()
{
void disp(); //function prototype
clrscr(); //clears the screen
disp(); //function call
getch(); //freeze the monitor
}
//function definition
void disp()
{
cout<<”Welcome to the GJU of S&T\n”;
cout<<”Programming is nothing but logic implementation”;
}

In this Unit, we will also discuss Class, as important Data Structure of C++. A Class is the
backbone of Object-Oriented Computing. It is an abstract data type. We can declare and
define data as well as functions in a class. An object is a replica of the class to the exception
that it has its own name. A class is a data type and an object is a variable of that type. Classes
and objects are the most important features of C++. The class implements OOP features and
ties them together.

FUNCTION DEFINITION AND DECLARATION

In C++, a function must be defined prior to it’s use in the program. The function definition
contains the code for the function. The function definition for display_message () in program
is given below the main () function. The general syntax of a function definition in C++ is
shown below:
Type name_of_the_function (argument list)
{
//body of the function
}
Here, the type specifies the type of the value to be returned by the function. It may be any
valid C++ data type. When no type is given, then the compiler returns an integer value from
the function.

Name_of_the_function is a valid C++ identifier (no reserved word allowed) defined by the
user and it can be used by other functions for calling this function. Argument list is a comma
separated list of variables of a function through which the function may receive data or send
data when called from other function. When no parameters,

the argument list is empty already as seen in program. The following function illustrates the
concept of function definition :

//function definition add()


void add()
{
int a,b,sum;
cout<<”Enter two integers”<<endl;
cin>>a>>b;
sum=a+b;
cout<<”\nThe sum of two numbers is “<<sum<<endl;
}
The above function add ( ) can also be coded with the help of arguments of parameters as
shown below:
//function definition add()
void add(int a, int b) //variable names are must in definition
{
int sum;
sum=a+b;
cout<<”\nThe sum of two numbers is “<<sum<<endl;
}

ARGUMENTS TO A FUNCTION

Arguments(s) of a function is (are) the data that the function receives when called/invoked
from another function.

PASSING ARGUMENTS TO A FUNCTION

It is not always necessary for a function to have arguments or parameters. The following
example illustrates the concept of passing arguments to function SUMFUN ( ):

// demonstration of passing arguments to a function


DEFAULT ARGUMENTS

C++ allows a function to assign a parameter the default value in case no argument for that
parameter is specified in the function call. For example.
// demonstrate default arguments function

#include<iostream.h>
int calc(int U)
{
If (U % 2 = = 0)
return U+10;
Else
return U+2
}
Void pattern (char M, int B=2)
{
for (int CNT=0;CNT<B; CNT++)
cout<calc(CNT) <<M;
cout<<endl;
}
Void main ()
{
Pattern(‘*’);
Pattern (‘#’,4)’
Pattern (;@;,3);
}

4.3.3 CONSTANT ARGUMENTS

A C++ function may have constant arguments(s). These arguments(s) is/are treated as
constant(s). These values cannot be modified by the function.
For making the arguments(s) constant to a function, we should use the keyword const as
given below in the function prototype :

Void max(const float x, const float y, const float z);

Here, the qualifier const informs the compiler that the arguments(s) having const should not
be modified by the function max (). These are quite useful when call by reference method is
used for passing arguments.

CALLING FUNCTIONS

In C++ programs, functions with arguments can be invoked by :


(a) Value
(b) Reference

Call by Value: - In this method the values of the actual parameters (appearing in the function
call) are copied into the formal parameters (appearing in the function definition), i.e., the
function creates its own copy of argument values and operates on them. The following
program illustrates this concept :

//calculation of compound interest using a function


#include<iostream.h>
#include<conio.h>
#include<math.h> //for pow()function
Void main()
{
Float principal, rate, time; //local variables
Void calculate (float, float, float); //function prototype clrscr();
Cout<<”\nEnter the following values:\n”;
Cout<<”\nPrincipal:”;
Cin>>principal;
Cout<<”\nRate of interest:”;
Cin>>rate;
Cout<<”\nTime period (in yeaers) :”;
Cin>>time;
Calculate (principal, rate, time); //function call
Getch ();
}
//function definition calculate()
Void calculate (float p, float r, float t)
{
Float interest; //local variable
Interest = p* (pow((1+r/100.0),t))-p;
Cout<<”\nCompound interest is : “<<interest;
}

Call by Reference: - A reference provides an alias – an alternate name – for the variable, i.e.,
the same variable’s value can be used by two different names : the original name and the alias
name.

In call by reference method, a reference to the actual arguments(s) in the calling program is
passed (only variables). So the called function does not create its own copy of original
value(s) but works with the original value(s) with different name. Any change in the original
data in the called function gets reflected back to the calling function. It is useful when you
want to change the original variables in the calling function by the called function.

//Swapping of two numbers using function call by reference


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1,num2;
void swap (int &, int &); //function prototype
cin>>num1>>num2;
cout<<”\nBefore swapping:\nNum1: “<<num1;
cout<<endl<<”num2: “<<num2;
swap(num1,num2); //function call
cout<<”\n\nAfter swapping : \Num1: “<<num1;
cout<<endl<<”num2: “<<num2;
getch();
}
//function fefinition swap()
void swap (int & a, int & b)
{
Int temp=a;
a=b;
b=temp;
}

INLINE FUNCTIONS

These are the functions designed to speed up program execution. An inline function is
expanded (i.e. the function code is replaced when a call to the inline function is made) in the
line where it is invoked. You are familiar with the fact that in case of normal functions, the
compiler have to jump to another location for the execution of the function and then the
control is returned back to the instruction immediately after the function call statement. So
execution time taken is more in case of normal functions. There is a memory penalty in the
case of an inline function.

The system of inline function is as follows :

inline function_header
{
body of the function
}
For example,
//function definition min()
inline void min (int x, int y)
cout<< (x < Y? x : y);
}

Void main()
{
int num1, num2;
cout<<”\Enter the two intergers\n”;
cin>>num1>>num2;
min (num1,num2; //function code inserted here
------------------
------------------
}

An inline function definition must be defined before being invoked as shown in the above
example. Here min ( ) being inline will not be called during execution, but its code would be
inserted into main ( ) as shown and then it would be compiled. If the size of the inline
function is large then heavy memory pentaly makes it not so useful and in that case normal
function use is more useful.
The inlining does not work for the following situations :

1. For functions returning values and having a loop or a switch or a goto


statement.
2. For functions that do not return value and having a return statement.
3. For functions having static variable(s).
4. If the inline functions are recursive (i.e. a function defined in terms of
itself).

The benefits of inline functions are as follows :

1. Better than a macro.


2. Function call overheads are eliminated.
3. Program becomes more readable.
4. Program executes more efficiently.

SCOPE RULES OF FUNCTIONS AND VARIABLES

The scope of an identifier is that part of the C++ program in which it is accessible. Generally,
users understand that the name of an identifier must be unique. It does not mean that a name
can’t be reused. We can reuse the name in a program provided that there is some scope by
which it can be distinguished between different cases or instances.

In C++ there are four kinds of scope as given below :

1. Local Scope
2. Function Scope
3. File Scope
4. Class Scope

Local Scope:- A block in C++ is enclosed by a pair of curly braces i.e., ‘{‘ and ‘}’. The
variables declared within the body of the block are called local variables and can be used
only within the block. These come into existence when the control enters the block and get
destroyed when the control leaves the closing brace. You should note the variable(s) is/are
available to all the enclosed blocks within a block.

For example,

int x=100;
{ cout<<x<<endl;
Int x=200;
{
cout<<x<<endl;
int x=300;
{
cout<<x<<endl;
}
}
cout<<x<<endl;
}
Function Scope : It pertains to the labels declared in a function i.e., a label can be used
inside the function in which it is declared. So we can use the same name labels in different
functions.
For example,
//function definition add1()
void add1(int x,int y,int z)
{
int sum = 0;
sum = x+y+z;
cout<<sum;
}
//function definition add2()
coid add2(float x,float y,float z)
{
Float sum = 0.0;
sum = x+y+z;
cout<<sum;
}

Here the labels x, y, z and sum in two different functions add1 ( ) and add2 ( ) are declared
and used locally.

File Scope : If the declaration of an identifier appears outside all functions, it is available to
all the functions in the program and its scope becomes file scope. For Example,
int x;
void square (int n)
{
cout<<n*n;
}
void main ()
{
int num;
…………...........
cout<<x<<endl;
cin>>num;
squaer(num);
…………...........
}

Here the declarations of variable x and function square ( ) are outside all the functions so
these can be accessed from any place inside the program. Such variables/functions are called
global.

Class Scope : In C++, every class maintains its won associated scope. The class members are
said to have local scope within the class. If the name of a variable is reused by a class
member, which already has a file scope, then the variable will be hidden inside the class.
Member functions also have class scope.
DEFINITION AND DECLARATION OF A CLASS

A class in C++ combines related data and functions together. It makes a data type which is
used for creating objects of this type.
Classes represent real world entities that have both data type properties (characteristics) and
associated operations (behavior).

The syntax of a class definition is shown below :


Class name_of _class
{
private : variable declaration; // data member
Function declaration; // Member Function (Method)
protected: Variable declaration;
Function declaration;
public : variable declaration;
Function declaration;
};

Here, the keyword class specifies that we are using a new data type and is followed by the
class name.

The body of the class has two keywords namely :

(i) private (ii) public

In C++, the keywords private and public are called access specifiers. The data hiding
concept in C++ is achieved by using the keyword private. Private data and functions can
only be accessed from within the class itself. Public data and functions are accessible outside
the class also. This is shown below :
Data hiding not mean the security technique used for protecting computer databases. The
security measure is used to protect unauthorized users from performing any operation
(read/write or modify) on the data. The data declared under Private section are hidden and
safe from accidental manipulation. Though the user can use the private data but not by
accident. The functions that operate on the data are generally public so that they can be
accessed from outside the class but this is not a rule that we must follow.

MEMBER FUNCTION DEFINITION

The class specification can be done in two part :

(i) Class definition. It describes both data members and member functions.
(ii) Class method definitions. It describes how certain class member functions
are coded.
We have already seen the class definition syntax as well as an example.
In C++, the member functions can be coded in two ways :

(a) Inside class definition


(b) Outside class definition using scope resolution operator (::)

The code of the function is same in both the cases, but the function header is different as
explained below :

Inside Class Definition:

When a member function is defined inside a class, we do not require to place a membership
label along with the function name. We use only small functions inside the class definition
and such functions are known as inline functions.
In case of inline function the compiler inserts the code of the body of the function at the place
where it is invoked (called) and in doing so the program execution is faster but memory
penalty is there.

Outside Class Definition Using Scope Resolution Operator (::) :

In this case the function’s full name (qualified_name) is written as shown:

Name_of_the_class :: function_name

The syntax for a member function definition outside the class definition is :

return_type name_of_the_class::function_name (argument list)


{
body of function
}

Here the operator::known as scope resolution operator helps in defining the member function
outside the class. Earlier the scope resolution operator(::)was ised om situations where a
global variable exists with the same name as a local variable and it identifies the global
variable.
DECLARATION OF OBJECTS AS INSTANCES OF A CLASS

The objects of a class are declared after the class definition. One must remember that a class
definition does not define any objects of its type, but it defines the properties of a class. For
utilizing the defined class, we need variables of the class type. For example,

Largest ob1,ob2; //object declaration

will create two objects ob1 and ob2 of largest class type. As mentioned earlier, in C++ the
variables of a class are known as objects. These are declared like a simple variable i.e., like
fundamental data types.

In C++, all the member functions of a class are created and stored when the class is defined
and this memory space can be accessed by all the objects related to that class. Memory space
is allocated separately to each object for their data members. Member variables store different
values for different objects of a class.

The figure shows this concept

ACCESSING MEMBERS FROM OBJECT(S)

After defining a class and creating a class variable i.e., object we can access the data
members and member functions of the class. Because the data members and member
functions are parts of the class, we must access these using the variables we created. For
functions are parts of the class, we must access these using the variable we created. For
Example,

Class student
{
private:
char reg_no[10];
` char name[30];
int age;
char address[25];
public :
void init_data()
{
- - - - - //body of function
-----
}
void display_data()
}
};
student ob; //class variable (object) created
-----
-----
Ob.init_data(); //Access the member function
ob.display_data(); //Access the member function
-----
-----

Here, the data members can be accessed in the member functions as these have private
scope, and the member functions can be accessed outside the class i.e., before or after the
main() function.

STATIC CLASS MEMBERS

Data members and member functions of a class in C++, may be qualified as static. We can
have static data members and static member function in a class.

Static Data Member: It is generally used to store value common to the whole class. The
static data member differs from an ordinary data member in the following ways :

(i) Only a single copy of the static data member is used by all the objects.
(ii) It can be used within the class but its lifetime is the whole program.

For making a data member static, we require :


(a) Declare it within the class.
(b) Define it outside the class.
For example
Class student
{
Static int count; //declaration within class
-----------------
-----------------
-----------------
};

The static data member is defined outside the class as :

int student :: count; //definition outside class

The definition outside the class is a must.

We can also initialize the static data member at the time of its definition as:

int student :: count = 0;

If we define three objects as : sudent obj1, obj2, obj3;

Static Member Function: A static member function can access only the static members of a
class. We can do so by putting the keyword static before the name of the function while
declaring it for example,

Class student
{
Static int count;
-----------------
public :
-----------------
-----------------
static void showcount (void) //static member function
{
Cout<<”count=”<<count<<”\n”;
}
};
int student ::count=0;

Here we have put the keyword static before the name of the function shwocount ().
In C++, a static member function fifers from the other member functions in the following
ways:

(i) Only static members (functions or variables) of the same class can be accessed
by a static member function.
(ii) It is called by using the name of the class rather than an object as given below:

Name_of_the_class :: function_name
For example,
student::showcount();

Constructors

A constructor is a member function of a class which initializes objects of a class. In


C++,Constructor is automatically called when object(instance of class) create.It is special
member function of the class.

How constructors are different from a normal member function?

A constructor is different from normal functions in following ways:


 Constructor has same name as the class itself
 Constructors don’t have return type
 A constructor is automatically called when an object is created.
 If we do not specify a constructor, C++ compiler generates a default constructor for us
(expects no parameters and has an empty body).

Types of Constructors

1. Default Constructors: Default constructor is the constructor which doesn’t take any
argument. It has no parameters.
// Cpp program to illustrate the
// concept of Constructors
#include <iostream>
using namespace std;

class construct
{
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: "<< c.a << endl << "b: "<< c.b;
return 1;
}
Output:
a: 10
b: 20

Note: Even if we do not define any constructor explicitly, the compiler will automatically
provide a default constructor implicitly. The default value of variables is 0 in case of
automatic initialization.

2. Parameterized Constructors: It is possible to pass arguments to constructors.


Typically, these arguments help initialize an object when it is created. To create a
parameterized constructor, simply add parameters to it the way you would to any other
function. When you define the constructor’s body, use the parameters to initialize the
object.
// CPP program to illustrate
// parameterized constructors
#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX()
{
return x;
}
int getY()
{
return y;
}
};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}

Output:
p1.x = 10, p1.y = 15

When an object is declared in a parameterized constructor, the initial values have to be


passed as arguments to the constructor function. The normal way of object declaration may
not work. The constructors can be called explicitly or implicitly.
Example e = Example(0, 50); // Explicit call

Example e(0, 50); // Implicit call


Uses of Parameterized constructor:

1. It is used to initialize the various data elements of different objects with different
values when they are created.
2. It is used to overload constructors.

3.Copy Constructor: A copy constructor is a member function which initializes an object


using another object of the same class. Detailed article on Copy Constructor.

What is a copy constructor?

A copy constructor is a member function which initializes an object using another object of
the same class. A copy constructor has the following general function prototype:
ClassName (const ClassName &old_obj);
Following is a simple example of copy constructor.

#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor
Point(const Point &p2) {x = p2.x; y = p2.y; }

int getX() { return x; }


int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();

return 0;
}

Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

When is copy constructor called?

In C++, a Copy Constructor may be called in following cases:


1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument.
3. When an object is constructed based on another object of the same class.
4. When compiler generates a temporary object.

It is however, not guaranteed that a copy constructor will be called in all these cases, because
the C++ Standard allows the compiler to optimize the copy away in certain cases.

When is user defined copy constructor needed?

If we don’t define our own copy constructor, the C++ compiler creates a default copy
constructor for each class which does a member wise copy between objects. The compiler
created copy constructor works fine in general. We need to define our own copy constructor
only if an object has pointers or any run time allocation of resource like file handle, a network
connection..etc.

Following is a complete C++ program to demonstrate use of Copy constructor. In the


following String class, we must write copy constructor.

#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
char *s;
int size;
public:
String(const char *str = NULL); // constructor
~String() { delete [] s; }// destructor
String(const String&); // copy constructor
void print() { cout << s << endl; } // Function to print string
void change(const char *); // Function to change
};

String::String(const char *str)


{
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

void String::change(const char *str)


{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

String::String(const String& old_str)


{
size = old_str.size;
s = new char[size+1];
strcpy(s, old_str.s);
}

int main()
{
String str1("GeeksQuiz");
String str2 = str1;

str1.print(); // what is printed ?


str2.print();

str2.change("GeeksforGeeks");

str1.print(); // what is printed now ?


str2.print();
return 0;
}

Output:
GeeksQuiz
GeeksQuiz
GeeksQuiz
GeeksforGeeks
What would be the problem if we remove copy constructor from above code?

If we remove copy constructor from above program, we don’t get the expected output. The
changes made to str2 reflect in str1 as well which is never expected.

#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
char *s;
int size;
public:
String(const char *str = NULL); // constructor
~String() { delete [] s; }// destructor
void print() { cout << s << endl; }
void change(const char *); // Function to change
};

String::String(const char *str)


{
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

void String::change(const char *str)


{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

int main()
{
String str1("GeeksQuiz");
String str2 = str1;

str1.print(); // what is printed ?


str2.print();

str2.change("GeeksforGeeks");

str1.print(); // what is printed now ?


str2.print();
return 0;
}
Output:
GeeksQuiz
GeeksQuiz
GeeksforGeeks
GeeksforGeeks
Can we make copy constructor private?

Yes, a copy constructor can be made private. When we make a copy constructor private in a
class, objects of that class become non-copyable. This is particularly useful when our class
has pointers or dynamically allocated resources. In such situations, we can either write our
own copy constructor like above String example, or make a private copy constructor so that
users get compiler errors rather than surprises at run time.

Why argument to a copy constructor must be passed as a reference?

A copy constructor is called when an object is passed by value. Copy constructor itself is a
function. So if we pass argument by value in a copy constructor, a call to copy constructor
would be made to call copy constructor which becomes a non-terminating chain of calls.
Therefore compiler doesn’t allow parameters to be pass by value.

Constructor Overloading in C++

In C++, We can have more than one constructor in a class with same name, as long as each
has a different list of arguments.This concept is known as Constructor Overloading and is
quite similar to function overloading.

 Overloaded constructors essentially have the same name (name of the class) and
different number of arguments.
 A constructor is called depending upon the number and type of arguments passed.
 While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.

// C++ program to illustrate


// Constructor overloading

#include <iostream>
using namespace std;

class construct
{
public:
float area;

// Constructor with no parameters


construct()
{
area = 0;
}
// Constructor with two parameters
construct(int a, int b)
{
area = a * b;
}

void disp()
{
cout<< area<< endl;
}
};

int main()
{
// Constructor Overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);

o.disp();
o2.disp();
return 1;
}

Output:
0
200

Destructors in C++

Destructor is a member function which destructs or deletes an object.

When is destructor called?


A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called

How destructors are different from a normal member function?


Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything

class String
{
private:
char *s;
int size;
public:
String(char *); // constructor
~String(); // destructor
};

String::String(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}

String::~String()
{
delete []s;
}

Can there be more than one destructor in a class?

No, there can only one destructor in a class with classname preceded by ~, no parameters and
no return type.

When do we need to write a user-defined destructor?

If we do not write our own destructor in class, compiler creates a default destructor for us.
The default destructor works fine unless we have dynamically allocated memory or pointer in
class. When a class contains a pointer to memory allocated in class, we should write a
destructor to release memory before the class instance is destroyed. This must be done to
avoid memory leak.

Objects as Function Arguments

The objects of a class can be passed as arguments to member functions as well as nonmember
functions either by value or by reference. When an object is passed by value, a copy of the
actual object is created inside the function. This copy is destroyed when the function
terminates. Moreover, any changes made to the copy of the object inside the function are not
reflected in the actual object. On the other hand, in pass by reference, only a reference to that
object (not the entire object) is passed to the function. Thus, the changes made to the object
within the function are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its data
members can be accessed inside the function using the object name and the dot operator.
However, the data members of the calling object can be directly accessed inside the function
without using the object name and the dot operator.
To understand how objects are passed and accessed within a member function, consider this
example.
Example: A program to demonstrate passing objects by value to a member function of the
same class

#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
};
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
void weight :: sum_weight(weight wl,weight w2)
{
gram = wl.gram + w2.gram;
kilogram=gram/1000;
gram=gram%1000;
kilogram+=wl.kilogram+w2.kilogram;
}
int main ()
{
weight wl,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
wl.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
wl.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
The output of the program is

Enter weight in kilograms and grams


Enter weight #1
Kilograms: 12
Grams: 560
Enter weight #2
Kilograms: 24
Grams: 850
Weight #1 = 12 Kgs. and 560 gms.
Weight #2 = 24 Kgs. and 850 gms.
Total Weight = 37 Kgs. and 410 gms.

In this example, the sum_weight () function has direct access to the data members of calling
object (w3 in this case). However, the members of the objects passed as arguments (w1 and
w2) can be accessed within function using the object name and dot operator. Note that, the
objects w1 and w2 are passed by value, however, they can re passed by reference also.

Returning object from function

A function can also return objects either by value or by reference. When an object is returned
by value from a function, a temporary object is created within the function, which holds the
return value. This value is further assigned to another object in the calling function.

The syntax for defining a function that returns an object by value is

class_name function_name (parameter_list)


{
// body of the function
}

To understand the concept of returning an object by value from a function, consider this
example.

Example:

A program to demonstrate the concept of returning objects from a function


#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
weight sum_weight (weight) ;
};
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
weight weight :: sum_weight(weight w2)
{
weight temp;
temp.gram = gram + w2.gram;
temp.kilogram=temp.gram/1000;
temp.gram=temp.gram%1000;
temp.kilogram+=kilogram+w2.kilogram;
return(temp);
}
int main ()
{
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
w3=w1.sum_weight (w2);
wl.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
wl.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();

return 0;
}

As the return type of function is weight (an object of class weight), a temporary object temp
is created within the function for holding return values. These values are accessed as temp
kilogram and temp gram by the function. When the control returns to main (), the object temp
is assigned to the object w3 in main( ).
In the case of returning an object by reference, no new object is created, rather a reference to
the original object in the called function is returned to the calling function.
The syntax for defining a function that returns an object by reference is

class_name& function_name (parameter_list)


{
//body of the function
}

However, a reference to the local object (object declared inside the function) cannot be
returned from the function since a reference to local data points to data within the function.
Hence, when the function terminates and local data is destroyed, this reference points to
nothing.

To understand this concept, consider the function sum_weight () that is modified as shown in
this code segment..

weight& weight::sum_weight(weight & w2)


{
weight temp; //object local to function
temp.gram=gram+w2.gram;
temp.kilogram=temp.gram/1000;
temp.gram=temp.gram%1000;
temp.kilogram+=kilogram+w2.kilogram;
return temp; //invalid
}

In this code segment, an attempt has been made to return the reference to an object of type
weight (that is temp).However, it is not possible as the object temp is local to the
sum_weight()function and a reference to this object remains effective only within the
function. Thus, returning the reference to temp object outside the function generates a
compile-time error.

You might also like