SlideShare ist ein Scribd-Unternehmen logo
1 von 39
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
1 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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:45PERIODS
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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
2 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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 passing
Objects
 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:
Object:student
Data:name,
marks
Functions:tota
l
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
3 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
4 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
 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);
information
messsage
object
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
5 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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.
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
6 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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 double
Long 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: 10
In 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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
7 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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.
 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.
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
8 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
Example:
#include <iostream.h>
#include <stdio.h>
void main( )
{
const long int l = 35000L-34L;  Integer Constant
const int hex = 0x80;  Hexadecimal Constant
cout << "Integer constants value is:" << l << 'n';
cout << "Hexadecimalconstants value is:" << hex << 'n';
printf ("nt 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;
};
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
9 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
Example:
#include <iostream.h>
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;}
};
};
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
10 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
void main()
{
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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
11 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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
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 : 210
Volume of Box2 : 1560
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
12 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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 explicitly
const 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();
}
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
13 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
CONSTRUCTOR
 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-Variables
Member-Functions
public:
class-name() // constructor
{
// Constructor code
}
... other Variables & Functions
}
Example:
class example
{
int a,b;
public:
//Constructor
example()
{
a=10;
b=20;
cout<<"Im Constructor"
}
void Display()
{
cout<<"Values :"<<a<<"t"<<b;
}
}
void main()
{
example Object;
Object.Display()
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
14 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
}
Output:
10 20
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-Variables
Member-Functions
public:
class-name(type Variable,type Varibale2......)
{
// Constructor code
}
... other Variables & Functions
}
Example:
class example
{
int a,b;
public:
//Constructor
Example(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()
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
15 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
}
Output:
10 20
PROGRAM:
#include <iostream.h>
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;
}
void main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
}
OUTPUT:
Object is being created, length = 10
Length of line : 10
Length of line : 6
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
16 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
Default Constructors
 If you have written a constructor for your class then when you create an instance of it, the
constructor is automatically called.
 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()
{
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
17 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
cout<<"NAME IS:->"<<name<<endl;
}
void join(str &a,str &b);
};
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;
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
18 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
rvalue=pamount;
for(int i=1;i<=y;i++)
rvalue=rvalue*(1.0+r);
}
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.
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
19 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
 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>
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)
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
20 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
{
x=y=a;
}
complex (float real,float imag)
{
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.
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
21 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
Syntax:
class class-name
{
Access Specifier:
Member-Variables
Member-Functions
public:
~ 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: declaration
private:
double length;
};
// Member functions definitions including constructor
line::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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
22 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
void main( )
{
line line;
// set line length
line.setlength(6.0);
cout << "Length of line : " << line.getlength() <<endl;
}
OUTPUT:
Object is being created
Length of line : 6
Object is being deleted
STATIC DATA AND MEMBER FUNCTION
STATIC 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; }
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
23 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
};
C c;
int C::i = C::f(); // initialize with static member function
int C::j = C::i; // initialize with another static data member
int C::k = c.f(); // initialize with member function from an object
int C::l = c.j; // initialize with data member from an object
int C::s = c.a; // initialize with nonstatic data member
int C::r = 1; // initialize with a constant value
class Y : private C {} y;
int C::m = Y::f();
int C::n = Y::r;
int C::p = y.r; // error
int 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.
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
24 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
Example
#include<iostream.h>
#include<conio.h>
class stat
{
int code;
static int count;
public:
stat()
{
code=++count;
}
void showcode()
{
cout<<"ntObject number is :"<<code;
}
static void showcount()
{
cout<<"ntCount Objects :"<<count;
}
};
int stat::count;
void main()
{
clrscr();
stat obj1,obj2;
obj1.showcount();
obj1.showcode();
obj2.showcount();
obj2.showcode();
getch();
}
Output:
Count Objects: 2
Object Number is: 1
Count Objects: 2
Object Number is: 2
Example
#include<iostream.h>
#include<conio.h>
class stat
{
int code;
static int count;
public:
void showcode()
{
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
25 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
cout<<"ntObject number is :"<<code;
}
static void showcount()
{
cout<<"ntCount Objects :"<<count;
}
};
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 integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
26 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
Example:
#include <iostream.h>
void main()
{
int var = 20; // actual variable declaration.
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: 20
Address stored in ip variable: 0xbfc601ac
Value 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;
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
27 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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));
}
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 Pointers
C++ supports null pointer, which is a
constant with a value of zero defined
in several standard libraries.
C++ pointer arithmetic
There are four arithmetic operators
that can be used on pointers: ++, --, +,
-
C++ pointers vs arrays
There is a close relationship between
pointers and arrays. Let us check how?
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
28 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
C++ array of pointers
You can define arrays to hold a
number of pointers.
C++ pointer to pointer
C++ allows you to have pointer on a
pointer and so on.
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.".
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
29 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
Example :
#include <iostream.h>
void main ()
{
// declare simple variables
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 : 5
Value of i reference : 5
Value of d : 11.7
Value 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 parameters
C++ supports passing references as
function parameter more safely than
parameters.
Reference as return value
You 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.
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
30 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
Example
#include <iostream.h>
class Box
{
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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
31 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
STORAGE CLASS
 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.
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
32 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
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
void func();
static int count = 10; /* Global variable */
main()
{
while(count--)
{
func();
}
return 0;
}
// Function definition
void 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 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i 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.
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
33 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
First File: main.cpp
#include <iostream.h>
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 write
This will produce write executable program, try to execute write and check the result as follows:
$./write
5
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:
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
34 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
#include<iostream.h>
int x,y,z,a,b,r;
addition(int a, int b)
{
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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
35 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
 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.
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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
36 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
#include <iostream.h>
void main()
{
cout << "Welcome to the wonderful world of C++!!!n";
LARGEST OF TWO NUMBERS
class 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";
else
cout<<"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
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
37 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
#include <iostream.h>
int GCD(int a, int b)
{
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 GCDn";
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];
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
38 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
float balance;
public:
void init();
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 here
void main(void)
{
clrscr();
UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II
39 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC
bank obj;
int choice =1;
while (choice != 0 )
{
cout<<"Enter 0 to exit
1. Initialize a new acc.
2. Deposit
3.Withdraw
4.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();
}

Weitere ähnliche Inhalte

Was ist angesagt?

Advanced Excel
Advanced Excel Advanced Excel
Advanced Excel eduCBA
 
Principal of objected oriented programming
Principal of objected oriented programming Principal of objected oriented programming
Principal of objected oriented programming Rokonuzzaman Rony
 
Object oriented vs. object based programming
Object oriented vs. object based  programmingObject oriented vs. object based  programming
Object oriented vs. object based programmingMohammad Kamrul Hasan
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented languagefarhan amjad
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Objectdkpawar
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programmingHariz Mustafa
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)indiangarg
 
Principles of object oriented programming
Principles of object oriented programmingPrinciples of object oriented programming
Principles of object oriented programmingAmogh Kalyanshetti
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingIqra khalil
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in pythonnitamhaske
 
diffrence between procedure oriented programming & object oriented programmin...
diffrence between procedure oriented programming & object oriented programmin...diffrence between procedure oriented programming & object oriented programmin...
diffrence between procedure oriented programming & object oriented programmin...nihar joshi
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...Make Mannan
 
OOPS with C++ | Concepts of OOPS | Introduction
OOPS with C++ | Concepts of OOPS | IntroductionOOPS with C++ | Concepts of OOPS | Introduction
OOPS with C++ | Concepts of OOPS | IntroductionADITYATANDONKECCSE
 
Intro To C++ - Class 07 - Headers, Interfaces, & Prototypes
Intro To C++ - Class 07 - Headers, Interfaces, & PrototypesIntro To C++ - Class 07 - Headers, Interfaces, & Prototypes
Intro To C++ - Class 07 - Headers, Interfaces, & PrototypesBlue Elephant Consulting
 

Was ist angesagt? (20)

Core java(2)
Core java(2)Core java(2)
Core java(2)
 
Advanced Excel
Advanced Excel Advanced Excel
Advanced Excel
 
Oops
OopsOops
Oops
 
Principal of objected oriented programming
Principal of objected oriented programming Principal of objected oriented programming
Principal of objected oriented programming
 
Object oriented vs. object based programming
Object oriented vs. object based  programmingObject oriented vs. object based  programming
Object oriented vs. object based programming
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)
 
Principles of object oriented programming
Principles of object oriented programmingPrinciples of object oriented programming
Principles of object oriented programming
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
2 Object Oriented Programming
2 Object Oriented Programming2 Object Oriented Programming
2 Object Oriented Programming
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Compare between pop and oop
Compare between pop and oopCompare between pop and oop
Compare between pop and oop
 
diffrence between procedure oriented programming & object oriented programmin...
diffrence between procedure oriented programming & object oriented programmin...diffrence between procedure oriented programming & object oriented programmin...
diffrence between procedure oriented programming & object oriented programmin...
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
 
OOPS with C++ | Concepts of OOPS | Introduction
OOPS with C++ | Concepts of OOPS | IntroductionOOPS with C++ | Concepts of OOPS | Introduction
OOPS with C++ | Concepts of OOPS | Introduction
 
Intro To C++ - Class 07 - Headers, Interfaces, & Prototypes
Intro To C++ - Class 07 - Headers, Interfaces, & PrototypesIntro To C++ - Class 07 - Headers, Interfaces, & Prototypes
Intro To C++ - Class 07 - Headers, Interfaces, & Prototypes
 

Ähnlich wie Cs6301 programming and datastactures

Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesFellowBuddy.com
 
CSc investigatory project
CSc investigatory projectCSc investigatory project
CSc investigatory projectDIVYANSHU KUMAR
 
1 intro
1 intro1 intro
1 introabha48
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]Rome468
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++ shammi mehra
 
Software_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxSoftware_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxArifaMehreen1
 
Programming in c++
Programming in c++Programming in c++
Programming in c++MalarMohana
 
Programming in c++
Programming in c++Programming in c++
Programming in c++sujathavvv
 
A Hand Book of Visual Basic 6.0.pdf.pdf
A Hand Book of Visual Basic 6.0.pdf.pdfA Hand Book of Visual Basic 6.0.pdf.pdf
A Hand Book of Visual Basic 6.0.pdf.pdfAnn Wera
 
Interview preparation for programming.pptx
Interview preparation for programming.pptxInterview preparation for programming.pptx
Interview preparation for programming.pptxBilalHussainShah5
 
C++Day-1 Introduction.ppt
C++Day-1 Introduction.pptC++Day-1 Introduction.ppt
C++Day-1 Introduction.pptcitizen15
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNicole Gomez
 

Ähnlich wie Cs6301 programming and datastactures (20)

Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 
CSc investigatory project
CSc investigatory projectCSc investigatory project
CSc investigatory project
 
1 intro
1 intro1 intro
1 intro
 
Unit 5.ppt
Unit 5.pptUnit 5.ppt
Unit 5.ppt
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
 
C++
C++C++
C++
 
chapter - 1.ppt
chapter - 1.pptchapter - 1.ppt
chapter - 1.ppt
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++
 
Intro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm ReviewIntro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm Review
 
OOP ppt.pdf
OOP ppt.pdfOOP ppt.pdf
OOP ppt.pdf
 
Software_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxSoftware_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptx
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
Bp301
Bp301Bp301
Bp301
 
A Hand Book of Visual Basic 6.0.pdf.pdf
A Hand Book of Visual Basic 6.0.pdf.pdfA Hand Book of Visual Basic 6.0.pdf.pdf
A Hand Book of Visual Basic 6.0.pdf.pdf
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++
 
Interview preparation for programming.pptx
Interview preparation for programming.pptxInterview preparation for programming.pptx
Interview preparation for programming.pptx
 
C++Day-1 Introduction.ppt
C++Day-1 Introduction.pptC++Day-1 Introduction.ppt
C++Day-1 Introduction.ppt
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
Topic 1 PBO
Topic 1 PBOTopic 1 PBO
Topic 1 PBO
 

Kürzlich hochgeladen

Multiple time frame trading analysis -brianshannon.pdf
Multiple time frame trading analysis -brianshannon.pdfMultiple time frame trading analysis -brianshannon.pdf
Multiple time frame trading analysis -brianshannon.pdfchwongval
 
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改yuu sss
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxEmmanuel Dauda
 
MK KOMUNIKASI DATA (TI)komdat komdat.docx
MK KOMUNIKASI DATA (TI)komdat komdat.docxMK KOMUNIKASI DATA (TI)komdat komdat.docx
MK KOMUNIKASI DATA (TI)komdat komdat.docxUnduhUnggah1
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFAAndrei Kaleshka
 
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...limedy534
 
DBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfDBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfJohn Sterrett
 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...dajasot375
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceSapana Sha
 
ASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel CanterASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel Cantervoginip
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort servicejennyeacort
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
IMA MSN - Medical Students Network (2).pptx
IMA MSN - Medical Students Network (2).pptxIMA MSN - Medical Students Network (2).pptx
IMA MSN - Medical Students Network (2).pptxdolaknnilon
 
RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.natarajan8993
 
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSINGmarianagonzalez07
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degreeyuu sss
 

Kürzlich hochgeladen (20)

Multiple time frame trading analysis -brianshannon.pdf
Multiple time frame trading analysis -brianshannon.pdfMultiple time frame trading analysis -brianshannon.pdf
Multiple time frame trading analysis -brianshannon.pdf
 
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptx
 
MK KOMUNIKASI DATA (TI)komdat komdat.docx
MK KOMUNIKASI DATA (TI)komdat komdat.docxMK KOMUNIKASI DATA (TI)komdat komdat.docx
MK KOMUNIKASI DATA (TI)komdat komdat.docx
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFA
 
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
 
DBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfDBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdf
 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts Service
 
ASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel CanterASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel Canter
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
 
IMA MSN - Medical Students Network (2).pptx
IMA MSN - Medical Students Network (2).pptxIMA MSN - Medical Students Network (2).pptx
IMA MSN - Medical Students Network (2).pptx
 
RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.
 
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
 

Cs6301 programming and datastactures

  • 1. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 1 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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:45PERIODS 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
  • 2. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 2 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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 passing Objects  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: Object:student Data:name, marks Functions:tota l
  • 3. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 3 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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
  • 4. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 4 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC  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); information messsage object
  • 5. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 5 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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.
  • 6. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 6 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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 double Long 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: 10 In 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
  • 7. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 7 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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.  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.
  • 8. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 8 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC Example: #include <iostream.h> #include <stdio.h> void main( ) { const long int l = 35000L-34L; Integer Constant const int hex = 0x80; Hexadecimal Constant cout << "Integer constants value is:" << l << 'n'; cout << "Hexadecimalconstants value is:" << hex << 'n'; printf ("nt 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; };
  • 9. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 9 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC Example: #include <iostream.h> 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;} }; };
  • 10. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 10 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC void main() { 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
  • 11. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 11 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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 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 : 210 Volume of Box2 : 1560
  • 12. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 12 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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 explicitly const 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(); }
  • 13. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 13 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC CONSTRUCTOR  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-Variables Member-Functions public: class-name() // constructor { // Constructor code } ... other Variables & Functions } Example: class example { int a,b; public: //Constructor example() { a=10; b=20; cout<<"Im Constructor" } void Display() { cout<<"Values :"<<a<<"t"<<b; } } void main() { example Object; Object.Display()
  • 14. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 14 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC } Output: 10 20 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-Variables Member-Functions public: class-name(type Variable,type Varibale2......) { // Constructor code } ... other Variables & Functions } Example: class example { int a,b; public: //Constructor Example(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()
  • 15. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 15 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC } Output: 10 20 PROGRAM: #include <iostream.h> 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; } void main( ) { Line line(10.0); // get initially set length. cout << "Length of line : " << line.getLength() <<endl; // set line length again line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; } OUTPUT: Object is being created, length = 10 Length of line : 10 Length of line : 6
  • 16. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 16 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC Default Constructors  If you have written a constructor for your class then when you create an instance of it, the constructor is automatically called.  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() {
  • 17. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 17 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC cout<<"NAME IS:->"<<name<<endl; } void join(str &a,str &b); }; 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;
  • 18. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 18 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC rvalue=pamount; for(int i=1;i<=y;i++) rvalue=rvalue*(1.0+r); } 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.
  • 19. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 19 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC  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> 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)
  • 20. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 20 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC { x=y=a; } complex (float real,float imag) { 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.
  • 21. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 21 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC Syntax: class class-name { Access Specifier: Member-Variables Member-Functions public: ~ 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: declaration private: double length; }; // Member functions definitions including constructor line::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
  • 22. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 22 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC void main( ) { line line; // set line length line.setlength(6.0); cout << "Length of line : " << line.getlength() <<endl; } OUTPUT: Object is being created Length of line : 6 Object is being deleted STATIC DATA AND MEMBER FUNCTION STATIC 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; }
  • 23. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 23 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC }; C c; int C::i = C::f(); // initialize with static member function int C::j = C::i; // initialize with another static data member int C::k = c.f(); // initialize with member function from an object int C::l = c.j; // initialize with data member from an object int C::s = c.a; // initialize with nonstatic data member int C::r = 1; // initialize with a constant value class Y : private C {} y; int C::m = Y::f(); int C::n = Y::r; int C::p = y.r; // error int 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.
  • 24. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 24 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC Example #include<iostream.h> #include<conio.h> class stat { int code; static int count; public: stat() { code=++count; } void showcode() { cout<<"ntObject number is :"<<code; } static void showcount() { cout<<"ntCount Objects :"<<count; } }; int stat::count; void main() { clrscr(); stat obj1,obj2; obj1.showcount(); obj1.showcode(); obj2.showcount(); obj2.showcode(); getch(); } Output: Count Objects: 2 Object Number is: 1 Count Objects: 2 Object Number is: 2 Example #include<iostream.h> #include<conio.h> class stat { int code; static int count; public: void showcode() {
  • 25. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 25 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC cout<<"ntObject number is :"<<code; } static void showcount() { cout<<"ntCount Objects :"<<count; } }; 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 integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character
  • 26. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 26 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC Example: #include <iostream.h> void main() { int var = 20; // actual variable declaration. 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: 20 Address stored in ip variable: 0xbfc601ac Value 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;
  • 27. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 27 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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)); } 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 Pointers C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries. C++ pointer arithmetic There are four arithmetic operators that can be used on pointers: ++, --, +, - C++ pointers vs arrays There is a close relationship between pointers and arrays. Let us check how?
  • 28. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 28 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC C++ array of pointers You can define arrays to hold a number of pointers. C++ pointer to pointer C++ allows you to have pointer on a pointer and so on. 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.".
  • 29. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 29 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC Example : #include <iostream.h> void main () { // declare simple variables 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 : 5 Value of i reference : 5 Value of d : 11.7 Value 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 parameters C++ supports passing references as function parameter more safely than parameters. Reference as return value You 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.
  • 30. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 30 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC Example #include <iostream.h> class Box { 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
  • 31. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 31 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC STORAGE CLASS  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.
  • 32. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 32 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC 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 void func(); static int count = 10; /* Global variable */ main() { while(count--) { func(); } return 0; } // Function definition void 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 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i 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.
  • 33. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 33 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC First File: main.cpp #include <iostream.h> 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 write This will produce write executable program, try to execute write and check the result as follows: $./write 5 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:
  • 34. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 34 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC #include<iostream.h> int x,y,z,a,b,r; addition(int a, int b) { 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
  • 35. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 35 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC  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. 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
  • 36. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 36 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC #include <iostream.h> void main() { cout << "Welcome to the wonderful world of C++!!!n"; LARGEST OF TWO NUMBERS class 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"; else cout<<"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
  • 37. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 37 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC #include <iostream.h> int GCD(int a, int b) { 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 GCDn"; 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];
  • 38. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 38 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC float balance; public: void init(); 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 here void main(void) { clrscr();
  • 39. UNIT –I CS6301 PROGRAMMING AND DATA STRUCTURES II 39 Prepared by Mr.K.S.Ramesh M.E., AP CSE/AREC bank obj; int choice =1; while (choice != 0 ) { cout<<"Enter 0 to exit 1. Initialize a new acc. 2. Deposit 3.Withdraw 4.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(); }