cs6301 programming and datastactures

52
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II CS6301 PROGRAMMING AND DATA STRUCTURES II UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS 9 C++ Programming features – Data Abstraction – Encapsulation – class – object – constructors – static members – constant members – member functions – pointers – references – Role of this pointer Storage classes – function as arguments. UNIT II OBJECT ORIENTED PROGRAMMING CONCEPTS 9 String Handling – Copy Constructor – Polymorphism – compile time and run time polymorphisms – function overloading – operators overloading – dynamic memory allocation – Nested classes - Inheritance – virtual functions. UNIT III C++ PROGRAMMING ADVANCED FEATURES 9 Abstract class – Exception handling – Standard libraries – Generic Programming – templates – class template – function template – STL – containers – iterators – function adaptors – allocators - Parameterizing the class – File handling concepts. UNIT IV ADVANCED NON-LINEAR DATA STRUCTURES 9 AVL trees – B-Trees – Red-Black trees – Splay trees – Binomial Heaps – Fibonacci Heaps – Disjoint Sets – Amortized Analysis – accounting method – potential method – aggregate analysis. UNIT V GRAPHS 9 Representation of Graphs – Breadth-first search – Depth-first search – Topological sort – Minimum Spanning Trees – Kruskal and 1 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Upload: ks-ramesh

Post on 06-May-2015

914 views

Category:

Data & Analytics


5 download

TRANSCRIPT

Page 1: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

CS6301 PROGRAMMING AND DATA STRUCTURES II

UNIT I                      OBJECT ORIENTED PROGRAMMING FUNDAMENTALS            9

C++ Programming features – Data Abstraction – Encapsulation – class – object – constructors – static members – constant members – member functions – pointers – references – Role of this pointer – Storage classes – function as arguments.

UNIT II                          OBJECT ORIENTED PROGRAMMING CONCEPTS                 9

String Handling – Copy Constructor – Polymorphism – compile time and run time polymorphisms – function overloading – operators overloading – dynamic memory allocation – Nested classes - Inheritance – virtual functions.

UNIT III                        C++ PROGRAMMING ADVANCED FEATURES                           9

Abstract class – Exception handling – Standard libraries – Generic Programming – templates – class template – function template – STL – containers – iterators – function adaptors – allocators - Parameterizing the class – File handling concepts.

UNIT IV                      ADVANCED NON-LINEAR DATA STRUCTURES                         9

AVL trees – B-Trees – Red-Black trees – Splay trees – Binomial Heaps – Fibonacci Heaps – Disjoint Sets – Amortized Analysis – accounting method – potential method – aggregate analysis.

UNIT V                                                             GRAPHS                                                             9

Representation of Graphs – Breadth-first search – Depth-first search – Topological sort – Minimum Spanning Trees – Kruskal and Prim algorithm – Shortest path algorithm – Dijkstra’s algorithm – Bellman-Ford algorithm – Floyd – Warshall algorithm.

                                                                                                                              TOTAL: 45 PERIODS

TEXT BOOKS:1. Bjarne Stroustrup, “The C++ Programming Language”, 3rd Edition, Pearson Education, 2007.2. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C++”, 2nd Edition, Pearson Education, 2005

1 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 2: Cs6301 programming and datastactures

Object:student

Data:name,marksFunctions:total

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

UNIT I

OBJECT ORIENTED PROGRAMMING FUNDAMENTALS

Object Oriented Programmings concept, Classes and Objects

Object oriented programming is method of programming where a system is considered as a collection of objects that interact together to accomplish certain tasks. Objects are entities that encapsulate data and procedures that operate on the data.

In OOPS first a concept known as "Object oriented analysis(OOA)" is used to specify the objects in term of real world requirements, their behaviour and interactions required. The next concept would be the "Object oriented design(OOD)" that converts these realtime requirements as a hierarchy of objects in terms of software development requirement. Finally OOPS is used to implement the requirements using the C++ programming language.

The main purpose of object oriented programming is to simplify the design, programming and most importantly debugging a program. So to modify a particular data, it is easy to identify which function to use. To add additional features it is easy to identify where to add functions and its related data.

Basic Elements Of Object Oriented Programming (OOPS)

Object Classes Encapsulation Data Abstraction Inheritance Polymorphism Dynamic Binding Message passingObjects Objects are instance of a class, that interact with each other at runtime. An object represents a

particular instance of a class. There can be more than one instance of an object. Each instance of an object can hold its own

relevant data. An Object is a collection of data members and associated member functions also known as

methods.

Example:

2 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 3: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

Classes A class has the data and its associated function wrapped in it. Classes are also known as a

collection of similar objects or objects of same type. In the OOPs concept the variables declared inside a class are known as "Data Members" and the

functions are known as "Member Functions". Example: Consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents

individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object functions like Start, Move, Stop form the Methods of Car Class.No memory is allocated when a class is created. Memory is allocated only when an object is created, i.e., when an instance of a class is created.

Encapsulation Encapsulation is the method of combining the data and functions inside a class. This hides the data from being accessed from outside a class directly, only through the functions

inside the class is able to access the information.1.2.4 Data Abstraction Data Abstraction "Data Abstraction", as it gives a clear separation between properties of data

type and the associated implementation details. There are two types, they are "function abstraction" and "data abstraction".

Data Abstraction also represents the needed information in the program without presenting the details.

Abstraction refers to the act of representing essential features without including the background details or explanation between them.

Functions that can be used without knowing how its implemented is function abstraction. Data abstraction is using data without knowing how the data is stored.

Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.

Inheritance Inheritance is a method by which new classes are created or derived from the existing classes.

Using Inheritance some qualities of the base classes are added to the newly derived class, apart from its own features

The advantage of using "Inheritance" is due to the reusability of classes in multiple derived classes.

The ":" operator is used for inherting a class.

Following are the different types of inheritance followed in C++.

Single inheritance Multiple inheritance Hierarchial inheritance

3 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 4: Cs6301 programming and datastactures

information

messsage

object

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

Multilevel inheritance Hybrid inheritance

Polymorphism Polymorphism is the ability of an object or reference to take many different forms at different

instances. These are of two types one is the "compile time polymorphism" and other one is the "run-time

polymorphism". Compile time polymorphism: In this method object is bound to the function call at the compile time itself. Run time polymorphism: In this method object is bound to the function call only at the run time.Dynamic Binding Dynamic Binding refers to linking a procedure call to the code that will be executed only at run

time. The code associated with the procedure in not known until the program is executed, which is also known as late binding.

Message Passing Message Passing is nothing but sending and receving of information by the objects same as

people exchange information. So this helps in building systems that simulate real life. It refers to that establishing communication between one place to another.

Following are the basic steps in message passing. Creating classes that define objects and its behaviour. Creating objects from class definitions Establishing communication among objects

In OOPs, Message Passing involves specifying the name of objects, the name of the function, and the information to be sent.

Example:

Employee.salary(name);

4 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 5: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

Introduction to C++: C++ was developed in bell labs by Bjarne Stroustrup in 1983-1985. Bjarne Stroustrup, after

completing the doctoral degree at the Computing Laboratory of the Cambridge University, joined the Bell Laboratories. With the aim of integrating the object oriented features of Simula with efficient and flexible C language (with OOPs),

C++ has evolved to be an effective "Object Oriented Programming" or commonly known as "OOPs" language. It is a high level language. Compared to other programming languages, the compilation time required for C++ is very less. This tutorial will help both beginners and advanced users.

Basic Structure of C++ program: #include directive Global Declarations return-type main() {Statements }Include Directive: The "#include" directive is used to include the files specifed inside the "<>" brackets. Mostly

standard files or header files of C++ are included using this directive like iostream.h, math.h etc.Global Declarations: The variables and other elements that need to be used all over the program or rather globally

should be declared after the include directive.main() Function: The main function is executed first in a C++ program. If a main() is supposed to return a integer

value then the return type should be specified as "int main()". If no value is returned simply use the return-type as "void".

The statements used inside the "main()" function can include the functions, classes used in C++ along with other statements.

For Example: #include <iostream.h> void main() {

cout << "Hscripts.com!"; }DATATYPES The set of values along with the operations that can be performed on these values are categorized

as datatypes. These data types are used to represent the memory usage in bytes, so appropriate a data type has to be used for optimum memory usage. Some data types have "unsigned", "signed" range.

Signed Range: The signed range the values can either be positive or negative values.Unsigned Range: The unsigned range the values would represent positive values and zero.

5 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 6: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

The following table lists the different Datatypes used in C++.Name Description Size(bytes) Range

char Character or small integer. 1-128 to 127, 0 to 255

short int(short) Short Integer. 2-32768 to 32767,0 to 65535

int Integer. 4-2147483648 to 2147483647,0 to 4294967295

long int(long) Long integer 4-2147483648 to 2147483647,0 to 4294967295

bool Boolean value 1 true or false

float Floating point number. 4 +/- 3.4e to +/- 38 (~7 digits)

double Double precision floating point number. 8+/- 1.7e to +/- 308 (~15 digits)

long doubleLong double precision floating point number.

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

wchar_t Wide character. 2 or 4 1 wide character

The other data types include "String", "Array", "Pointer" datatypes.A variable defines a location in the memory that holds a value which can be modified later.Syntax: Typevariable_list;In the above syntax "type" refers to any one of the C++ data types.Declaring Variables:

Variables in C++ should be declared before they are used in the code block. It is better to declare it right at the place where its used as this makes the programming much easier. This kind of declaration reduces the errors in the program.Example:

#include <iostream.h> void main() { int n = 10; cout << "Integer value is:"<< n << '\n'; }

Result:Integer value is: 10In the above example "n" is an integer variable declared using return type "int".Variables can also be intialized dynamically at the place of declaration using the expression as below.Example: float area = 3.14159 * rad * rad

Naming variables in C++: Always the first character of a variable must be a letter or an underscore. The variable name cannot start with a digit.

6 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 7: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

Other characters should be either letters, digits, underscores. There is no limit for the length of variables. Declared keywords cannot be used as a variable name. Upper and lower case letters are distinct.

Local variables Local variables are those that are declared inside a function. Only the statements that are

within the block of the code can refer these variables.Example:

#include <iostream.h>int test(){int x;x = 200;return x;}void main( ){int x;x = 100;cout << "Value of X in main is:" << x << '\n';cout << "Value of X in Test is:" << test() << '\n';}

Global Variables Variables that are declared outside the scope of a function, so that it can be used anywhere in

the program is known as Global Variables.Example:

#include <iostream.h>float pi = 3.14;void main( ){int area,rad;rad = 100;area = pi*rad*rad;cout << "Area of a Circle:" << area << '\n';}

Result:Area of a Circle: 31400

Constants Constants are values that will not change when a program is executed. These are also known as "literals" and it can be of any data type and they are usually declared

using the keyword "const". Types of constants are integer, character, hexadecimal, octal, string constants, backslash

character constants.Example:

#include <iostream.h>

7 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 8: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

#include <stdio.h>void main( ){const long int l = 35000L-34L; \\ Integer Constantconst int hex = 0x80; \\ Hexadecimal Constantcout << "Integer constants value is:" << l << '\n';cout << "Hexadecimalconstants value is:" << hex << '\n';printf ("\n\t This is hscripts"); \\ String Constant}

Result: Integer constants value is: 34966 Hexadecimal constants value is: 128

Classes A Class is a way to bind the data and its associated functions together. All the elements of a class are private by default, even elements can be declared as public or

protected. An object is an instance of a class.ACCESS SPECIFIERS Access specifiers defines the access rights for the statements or functions that follows it until

another access specifier or till the end of a class. The three types of access specifiers are "private", "public", "protected".

private: The members declared as "private" can be accessed only within the same class and not from

outside the class.public:

The members declared as "public" are accessible within the class as well as from outside the class.protected:

The members declared as "protected" cannot be accessed from outside the class, but can be accessed from a derived class. This is used when inheritaance is applied to the members of a class.

Syntax: class class-name{private:variable declaration;function declaration;public:variable declaration;function declaration;};

Example:#include <iostream.h>

8 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 9: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

class dat{private:int sdata;public:void setdat( int a){ sdata =a; }void show( ){ cout << "\nSet data is " << sdata;}};void main(){dat x,y;x.setdat(1000);y.setdat(1245);x.show();y.show();}

Result: Set Data is:1000 Set Data is:1245

NESTED CLASS Nested class is a class defined inside a class, that can be used within the scope of the class in

which it is defined. C++ nested classes are not given importance because of the strong and flexible usage of

inheritance. Its objects are accessed using "Nest::Display".Example:

#include <iostream.h>class nest{public:class Display{private:int s;public:void sum( int a, int b){ s =a+b; }void show( ){ cout << "\nSum of a and b is:: " << s;}};};

void main(){

9 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 10: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

nest::Display x;x.sum(12, 10);x.show();}

Result: Sum of a and b is::22

LOCAL CLASS Local class is a class defined inside a function. Following are some of the rules for using these

classes. Global variables declared above the function can be used with the scope operator "::". Static variables declared inside the function can also be used. Automatic local variables cannot be used. It cannot have static data member objects. Member functions must be defined inside the local classes. Enclosing functions cannot access the private member objects of a local class.

Example:

#include <iostream.h>int y;void g();int main(){g();return 0;}void g(){class local{public:void put( int n) {::y=n;}int get() {return ::y;}}ab;ab.put(20);cout << "The value assigned to y is::"<< ab.get();}

Result: The value assigned to y is::20

OBJECTS

10 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 11: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

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 BoxBox Box2; // Declare Box2 of type Box

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 following example to make the things clear:#include <iostream.h>class Box{ public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box};void 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; }

OUTPUT:

Volume of Box1 : 210Volume of Box2 : 1560

11 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 12: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

CONSTANT OBJECTS

Variables const ensures their values are not accidentally changed.class objects can be made const by using the const keyword.

All const variables must be initialized at time of creation. In the case of built-in data types, initilization is done through explicit or implicit assignment:

const int nValue = 5; // initialize explicitlyconst int nValue2(7); // initialize implicitly

Example:#include <iostream.h>class testClass{public:void printfuncA(){cout << "this is not a constant function so constant objects cannont access it" << endl;}void printfuncB() const{cout << "this is a constant function which can only be accessed by constant objects" << endl;} };void main(){cout << "Hello world" << endl;//const testClass objA; (this gets an error since it is a non constant function trying to access a constant object)//objA.printfuncA();cout << "Look at the code to see how this works the following is a normal object" << endl;testClass objA;objA.printfuncA();cout << "\n";cout << "Again look at the code the following is a constant object" << endl;const testClass objB;objB.printfuncB();}

CONSTRUCTOR

12 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 13: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

It is special member function of the class. It has same name of class.It is automatically called when object(instance of class) create.It

must be a public member. No Return Values. References and pointers cannot be used on constructor because their addresses cannot be

taken. Constructors cannot be declared with the keyword virtual. Constructors a cannot be declared static, const, or volatile. Unions cannot contain class objects that have constructors .

Constructor General Form:class class-name{Access Specifier:Member-VariablesMember-Functionspublic:class-name() // constructor{// Constructor code}... other Variables & Functions} Example:class example{int a,b;public://Constructorexample(){a=10;b=20;cout<<"Im Constructor"}void Display(){cout<<"Values :"<<a<<"\t"<<b;}}void main(){example Object;Object.Display()}Output:10    20

13 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 14: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

    TYPES CONSTRUCTER

Parameterized Constructor Default Constructors Copy Constructor

1.6.2.1 Parameterized Constructor: Which constructor has arguments that are called Parameterized Constructor.

Parameterized Constructor   General Form: class class-name{Access Specifier:Member-VariablesMember-Functionspublic:class-name(type Variable,type Varibale2......){// Constructor code}... other Variables & Functions}Example:class example{int a,b;public://ConstructorExample(int x,int y){a=x;b=y;cout<<"Im Constructor";}void Display(){cout<<"Values :"<<a<<b;}}void main(){example e1(10,20);//implicitly call

example e2=example(1,2);//explicitly call// Constructor invoked with parameters.Object.Display()}Output:10    20

14 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 15: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

PROGRAM:#include <iostream.h>class Line{public:void setLength( double len );double getLength( void );Line(double len); // This is the constructorprivate:double length;};// Member functions definitions including constructorLine::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;}void main( ){Line line(10.0);// get initially set length.cout << "Length of line : " << line.getLength() <<endl;// set line length againline.setLength(6.0);cout << "Length of line : " << line.getLength() <<endl;}OUTPUT:Object is being created, length = 10Length of line : 10Length of line : 6

Default Constructors If you have written a constructor for your class then when you create an instance of it, the

constructor is automatically called.

15 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 16: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

If you haven't supplied a constructor, then the compiler will create a default one for you. This default constructor takes no parameters, or has default values for all parameters.

A default parameter is one where the parameter value is supplied in the definition.

Example. class phonerec {     public:     string name;     string phonenumber[16];     phonerec(string myname ="Me",string myphone="555-1000") ; // defaults }; phonerec p; // calls the constructor a default parameter "Me" phonerec p("David","0207 384") ; Constructor with Dynamic Allocation Dynamic Constructor Used to allocate the memory while creating objects Allocation of memory to objects at the time of their construction is known as dynamic construction

of objects. Memory allocated with help of the new operator

Example# include <iostream.h># include <conio.h># include <string.h>class str{char *name;int len;public:str(){len=0;name=newchar[len+1];}str(char *s){len=strlen(s);name=newchar[len+1];strcpy(name,s);}void show(){cout<<"NAME IS:->"<<name<<endl;}void join(str &a,str &b);

16 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 17: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

};void str::join(str &a,str &b){len=a.len+b.len;delete new;name=newchar[len+1];strcpy(name,a.name);strcat(name,b.name);};void main(){clrscr();char *first="HARSHIL";str n1(first),n2("NINAD"),n3("PRATIK"),n4,n5;n4.join(n1,n2);n5.join(n4,n3);n1.show();n2.show();n3.show();n4.show();n5.show();}Dynamic initialization of Objects Dynamic initialization is that in which initialization value isn't known at compile-time. It's

computed at runtime to initialize the variable. The benefit of dynamic initialization is that it allows different initialization modes using

overloaded constructors.Example:#include<iostream.h>Class fixeddeposit{ int pamount, years;float rate,rvalue;public:fixeddeposit(){}fixeddeposit(int p, int y, float=0.2);fixeddeposit(int p,int y,int r);void display();};fixeddeposit ::fixeddeposit(int p,int y,float r){pamount=p;years=y;rate=r;rvalue=pamount;for(int i=1;i<=y;i++)rvalue=rvalue*(1.0+r);

17 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 18: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

}fixeddeposit ::fixeddeposit(int p,int y,int r){pamount=p;years=y;rate=r;rvalue=pamount;for(int i=1;i<=y;i++)rvalue=rvalue*(1.0+float(r)/100);}Void fixeddeposit::display(){cout<<”principalamount=”<<pamount<<”\n”;cout<<”return value=”<<rvalue<<”\n”;}Void main(){fixeddeposit f1,f2,f3;int p,y,R;float r;cout<<”enter the amount,period and interest(in percent)”;cin>>p>>y>>R;f1= fixeddeposit(p,y,R);.cout<<”enter the amount,period and interest(in percent)”;cin>>p>>y>>r;f2= fixeddeposit(p,y,r);cout<<”enter the amount and period”;cin>>p>>y>>r;f3= fixeddeposit(p,y);cout<<”\ndeposit 1”;f1.display();cout<<”\ndeposit 2”;f2.display();cout<<”\ndeposit 3”;f3.display();}

COPY CONSTRUCTOR 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.Example:#include<iostream.h>

18 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 19: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

Class code{int id;public:code(){}Code(int a){ id=a;}code(code &x){id=x.id;}void display(){Cout<<id;}};void main(){code a(100);code b(a);code c=a;Code d;d=a;Cout<<”\n id of a:”,a.display();Cout<<”\n id of b:”,b.display();Cout<<”\n id of c:”,c.display();Cout<<”\n id of d:”,d.display();}

Multiple Constructors in a Class (Constructor overloading)Example program for Addition of two complex numbers using friend function:#include<iostream.h>#include<conio.h>class complex{float x,y;public:complex (){}complex (float a){x=y=a;}complex (float real,float imag){

19 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 20: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

x=real’y=imag;}friend complex sum(complex,complex);friend void show(complex);};friend complex sum(complex c1,complex c2);{complex c3;c3.x=c1.x+c2.x;c3.y=c1.y+c2.y;return(c3);}void show(complex c){cout<<c.x<<”+j”<<c.y<<”\n”;}

void main(){complex a(2.7,3.5);complex b(1.6);complex c;c=sum(a,b);cout<<”A=”<<show(a);cout<<”B=”<<show(b);cout<<”C=”<<show(b);}The Destructor: When an object is no longer needed it can be destroyed. A destructor is a special member function of a class that is executed whenever an object of it's

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.

A class cannot have more than one destructor. No Return Values. A destructor must be declared in the public section of a class so that is accessible to all its users. Destructor can be very useful for releasing resources before coming out of the program like

closing files, releasing memories etc.

Syntax:class class-name{Access Specifier:Member-Variables

20 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 21: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

Member-Functionspublic:~ class-name() // destructor{// destructor code}... other Variables & Functions}

Example:#include <iostream.h>class line{public:void setlength( double len );double getlength( );line(); // This is the constructor declaration~line(); // This is the destructor: declarationprivate:double length;};// Member functions definitions including constructorline::line(void){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( ){return length;}// Main function for the program

void main( ){line line;// set line lengthline.setlength(6.0);

21 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 22: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

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

OUTPUT:Object is being createdLength of line : 6Object is being deleted

STATIC DATA AND MEMBER FUNCTIONSTATIC DATA MEMBERS

The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.

Example: class X{public: static int i;};int X::i = 0; // definition outside class declaration Once you define a static data member, it exists even though no objects of the static data member's

class exist. In the above example, no objects of class X exist even though the static data member X::i has been defined.

Static data members of a class in namespace scope have external linkage. The initializer for a static data member is in the scope of the class declaring the member.

Static data members and their initializers can access other static private and protected members of their class.

Example:class C { static int i; static int j; static int k; static int l; static int m; static int n; static int p; static int q; static int r; static int s; static int f() { return 0; } int a;public: C() { a = 0; } };C c;int C::i = C::f(); // initialize with static member functionint C::j = C::i; // initialize with another static data memberint C::k = c.f(); // initialize with member function from an object

22 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 23: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

int C::l = c.j; // initialize with data member from an objectint C::s = c.a; // initialize with nonstatic data memberint C::r = 1; // initialize with a constant valueclass Y : private C {} y;

int C::m = Y::f();int C::n = Y::r;int C::p = y.r; // errorint C::q = y.f(); // error

The initializations of C::p and C::q cause errors because y is an object of a class that is derived privately from C, and its members are not accessible to members of C. CONSTANT AND VOLATILE MEMBER FUNCTIONS A member function declared with the const qualifier can be called for constant and nonconstant

objects. A nonconstant member function can only be called for a nonconstant object. Similarly, a member

function declared with the volatile qualifier can be called for volatile and nonvolatile objects. A nonvolatile member function can only be called for a nonvolatile object.

Uses of const and volatile Any declaration can be prefixed with const or volatile A const variable can only be assigned a value when it is defined The const declaration can also be used for parameters in a function definition The volatile keyword can be used to state that a variable may be changed by hardware, the kernel,

another thread etc. For example, the volatile keyword may prevent unsafe compiler optimizations for memory-

mapped input/output The use of pointers and the const keyword is quite subtle: const int *p is a pointer to a const int int const *p is also a pointer to a const int int *const p is a const pointer to an int const int *const p is a const pointer to a const int

STATIC MEMBER FUNCTIONS: You cannot have static and nonstatic member functions with the same names and the same

number and type of arguments.Static data members, you may access a static member function of a class .

A static member function cannot be declared with the keywords virtual, const, volatile, or const volatile.

Example#include<iostream.h>#include<conio.h>class stat{

23 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 24: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

int code;static int count;public:stat(){code=++count;}void showcode(){cout<<"\n\tObject number is :"<<code;}static void showcount(){cout<<"\n\tCount Objects :"<<count;}};int stat::count;void main(){clrscr();stat obj1,obj2;obj1.showcount();obj1.showcode();obj2.showcount();obj2.showcode();getch();} Output: Count Objects: 2Object Number is: 1Count Objects: 2Object Number is: 2Example#include<iostream.h>#include<conio.h>class stat{int code;static int count;public:void showcode(){cout<<"\n\tObject number is :"<<code;}static void showcount(){cout<<"\n\tCount Objects :"<<count;

24 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 25: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

}};int stat::count=1;void main(){clrscr();start::  showcount();start:: showcode();getch();}

POINTER A pointer is a variable whose value is the address of another variable. Like any variable or

constant, you must declare a pointer before you can work with it. The general form of a pointer

variable declaration is:

type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration:

A pointer variable is one that stores an address. We can declare pointers as follows int* p; .This means that p stores the address of a variable of type int.

Pointer is a data type that stores addresses, it is declared as follows: int* a; char* p; etc. The value stored in a pointer p can be accessed through the dereferencing operator “*”. The address of a memory location of a variable can be accessed through the reference operator

“&”.int *ip; // pointer to an integerdouble *dp; // pointer to a doublefloat *fp; // pointer to a floatchar *ch // pointer to character

Example:#include <iostream.h>void main(){ int var = 20; // actual variable declaration.

25 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 26: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

int *ip; // pointer variable ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; } OUTPUT:Value of var variable: 20Address stored in ip variable: 0xbfc601acValue of *ip variable: 20

Example:#include <iostream>int main (){ int firstvalue, secondvalue; int * mypointer;

mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0;}

Example:#include<iostream.h> #include<conio.h> int main() { int i=10; int *Ptr; clrscr(); Ptr=&i; cout<<"\nValue Of i :"<<i; cout<<"\nAddress Of i :"<<i; cout<<"\nValue Of Ptr :"<<Ptr; cout<<"\nAddress Of Ptr :"<<&Ptr; cout<<"\nPtr's Pointer Value:"<<*Ptr; cout<<"\nPtr Equal to &i :"<<*(&i)); 

26 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 27: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

OBJECT AND POINTER

#include <iostream.h>class Value{protected:int val;public:void set_values (int a){ val=a;}};class Cube: public Value{public:int cube(){ return (val*val*val); }};int main () {Cube cb;Value * ptr = &cb;ptr->set_values (10);cout << "The cube of 10 is::" << cb.cube() << endl;return 0;}

Result: The cube of 10 is:: 1000

Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer:

Concept Description

C++ Null PointersC++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.

C++ pointer arithmeticThere are four arithmetic operators that can be used on pointers: ++, --, +, -

C++ pointers vs arraysThere is a close relationship between pointers and arrays. Let us check how?

C++ array of pointersYou can define arrays to hold a number of pointers.

C++ pointer to pointerC++ allows you to have pointer on a pointer and so on.

27 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 28: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

Passing pointers to functions

Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.

Return pointer from functions

C++ allows a function to return a pointer to local variable,static variable and dynamically allocated memory as well.

REFERENCE

A Reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.

C++ References vs Pointers:References are often confused with pointers but three major differences between references and pointers are:

You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.

Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.

A reference must be initialized when it is created. Pointers can be initialized at any time.

Creating   References Think of a variable name as a label attached to the variable's location in memory. You can then

think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the following example:

int i = 17;

We can declare reference variables for i as follows.

int & r = i;Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer reference initialized to i" and read the second declaration as "s is a double reference initialized to d.".

Example :#include <iostream.h> void main (){ // declare simple variables

28 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 29: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

int i; double d; // declare reference variables int& r = i; double& s = d; i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl; d = 11.7; cout << "Value of d : " << d << endl; cout << "Value of d reference : " << s << endl;}

When the above code is compiled together and executed, it produces the following result:Value of i : 5Value of i reference : 5Value of d : 11.7Value of d reference : 11.7 References are usually used for function argument lists and function return values. So following

are two important subjects related to C++ references which should be clear to a C++ programmer:

Concept Description

References as parametersC++ supports passing references as function parameter more safely than parameters.

Reference as return valueYou can return reference from a C++ function like a any other data type can be returned.

THIS   POINTER

Every object has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only

member functions have a this pointer.

Example

#include <iostream.h> class Box{

29 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 30: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

public: // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } int compare(Box box) { return this->Volume() > box.Volume(); } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box};void main( ){ Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2

if(Box1.compare(Box2)) { cout << "Box2 is smaller than Box1" <<endl; } else { cout << "Box2 is equal to or larger than Box1" <<endl; }}When the above code is compiled and executed, it produces the following result:Constructor called.Constructor called.Box2 is equal to or larger than Box1

STORAGE   CLASS

30 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 31: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program

auto register static extern mutable

The auto Storage Class The auto storage class is the default storage class for all local variables.{ int mount; auto int month;}The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables.

The register Storage Class The register storage class is used to define local variables that should be stored in

a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and

can't have the unary '&' operator applied to it (as it does not have a memory location).{ register int miles;}

The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class The static storage class instructs the compiler to keep a local variable in existence during the life-

time of the program instead of creating and destroying it each time it comes into and goes out of scope.

Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it

is declared.

In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.#include <iostream>// Function declaration

31 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 32: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

void func(); static int count = 10; /* Global variable */ main(){ while(count--) { func(); } return 0;}// Function definitionvoid func( ){ static int i = 5; // local static variable i++; std::cout << "i is " << i ; std::cout << " and count is " << count << std::endl;}

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

i is 6 and count is 9i is 7 and count is 8i is 8 and count is 7i is 9 and count is 6i is 10 and count is 5i is 11 and count is 4i is 12 and count is 3i is 13 and count is 2i is 14 and count is 1i is 15 and count is 0

The extern Storage Class The extern storage class is used to give a reference of a global variable that is visible to ALL the

program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at

a storage location that has been previously defined. When you have multiple files and you define a global variable or function, which will be used in

other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file.

The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.

First File: main.cpp

#include <iostream.h>

32 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 33: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

int count ;extern void write_extern(); main(){ count = 5; write_extern();}

Second File: support.cpp

#include <iostream> extern int count; void write_extern(void){ std::cout << "Count is " << count << std::endl;}Here, extern keyword is being used to declare count in another file. Now compile these two files as follows:$g++ main.cpp support.cpp -o writeThis will produce write executable program, try to execute write and check the result as follows:$./write5

The mutable Storage Class The mutable specifier applies only to class objects. It allows a member of an object to override

constness. That is, a mutable member can be modified by a const member function.

FUNCTION A Function is a set of statements that can be used anywhere in the program. Main reason for using

it is to strcuture the programmming by creating function for repetitive tasks.Syntax: return-type function-name(parameter list) { Statements }In the above syntax the "return-type" defines the data type of the value returned by the functions, the "function-name", unique name used to call a function. The "Parameters" are seperated by commas that consist of the data type along with identfiers for the parameters.

Example:#include<iostream.h>int x,y,z,a,b,r;addition(int a, int b)

33 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 34: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

{r = a + b;return (r);}void main(){cout << "Enter the first integer::"; cin >> x;cout << "Enter the second integer::"; cin >> y;z = addition(x,y);cout << "Sum of X and Y is::" << z << '\n';}

Result: Enter the first integer::10 Enter the second integer::20 Sum of X and Y is:: 30

Pass by value Pass by value or Call by value is the method where a copy of the value of the

variables are passed to the function to do specific operation to return the result. The actual values of the variable remains unchanged as changes are made to the

copied values of the variables.Example:

#include <iostream.h> multiply(int a, int b) { int r; r = a * b; return (r); } int main() { int x,y; cout << "Enter the first integer::"; cin >> x; cout << "Enter the second integer::"; cin >> y; cout << "Product of X and Y is::" << multiply(x,y); }

Result: Enter the first integer::10 Enter the second integer::2 Product of X and Y is::20

Pass by reference Pass by reference or Call by reference is the method by which the address of the

variables are passed to the function. The "&" symbol is used to refer the address of the variables to the function.

34 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 35: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

Example: #include <iostream.h> void main( ) { void changes( int& , int& ); int x =10, y=20; cout << "Value of X is::" << x << '\n'; cout << "Value of Y is::" << y << '\n'; changes(x,y); cout << "Changed value of X is::" << x << '\n'; cout << "Changed value of Y is::" << y << '\n'; } void changes(int& a, int& b) { a = a* 10; b = b*100; }

Result: Value of X is::10 Value of Y is::20 Changed value of X is::100 Chnaged value of Y is::2000

DEFAULT ARGUMENTS A default argument is a value given in the declaration that the compiler

automatically inserts if you don’t provide a value in the function call. Default arguments are only placed in the declaration of a function

(typically placed in a header file). The compiler must see the default value before it can use it.

Example 1:

Void add(int size, int initQuantity = 0);Example 2:void myFunc(int a,int b,int c,int d);void myFunc(int a,int c) { myFunc(a,20,c,40);}

PROGRAM#include <iostream.h>void main(){

35 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 36: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

cout << "Welcome to the wonderful world of C++!!!\n";

LARGEST OF TWO NUMBERSclass name{private:int a;int b;public:void show(){cout<<"enter the a and b value";cin<<a<<b;if(a>b)cout<<"a is largest";elsecout<<"b is largest";}};void main(){name n;n.show();}CALCULATE THE SUM OF THE INTEGERS FROM 1 TO 10#include <iostream.h> void main(){   int sum;    int x;    x = 1;    sum = 0;    while ( x <= 10 )   {      sum += x;      x++;   }   cout << "The sum is: " << sum << endl;   } Program#include <iostream.h>int GCD(int a, int b){

36 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 37: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

int Remainder;

while( b != 0 ){Remainder = a % b;a = b;b = Remainder;}return a;}void main(){int x, y;cout << "This program allows calculating the GCD\n";cout << "Value 1: ";cin >> x;cout << "Value 2: ";cin >> y;cout << "\nThe Greatest Common Divisor of "<< x << " and " << y << " is " << GCD(x, y) << endl;}Program To calculate x raised to the power y.#include <iostream.h>void main(){doule x,y;cout << "Enter number to be raised to power : ";cin >> x;cout << "Enter the exponent : "; cin >> y;double result = pow(a,b);cout << "Result is " << result <<endl;getch();}

PROGRAM TO REPRESENT A BANK ACCOUNT (IMPLEMENTED AS A CLASS)# include<conio.h>include <iostream>class bank{char name[20];int acno;char actype[4];float balance;public:void init();

37 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 38: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

void deposit();void withdraw();void disp_det();};void bank :: init(){cout<<"New Account";cout<<"Enter the Name of the depositor : ";cin.get(name,19,'');cout<<"Enter the Account Number : ";cin>>acno;cout<<"Enter the Account Type : (CURR/SAVG/FD/RD/DMAT) ";cin>>actype;cout<<"Enter the Amount to Deposit : ";cin >>balance;}void bank :: deposit(){float more;cout <<"Depositing";cout<<"Enter the amount to deposit : ";cin>>more;balance+=more;}void bank :: withdraw(){float amt;cout<<"Withdrwal";cout<<"Enter the amount to withdraw : ";cin>>amt;balance-=amt;}void bank :: disp_det(){cout<<"Account Details";cout<<"Name of the depositor : "<<name<<endl;cout<<"Account Number : "<<acno<<endl;cout<<"Account Type : "<<actype<<endl;cout<<"Balance : $"<<balance<<endl;}// main function , exectution starts herevoid main(void){clrscr();bank obj;int choice =1;while (choice != 0 )

38 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC

Page 39: Cs6301 programming and datastactures

UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II

{cout<<"Enter 0 to exit1. Initialize a new acc.2. Deposit3.Withdraw4.See A/c Status";cin>>choice;switch(choice){case 0 :obj.disp_det();cout<<"EXITING PROGRAM.";break;case 1 : obj.init();break;case 2: obj.deposit();break;case 3 : obj.withdraw();break;case 4: obj.disp_det();break;default: cout<<"Illegal Option"<<endl;}}getch();}

39 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC