38
Data Structures and Programming with C++ Class Notes Faculty: Dr. Atul Kumar Dwivedi (Ph.D. VLSI Signal Processing, NIT Raipur) BHILAI INSTITUTE OF TECHNOLOGY. DURG

Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

Data Structures and

Programming with

C++

Class Notes

Faculty: Dr. Atul Kumar Dwivedi

(Ph.D. VLSI Signal Processing, NIT Raipur)

BHILAI INSTITUTE OF TECHNOLOGY. DURG

Page 2: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 2

Table of Contents

Unit-1: Principles of Object Oriented Programming ................................................................... 4

1.1 C Programming Revisited ........................................................................................................... 4

1.2 C Structures Revisited .................................................................................................................. 4

1.3 Basic Concepts of Object Oriented Programming ............................................................ 4

1.3.1 Objects: ....................................................................................................................................... 4

1.3.2 Class: ............................................................................................................................................ 4

1.3.3 Data Encapsulation ............................................................................................................... 5

1.3.4 Data Abstraction: ................................................................................................................... 5

1.3.5 Inheritance:............................................................................................................................... 6

1.3.6 Polymorphism: ........................................................................................................................ 7

1.3.7 Dynamic Binding: ................................................................................................................... 7

1.3.8 Message Passing: .................................................................................................................... 8

1.4 Benefits of Object Oriented Programming .......................................................................... 9

Benefits to the programmer: ........................................................................................................ 9

Benefits to the user: ......................................................................................................................... 9

1.5 Defining Class ................................................................................................................................ 10

1.6 Defining Objects ........................................................................................................................... 11

1.7 Accessing the data members using objects of the class ............................................. 11

1.8 Defining member functions in a class................................................................................. 12

1.9 Inline functions and its advantages ..................................................................................... 15

1.10 Nesting of member functions .............................................................................................. 16

Page 3: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 3

1.11 Private member functions .................................................................................................... 18

1.12 Array within a class .................................................................................................................. 19

1.13 Array of objects .......................................................................................................................... 20

1.14 Objects as function arguments............................................................................................ 24

1.15 Returning objects ...................................................................................................................... 26

1.16 Friendly functions ..................................................................................................................... 28

1.17 Constructors ................................................................................................................................ 31

1.18 Types of Constructors ............................................................................................................. 32

1.19 Multiple Constructors in a Class ......................................................................................... 35

Syntax: ................................................................................................................................................. 35

1.20 Destructor .................................................................................................................................... 37

Page 4: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 4

Unit-1: Principles of Object Oriented

Programming

1.1 C Programming Revisited

In last semester, programming concepts was introduced to you by using a language

C. The concepts of input, output, loops, and conditional statements are common to

every programming language (refer power points slides at

dratul.wordpress.com)

1.2 C Structures Revisited

Refer power points slides at dratul.wordpress.com

1.3 Basic Concepts of Object Oriented Programming

The object oriented programming has following eight important concepts: Objects,

Classes, data encapsulation, data abstraction, inheritance, polymorphism, dynamic

binding and message passing.

1.3.1 Objects:

Objects are run time entities related to a person, place or thing that have some

specific features. Objects take space in the system memory and have some address

associated with the memory. The data and functions of an object are stored in the

class.

1.3.2 Class:

Class specifies the data and functions related to objects. 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

Page 5: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 5

data of type class with which they are created. A class is thus a collection of objects

similar types(figure 1).

Figure 1: Class and object

For examples, Ashok, Mahesh and Meena can be objects of class Student. Classes are

user-defined data 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 student has been defines as a class, then the

statement student Ashok; will create an object mango belonging to the class

fruit.

1.3.3 Data Encapsulation

The wrapping up of data and functions into a single unit (called class) is known as

encapsulation. Encapsulation helps in data hiding and protection.

Data protection helps the programmer as well user by providing data security

Figure 2: Data and functions encapsulated within a class

1.3.4 Data Abstraction:

Data abstraction refers to, providing only needed information to the outside world

and hiding implementation details. For example, consider a class Complex with

Page 6: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 6

public functions as getReal() and getImag(). We may implement the class as an array

of size 2 or as two variables. The advantage of abstractions is, we can change

implementation at any point, users of Complex class wont’t be affected as out

method interface remains same. Had our implementation be public, we would not

have been able to change it.

Figure 3 Inheritance example

1.3.5 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.

Inheritance provides re usability. This means that we can add additional features to

an existing class without modifying it.

Page 7: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 7

Example: In figure 3, an example of birds is shown, some of them flying birds and

some of the birds are non flying. Hence there can be two sub-classes of the main bird

class. There can be class for each bird also which will third level inherited class.

Thus oop facilitates inheritance in programming by using child class definition.

1.3.6 Polymorphism:

Polymorphism means ability to take more than one form. An operation may exhibit

different behaviors in different instances. The behavior depends upon the types of

data used in the operation. C++ supports operator overloading and function

overloading. Operator overloading is the process of making an operator to exhibit

different behaviors in different instances is known as operator overloading.

Function overloading is using a single function name to perform different types of

tasks. Polymorphism is extensively used in implementing inheritance.

Fig.ure4 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.

1.3.7 Dynamic Binding:

In dynamic binding, the code to be executed in response to function call is decided at

runtime. C++ has virtual functions to support this. 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.

Page 8: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 8

Figure 4: Polymorphism

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. 4 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.

1.3.8 Message Passing:

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 realworld 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:

Page 9: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 9

1.4 Benefits of Object Oriented Programming

The main purpose of object oriented programming is to provide more security to

the data rather than focusing on the procedure. The advantages of object oriented

programming are divided into two parts (i) benefits to the programmer and (ii)

benefits to the user. Object orientation contributes to the solution of many problems

associated with 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:

Benefits to the programmer:

1. Through inheritance, we can eliminate redundant code extend the use of existing

classes.

2. 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.

3. 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.

4. It is possible to have multiple instances of an object to co-exist without any

interference.

5. It is possible to map object in the problem domain to those in the program.

6. It is easy to partition the work in a project based on objects..

7. The data-centered design approach enables us to capture more detail of a model

can implemental form.

8. Object-oriented system can be easily upgraded from small to large system.

9. Message passing techniques for communication between objects makes to

interface descriptions with external systems much simpler.

10. Software complexity can be easily managed.

Benefits to the user:

Page 10: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 10

11. New features can be easily added thus user interface and functionality can be

updated with the latest technology available

12. User data is protected because of data encapsulation property of oop.

13. Time complexity of the program is reduced by the use of inheritance and

polymorphism. Thus the programs are faster in terms of speed .

14. Because of operator overloading and function overloading , the number of of

variables required are less, hence OOP based Programs also consume less

memory.

OOP has become one of the most popular programming methods 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, data bases, Hypertext, Hypermedia, and

expertext, AI and expert systems, Neural networks and parallel programming,

decision support and office automation systems, and computer aided design(CAD)

systems.

1.5 Defining Class

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.

class definition starts with the keyword class followed by the classname; and the

class body, enclosed by a pair of curly braces. A class definition must be followed

Page 11: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 11

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.

1.6 Defining 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.

1.7 Accessing the data members using objects of the class

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:

Page 12: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 12

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.

1.8 Defining member functions in a class

Page 13: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 13

A member function of a class is a function that has its definition or its prototype

within the class definition like any other variable. It operates on any object of the

class of which it is a member, and has access to all the members of a class for that

object.

Let us take previously defined class to access the members of the class using a

member function instead of directly accessing them –

class Box {

public:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

double getVolume(void);// Returns box volume

};

Member functions can be defined within the class definition or separately

using scope resolution operator, : :. Defining a member function within the class

definition declares the function inline, even if you do not use the inline specifier. So

either you can define Volume() function as below –

class Box {

public:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

double getVolume(void) {

return length * breadth * height;

}

};

If you like, you can define the same function outside the class using the scope

resolution operator (::) as follows –

double Box::getVolume(void) {

return length * breadth * height;

}

Page 14: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 14

Here, only important point is that you would have to use class name just before ::

operator. A member function will be called using a dot operator (.) on a object

where it will manipulate data related to that object only as follows −

Box myBox; // Create an object

myBox.getVolume(); // Call member function for the object

Let us put above concepts to set and get the value of different class members in a

class –

#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

// Member functions declaration

double getVolume(void);

void setLength( double len );

void setBreadth( double bre );

void setHeight( double hei );

};

// Member functions definitions

double Box::getVolume(void) {

return length * breadth * height;

}

void Box::setLength( double len ) {

length = len;

}

void Box::setBreadth( double bre ) {

breadth = bre;

}

void Box::setHeight( double hei ) {

height = hei;

}

Page 15: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 15

// Main function for the program

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.setLength(6.0);

Box1.setBreadth(7.0);

Box1.setHeight(5.0);

// box 2 specification

Box2.setLength(12.0);

Box2.setBreadth(13.0);

Box2.setHeight(10.0);

// volume of box 1

volume = Box1.getVolume();

cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2

volume = Box2.getVolume();

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

1.9 Inline functions and its advantages

C++ inline function is powerful concept that is commonly used with classes. If a

function is inline, the compiler places a copy of the code of that function at each

point where the function is called at compile time.

Any change to an inline function could require all clients of the function to be

recompiled because compiler would need to replace all the code once again

otherwise it will continue with old functionality.

Page 16: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 16

To inline a function, place the keyword inline before the function name and define

the function before any calls are made to the function. The compiler can ignore the

inline qualifier in case defined function is more than a line.

A function definition in a class definition is an inline function definition, even

without the use of the inline specifier.

Following is an example, which makes use of inline function to return max of two

numbers –

#include <iostream>

using namespace std;

inline int Max(int x, int y) {

return (x > y)? x : y;

}

// Main function for the program

int main() {

cout << "Max (20,10): " << Max(20,10) << endl;

cout << "Max (0,200): " << Max(0,200) << endl;

cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;

}

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

Max (20,10): 20

Max (0,200): 200

Max (100,1010): 1010

1.10 Nesting of member functions

A member function of a class can be called only by an object of that class using a dot

operator. However, there is an exception to this. A member function can be called

Page 17: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 17

by using its name inside another member function of the same class. This is known

as nesting of member functions.

Example:

/*Nesting of member function*/

/*program for largest value */

#include<iostream>

#include<conio.h>

using namespace std;

class largest

{

int m; //decalaration

int n;

public :

void getdata(int a,int b);

int large();

void display();

};

void largest :: getdata(int a,int b)

{

m=a;

n=b;

}

int largest :: large()

{

if(m>n)

return m;

else

return n;

}

void largest :: display()

{

cout<<"Largest value : "<<large();

}

//-----------------Main program--------------------

int main()

{

largest l; //memory for l is created

l.getdata(10,20);

Page 18: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 18

l.display();

return 0;

}

1.11 Private member functions

Private member functions can only be accessed by using private or public member

functions of the class. These member functions can not be accessed outside the class

# include <iostream.h>

# include <conio.h>

class student

{

private:

int rn;

float fees;

void read()

{

rn=12;

fees=145.10;

}

public:

void show()

{

read();

cout<<"\n Rollno = "<<rn;

cout<<"\n Fees = "<<fees;

}

};

void main ( )

{

clrscr ();

student st;

// st.read ( ); // not accessible

st.show ( );

getch();

}

Page 19: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 19

1.12 Array within a class

Arrays can be declared as the members of a class. The arrays can be declared as

private, public or protected members of the class. To understand the concept of

arrays as members of a class, consider this example.

#include<iostream>

using namespace std;

const int size=6;

class student

{

int roll_no;

int marks[size];

public:

void getdata ();

void tot_marks ();

} ;

void student :: getdata ()

{

cout<<"\nEnter roll no: ";

cin>>roll_no;

for(int i=0; i<size; i++)

{

cout<<"Enter marks in subject"<<(i+1)<<": ";

cin>>marks[i] ;

}

}

void student :: tot_marks() //calculating total marks

{

int total=0;

for(int i=0; i<size; i++)

total = total+marks[i];

cout<<"\n\nTotal marks "<<total;

}

int main()

{

student stu;

stu.getdata() ;

stu.tot_marks() ;

return 0;

Page 20: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 20

}

1.13 Array of objects

If there are similar objects need to be created then Like array of other user-

defined data types, an array of type class can also be created. The array of type class

contains the objects of the class as its individual elements. Thus, an array of a class

type is also known as an array of objects. An array of objects is declared in the same

way as an array of any built-in data type.

Example 1: There are four transistors with the current and voltage ratings given in

the table below. Write a program to find which transistors have highest power

consumption when operated at rated voltage and current.

S.N. ID Type Voltage (V) Current(mA)

1. 2N3904 NPN 40 200

2. 2N3906 PNP 30 200

3. TIP120 Darlington 20 500

4. FQP30N06L N-MOS 60 300

Create class for a single transistor. Use the concept of array of objects to have

multiple instances of the transistor.

Program:

#include<iostream>

using namespace std;

class transistor

{

public:

char ID[10];

char type[10];

double voltage;

double current;

double p;

void input();

Page 21: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 21

double power();

void pwdisp();

};

void transistor::input()

{

cout<<"enter ID"<<endl;

cin>>ID;

cout<<"enter type"<<endl;

cin>>type;

cout<<"enter voltage"<<endl;

cin>>voltage;

cout<<"enter current"<<endl;

cin>>current;

}

double transistor::power()

{

p=voltage*current;

return p;

}

void transistor::pwdisp()

{

cout<<"Power is:"<<p<<endl;

}

int main()

{

transistor t[4];

int maxp=0;

for(int i=0;i<=3;i++)

{

t[i].input();

t[i].power();

t[i].pwdisp();

}

for(int i=0;i<=3;i++)

{

if(t[i].power()>maxp)

maxp=t[i].power();

}

cout<<"the max rating of transistor is "<<maxp;

Page 22: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 22

return 0;

}

Example 2: Consider previous example with 5 different students. Then find the

topper student among them.

Example 3: Write a program using class to process the shopping list for a

departmental store. The list includes details such as the code no and price of each

item and performs the operations like adding, deleting items to the list and printing

the total value of the order.

Program:

#include<iostream>

using namespace std;

class items

{

int code[50];

float price[50];

int count;

public:

void CNT(void){count=0;}

void getitem(void);

void dspsum(void);

void remove(void);

void dspitems(void);

};

void items::getitem(void)

{

cout<<"Enter item code";

cin>>code[count];

cout<<"Enter item cost";

cin>>price[count];

count++;

}

void items::dspsum(void)

{

float sum=0;

for(int i=0;i<count;i++)

Page 23: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 23

sum=sum+price[i];

cout<<"\n Total Value:"<<sum<<"\n";

}

void items::remove(void)

{

int a;

cout<<"Enter item code";

cin>>a;

for(int i=0;i<count;i++)

if(code[i]==a)

price[i]==0;

}

void items::dspitems(void)

{

cout<<"\n Code Price\n";

for(int i=0;i<count;i++)

{

cout<<"\n"<<code[i];

cout<<" "<<price[i];

}

cout<<"\n";

}

int main()

{

items order;

order.CNT();

int x;

do

{

cout<<"\n Enter a correct number of choice\n";

cout<<"\n 1:Add an item";

cout<<"\n 2:Display total value:";

cout<<"\n 3:Delete an item";

cout<<"\n 4:Display all items";

cout<<"\n 5:quit";

cout<<"\n Enter correct option";

cin>>x;

switch(x)

{

case 1: order.getitem();

Page 24: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 24

break;

case 2: order.dspsum();

break;

case 3: order.remove();

break;

case 4: order.dspitems();

break;

default: cout<<"error in choice";

}

}while(x!=5);

return 0;

}

1.14 Objects as function arguments

Similar to variables, objects of a class can also be passed by calling a function. In a

function call, a copy of actual objects is sent to the called function as formal objects.

Actual and formal copies of objects are stored at different memory locations. Hence

the changes made in the formal objects are not reflected in the actual objects.

The syntax for defining functions having objects as function arguments is as below

Example 1: Write a program to calculate life of the product by passing object

as an argument

#include<iostream>

Page 25: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 25

using namespace std;

class life

{

int mfgyr;

int expyr;

int yr;

public:

void getyrs()

{

cout<<"\n Manufacturing year:";

cin>>mfgyr;

cout<<"\n Expiry year:";

cin>>expyr;

}

void period(life);

};

void life::period(life y1)

{

yr=y1.expyr-y1.mfgyr;

cout<<"Life of product:" <<yr<< "Years";

}

int main()

{

life product1,product2;

product1.getyrs();

product1.period(product1);

product2.getyrs();

product2.period(product2);

return 0;

}

Example 2: There are two transistors with the current and voltage ratings given in

the table below. Write a program to find which transistors have highest power

consumption when operated at rated voltage and current.

ID Type Voltage (V) Current(mA)

2N3904 NPN 40 200

2N3906 PNP 30 200

Page 26: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 26

Input: ID, Type, voltage and Current

Output: ID, Type, Voltage and Current of the Transistor computing largest power

Instructions: All operations must be completed in the class. Do nothing in the main

program, pass and return objects to the functions if required

Hint:

#include <iostream>

using namespace std;

class Transistor

{

Private:

double voltage;

double current;

double power;

Public:

void readdata();

void powercalc();

void maxpower(Transistor T1, Transistor T2);

void display();

}

1.15 Returning objects

In C++ programming, object can be returned from a function in a similar way as

variables.

As we know that a function can return only one variable at a time and data type of

the variable is to be written before the function name which is known as return

type. The returntype must be written at the time of declaration as well as at the time

of detailed definition of the function if function is defined outside the class.

Page 27: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 27

When an object is returned from a function then the returntype is className,

therefore classname must be written before the functionName. The syntax for this is

as given below

Example: C++ program to add two complex numbers by passing objects to a

function and returning the result using a object.

#include <iostream>

using namespace std;

class Complex

{

private:

int real;

int imag;

public:

Complex(): real(0), imag(0) { }

void readData()

{

cout << "Enter real and imaginary number

respectively:"<<endl;

cin >> real >> imag;

}

void addComplexNumbers(Complex comp1, Complex comp2)

{

// real represents the real data of object c3 because this

function is called using code c3.add(c1,c2);

real=comp1.real+comp2.real;

Page 28: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 28

// imag represents the imag data of object c3 because

//this function is called using code c3.add(c1,c2);

imag=comp1.imag+comp2.imag;

}

void displaySum()

{

cout << "Sum = " << real<< "+" << imag << "i";

}

};

int main()

{

Complex c1,c2,c3;

c1.readData();

c2.readData();

c3.addComplexNumbers(c1, c2);

c3.displaySum();

return 0;

}

1.16 Friendly functions

A friend function of a class is defined outside that class' scope but it has the right to

access all private and protected members of the class. Even though the prototypes

for friend functions appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class

template, in which case the entire class and all of its members are friends.

To declare a function as a friend of a class, precede the function prototype in the

class definition with keyword friend as follows –

Page 29: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 29

class classname

{

Datamember1;

public:

double Datamember2;

friend void memberfunction1( classname );

void memberfunction2( double);

};

Consider this complete example

#include <iostream>

using namespace std;

class Box

{

double width;

Page 30: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 30

public:

friend void printWidth(Box);

void setWidth(double);

};

// Member function definition

void Box::setWidth( double wid )

{

width = wid;

}

// Note: printWidth() is not a member function of any class.

void printWidth( Box box )

{

/* Because printWidth() is a friend of Box, it can

directly access any member of this class */

cout << "Width of box : " << box.width <<endl;

}

// Main function for the program

int main()

{

Box box;

// set box width without member function

box.setWidth(10.0);

// Use friend function to print the wdith.

printWidth( box );

return 0;

}

Practice Problem1: Write a program to calculate maximum out of two numbers

using friend function (for solution refer myp43.cpp).

Advantages:

1. They provide a degree of freedom in the interface design options.

2. We can able to access the other class members in our class if,we use friend

keyword.

3. We can access the members without inheriting the class.

Disadvantage:

Page 31: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 31

Since the friend function can access to the data members and member functions

which may be either private or public of any class remaining outside of the class so

it can break the security.

1.17 Constructors

A class constructor is a special member function of a class that is executed

whenever we create new objects of that class. A constructor will have exact same

name as the class and it does not have any return type at all, not even void.

Constructors are very useful specially for setting initial values for certain member

variables.

Syntax for defining a constructor

#include <iostream>

using namespace std;

class Classname

{

public:

double datamember1;

double datamember2;

void memberfunction1( double);

double memberfunction( void );

classname(); // This is the constructor no return type

};

Example: Following program explains the concept of constructor:

#include <iostream>

using namespace std;

class Box{

public:

Box(); // This is the constructor

double length;

};

// Member functions definitions including constructor

Box::Box(void){

cout<<”Enter length”;

Page 32: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 32

cin>>length;

}

int main( ){

Box b;

cout << "Length of Box : " << b.length <<endl;

return 0;

}

In this example (myp42.cpp), we can observe that the program asks to store values

even without calling any function. The constructor Box is called immediately after

the object is created. It asks the user to enter length even without calling any

member function.

1.18 Types of Constructors

Constructors are of three types, i. e., default , parameterized and copy constructor.

Default Constructor: - The Constructor is which has no arguments is called as

default constructor or empty Constructor. It is automatically called when objects

of class are created but remember name of constructor is always same as name of

class and constructor never declared with the help of any return type.

Syntax for defining a constructor

#include <iostream>

using namespace std;

class Classname

{

public:

double datamember1;

double datamember2;

void memberfunction1( double);

double memberfunction( void );

classname(); // This is the default constructor no return type

};

Example

#include <iostream>

Page 33: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 33

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(); // This is the constructor

private:

double length;

};

// Member functions definitions including constructor

Line::Line(void) {

cout << "Object is being created" << endl;

}

void Line::setLength( double len ) {

length = len;

}

double Line::getLength( void ) {

return length;

}

// Main function for the program

int main() {

Line line;

// set line length

line.setLength(6.0);

cout << "Length of line : " << line.getLength() <<endl;

return 0;

}

Parameterized Constructor: - The constructor which has arguments to be

passed at the time of declaration is called parameterized constructor.

For this purpose, the objects of class are created by passing some arguments at

the time of creating objects. The syntax for writing parameterized constructor is

#include <iostream>

using namespace std;

Page 34: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 34

class Classname

{

public:

double datamember1;

double datamember2;

void memberfunction1( double);

double memberfunction( void );

classname(int); // This is the parameterized constructor with no

//return type

};

Example for parameterized constructor is #include <iostream>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(double len); // This is the constructor

private:

double length;

};

// Member functions definitions including constructor

Line::Line( double len) {

cout << "Object is being created, length = " << len << endl;

length = len;

}

void Line::setLength( double len ) {

length = len;

}

double Line::getLength( void ) {

return length;

}

// Main function for the program

int main() {

Line line(10.0);

// get initially set length.

cout << "Length of line : " << line.getLength() <<endl;

// set line length again

line.setLength(6.0);

Page 35: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 35

cout << "Length of line : " << line.getLength() <<endl;

return 0;

}

Copy Constructor: - These are special type of Constructors which takes an object

as argument, and is used to copy values of data members of one object into other

object.

The copy constructor is a constructor which creates an object by initializing it with

an object of the same class, which has been created previously. The copy constructor

is used to −

Initialize one object from another of the same type.

Copy an object to pass it as an argument to a function.

Copy an object to return it from a function.

If a copy constructor is not defined in a class, the compiler itself defines one.If the

class has pointer variables and has some dynamic memory allocations, then it is a

must to have a copy constructor. The most common form of copy constructor is

shown here −

classname (const classname &obj) {

// body of constructor

}

This requires understanding of pointers hence we shall study in unit 3.

1.19 Multiple Constructors in a Class

Multiple constructors are allowed within the class if they have different number of

arguments (or parameters). This way default constructor and parameterized

constructor can be defined simultaneously.

Syntax:

Class classname

Page 36: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 36

{

datamember1;

datamember2;

public:

memberfunction1();

memberfunction2();

classname(); //This is 1st constructor

classname(int,int);// This is second constructor

}

Example:

Write a program using two constructors simultaneously in a class for

accepting students name and roll number

Program :

(myp44.cpp)

#include<iostream>

using namespace std;

class Student{

public:

int rollno;

string name;

public:

Student(int x) {

rollno=x;

name="None";

}

Student(int x, string str) {

rollno=x ;

name=str ;

}

};

int main(){

Student A(10);

Student B(11,"Ram");

cout<<A.name<<endl<<B.name;

return 0;

}

Page 37: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 37

1.20 Destructor

A destructor is a special member function of a class that is executed whenever an

object of its class goes out of scope or whenever the delete expression is applied to a

pointer to the object of that class.

A destructor will have exact same name as the class prefixed with a tilde (~) and it

can neither return a value nor can it take any parameters. Destructor can be very

useful for releasing resources before coming out of the program like closing files,

releasing memories etc.

Syntax

{

datamember1;

datamember2;

public:

memberfunction1();

memberfunction2();

~classname(); //This is 1st constructor

~classname(int,int);// This is second constructor

}

Following example explains the concept of destructor –

#include <iostream>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(); // This is the constructor declaration

~Line(); // This is the destructor: declaration

private:

double length;

};

// Member functions definitions including constructor

Line::Line(void) {

Page 38: Data Structures and Programming with C++ · Unit-1: Principles of Object Oriented Programming 1.1 C Programming Revisited In last semester, programming concepts was introduced to

DC++ 2017

© Dr. Atul Kumar Dwivedi, BIT, Durg www.dratul.wordpress.com 38

cout << "Object is being created" << endl;

}

Line::~Line(void) {

cout << "Object is being deleted" << endl;

}

void Line::setLength( double len ) {

length = len;

}

double Line::getLength( void ) {

return length;

}

// Main function for the program

int main() {

Line line;

// set line length

line.setLength(6.0);

cout << "Length of line : " << line.getLength() <<endl;

return 0;

}