II YEAR / III SEMESTER
20IT302 - C++ AND DATA STRUCTURES
UNIT I
OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
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
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
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
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
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.
Object Oriented Programming Concepts
Classes:
• A class is a collection of objects that have
identical properties, common behavior and
shared relationship.
• Classes are user defined data types. A class can
hold both data and functions.
• For example: Fruit, Animal etc
Objects:
• Object is a basic unit of Object Oriented Programming.
• They are instances of class
• Interacts by sending messages to one another. Object is
a basic unit of Object Oriented Programming.
• They are instances of class which interacts by sending
messages to one another.
• Example: Apple, orange, mango are the objects of class
fruit.
Data Abstraction, Encapsulation & Data Hiding
Data Abstraction:
• Data Abstraction refers to the process of
representing essential features without including
background details or explanations.
EXAMPLE:
Let's take one real life example of a TV, which you can turn on
and off, change the channel, adjust the volume, and add
external components such as speakers, VCRs, and DVD
players, BUT you do not know its internal details, that is, you
do not know how it receives signals over the air or through a
cable, how it translates them, and finally displays them on the
scree
Data Encapsulation:
• The wrapping of data and functions into a single
unit (class) is called data encapsulation.
• Encapsulation is a method of combining the
data(variables) and functions(methods) inside a
class.
• The data is not accessible to the outside world.
• Only the member function wrapped in the class
access it.
Hiding of data from direct access by the program is
called as Information hiding or Data hiding
Data hiding is a method used in object oriented
programming to hide information within computer
code.
Inheritance
• Inheritance is the process by which one object
can acquire and use the properties of another
object.
• The existing class is known as base class or super
class or parent class.
• The new class is known as derived class or sub
class or child class.
• The derived class shares some of the properties of
the base class. Therefore a code from a base class
can be reused by a derived class.
Cube
Square
Rectangle
height width
Shape
Polymorphism
• The ability of an operator and function to take
multiple forms is known as Polymorphism.
There are two types of polymorphism.
Compile time polymorphism:
Object is bound to the function call at the compile
time.
Run time polymorphism:
Object is bound to the function call only at the run
time.
• Overloading is a part of polymorphism, where a
function or operator is made and defined many
times to perform different functions.
• There are two types of overloading
o Operator Overloading
o Function Overloading
OPERATOR OVERLOADING
The operator is overloaded to provide the special meaning to the user-defined
data type.
• Example:
Overloading ‘+’ operator to perform addition and concatenation of two strings.
FUNCTIONS OVERLOADING
Function overloading means two or more function have same name, but differ in
the number of arguments or data type of arguments.
Example:
int add(int);
int add(int, int);
int add(int, float);
Dynamic binding & Message Passing
Dynamic binding:
◦ Binding is the process of connecting one program to
another.
◦ Dynamic Binding refers to the process of linking a
procedure call to the procedure code that will be
executed only at run time.
Message Passing:
◦ Objects communicate with one another by sending and
receiving information to each other
◦ A message for an object is request for execution of
procedure.
◦ Message passing involves specifying the name of the object,
the name of the function (message) and the information to be
sent.
Benefits of OOP
•Understandability
•Reusability
•Security
•Modularity
Applications of OOP
• Real time system
• Simulation and Modelling
• User Interface Design
• Object Oriented Databases
• AI and Expert Systems
• Neural Networks and Parallel Programming
• Decision Support and Office Automation System
• CAD/CAM systems etc.,
HEADER FILE
# include <iostream.h> - To use the input and output statements.
# - Preprocessor
include - Keyword
io - Input and Output.
stream - Sequence of bytes.
.h - Header file.
# include <conio.h> - To use the clrscr( ) and getch( ) statements.
# include<math.h> - To use the mathematical functions (Sine or Cos
etc.,)
CLASS DEFINITION:
class classname
{
Access specifier://Can be private,public or protected
Data Declaration;//Variables used
Access specifier:
Member function declaration or definition;
};
MEMBER FUNCTIONS
Member Function Declaration:
returntype functionname (datatype variablename);
• Returntype – void or int
• Function name – User Defined Name
• Datatype – int
• Variable name - User Defined Name
Member Function definition:
returntype functionname (datatype variablename)
{
-------
}
Main Function:
The main() function is the first function in your program that
is executed when it begins executing
int main ( )
{
classname object;
object.functionname ( );
return 0;
}
EXAMPLE
# include <iostream.h>
class display
{
int a,b,c;
public:
void dis( )
{
cin>>a>>b;
c=a+b;
cout<<c;
}
};
int main( )
{
display d;
d.dis( );
return 0;
}
DATA ABSTRACTION
• Provides only the necessary details
• As the name suggests, abstraction is the “abstract form of
anything”.
• In programming language abstraction is implemented using
Interface and abstract class, which represents abstract view
of methods and proper- ties of class.
Two types of abstraction. They are
• Data abstraction
• Function abstraction
DATA ABSTRACTION
• Data that can be used without knowing how it is stored is called Data
Abstraction.
Example : int x, y;
FUNCTION ABSTRACTION
Functions that can be used without knowing its implementation details is called
Function Abstraction.
Ex:
• <iostream.h> : cin, cout
• <string.h> : strcat( ), strcpy( ), strcmp( ), strlen( );
Abstraction using
access specifiers
• Members defined with a public
access specifiers are accessible to
all parts of the program.
• Members defined with a private
access specifiers are not
accessible to code that uses the
class. The private section hides
the implementation from code
that uses the type.
DATA ENCAPSULATION
• Binds data and functions together
• Keeps the data safe from outside
interface and misuse.
• The data is not accessible to the outside
world and only those functions, which
are wrapped in the class are able to
access it.
• Encapsulation is implemented using
private and protected access specifiers.
• The process by which one object can acquire the properties of
another object:
• A. Encapsulation
• B. Inheritance
• C. Polymorphism
• An object that has more than one form is referred to as:
• A. Inheritance
• B. Interface
• C. Abstract class
• D. Polymorphism
Basics of C++ Program
Basic Console I/O Statements in C++
The output operator is <<. To output to the console, use
cout << expression;
cout << “Hello World n”;
cout << “236.99”;
The input operator is >>. To input values from keyboard, use
cin >> variables;
int a,b;
cin>>a>>b;
Comments
A comment in C++ can be given in a same way as we give in C.
/* —— */ is a multiline comment and // is a single line comment.
For Example
/* This is a multiline comment and can Span for multiline. This
comment is similar to C */
// This is a single line comment
C++ Tokens
• Keywords
• Identifiers
• Constants
• Operators
Keywords
Identifiers
• An identifier is formed with a sequence of letters (including ‘_ ‘) and
digits
• Examples of valid variable names are myname, jj, name123
• Examples of invalid variables
12B Invalid variable name since its starts with a number.
Basic pay Invalid variable name since it has a space
ABC,1 Invalid variable name since , is a special character
Constants
• Constants refer to values that do not change during the execution of
the program. Ex- amples for constants are
1998 Integer constant
25.789 Floating point constant
“Hello World” String constant
‘a’ Character constant
Operators
: :
()[], ->, ., typeid, casts,
! (negation), ~ (bit-not)
new, delete ++, , - (unary), *(unary), &
(unary), sizeof
*, /, % (modulus)
- +
<<, >>
<, <=, >, >=
= =, !=
Data Types
• Built in Data types
• User Defined Data types
• Derived Data types
Built in Data Types
• Signed integer
int x,y;
long int a;
• Unsigned integer
unsigned short a;
unsigned long x;
• Character type
char x;
• Floating point types
double m;
float f;
• Boolean type
bool logic;
User Defined Data Types
• Structures, Unions and Classes
• A structure is a collection of one or more variables; the variables may
belong to different types, grouped together under a single name for
easy handling.
struct point
{
int x;
int y;
}p1,p2;
Union
• A union is a user defined data type that may hold (at different times)
objects of different types and sizes
union u1
{
int i; float f; char c;
}u;
CLASS
• A Class is a user defined data-type which has data members and
member functions.
• Data members are the data variables
• Member functions are the functions used to manipulate behavior of
the objects in a Class
class class_name
{
access_specifier 1 :
member 1;
access_specifier 2 :
member 2;
---
};
• Access specifiers modifies the access rights for the member and it
contains three keywords.
They are
•Private
•Protected
•Public
• Private members -accessible only from within the same class.It cannot be
accessed outside the class.
• Protected members - accessible from members of their same class and
also from members of their derived classes.
• Public members are accessible from anywhere.
• By default, all members of a class have private access for all its members.
class Rectangle
{
int x, y;
public :
void area( );
void display( );
};
OBJECT
• Object is an instance of a class.
Syntax:
classname object;
Employee e1, e2;
Example
e1.tax_calculation( );
Example:
CONSTRUCTORS AND DESTRUCTORS
• Constructor in C++ is a special method that is invoked automatically
at the time of object creation.
• The constructor are used for object initialization or memory
allocation.
• The destructor performs deallocation of memory or other clean_up
for objects.
• The constructor has the same name as the class name and it doesn’t
return any type.
• The destructor also defined same as constructor with ‘~’ in front.
• The compiler calls the constructor whenever an object is created and
destructors are called when a class object goes out of scope.
#include <iostream>
using namespace std;
class sample
{
public :
int x;
public :
sample( )
{
x = 1;
cout<<x;
}
};
int main( )
{
sample s;
return 0;
}
Output:
1
Destructor
class sample
{
int x;
public :
~ sample( )
{
delete x :
}
};
Limitations
• Constructors and destructors cannot have return type
• Pointers and references cannot be used on constructors and
destructors
• Constructors and destructors cannot be declared static, const or
volatile
• Constructors cannot be declared with the keyword virtual.
STATIC MEMBERS
• Static Member of a class can contain static member data and static member
function.
• It must be declared with the keyword static.
Static Data Member:
• A variable is a part of a class which is not a part of an object is called a static
member.
• When a data member is declared as static only one copy of the data is maintained
for all objects of the class.
• (i.e) All other objects must share that copy.
• It is automatically initialized to 0, when the first object of the class is created.
• It must be initialized always outside the class using scope resolution operator ‘: :’
along with the class name.
Syntax:
static data_type data_member;
• static is a keyword of the predefined library
#include <iostream>
using namespace std;
class GfG
{
public:
static int i;
};
int GfG::i=10;
int main()
{
GfG obj1;
GfG obj2;
cout << obj1.i<<" "<<obj2.i;
return 0; Output: 10 10
}
• Static Member function:
The static member functions are special functions used to access
the static data members or other static member functions.
It can be declared with the keyword static.
A static function will be called using the class name followed by
scope resolution operator
class_name : : function_name( );
A static function is common to the entire class.
#include <iostream>
using namespace std;
class Note
{
static int num;
public:
static int func ()
{
return num;
}
};
int Note :: num = 5;
int main ()
{
cout << " The value of the num is: " << Note:: func () << endl;
return 0;
} Output: The value of the num is: 5
CONSTANT MEMBERS
Constant Data Member
• Data Members of a class can be declared as constant using the
keyword ‘const’ in the member declaration.
• They are not initialized during the declaration.
• Constant data members can be initialized using the constructor.
• Once initialized it cannot be changed
Syntax:
const datatype variable_name;
#include <iostream>
using namespace std;
int main ()
{
const int num = 25;
num = num + 10;
return 0;
}
Output: Compiler Error
CONSTANT MEMBER FUNCTION
• A const is a constant member function of a class that never changes
any class data members, and it also does not call any non-const
function.
• It is also known as the read-only function.
• We can create a constant member function of a class by adding the
const keyword after the name of the member function.
SYNTAX:
return_type mem_fun() const
{
}
the const keyword is used after the name of the member function to
make it constant
#include <iostream>
using namespace std;
class Data
{
int val=25;
public:
int getValue() const
{
return val;
}
};
int main()
{
Data d;
cout << d.getValue();
return 0;
}
MEMBER FUNCTIONS
•Member functions are the functions that are declared
inside the class definition and works on the data
members (variables) of the class
•Member functions can be defined inside or outside of
the class.
•If the member function is defined inside the class
definition it is called Inline function, which can be
defined directly.
Member function is defined
inside the class definition
#include <iostream>
using namespace std;
class area {
public:
int x=5;
public:
void square()
{
cout<<x*x;
}
};
int main()
{
area a;
a.square();
return 0;
}
Output : 25
•If it is declared outside the class, it should be defined
using the scope resolution operator : : along with class
name and function name.
•Here the function must be declared inside the class
definition first, and then defined outside.
•By default, all member functions and variables are
private to that class
#include <iostream>
using namespace std;
class area {
public:
int x=5;
public:
void square();
};
void area::square()
{
cout<<x*x;
}
int main()
{
area a;
a.square();
return 0;
}
Output : 25
Friend Function
• A function that is declared with a keyword friend is known as friend
function.
• Function can be declared as a friend in any number of classes.
• The function defined elsewhere in the program.
• Function definition doesn’t use either keyword friend or scope
resolution operator.
• Friend function although not a member function, it has full rights to
access the private members of a class
Declaration
class class-name
{
public:
…..
friend returntype functionname(); //friend function declaration
};
Output: Hai
#include <iostream>
using namespace std;
class one
{
private:
friend void func();
};
void func()
{
cout<<"Hai";
}
int main()
{
func();
return 0;
}
Output:
#include <iostream>
using namespace std;
class one
{
private:
void func();
};
void one::func()
{
cout<<"Hai";
}
int main()
{
one x;
x.func();
return 0;
}
• Friend Class : A friend class can access private and protected members of other class in
which it is declared as friend.
• It is useful to allow a particular class to access private members of other class.
Syntax for implementing a friend class is:
class ClassB;
class ClassA
{
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
};
class ClassB
{
... .. ...
};
Characteristics:
• It’s not in the scope of the class.
• Since it is not in the scope of the class it can’t be called using
object of that class.
• It can be invoked like a normal function without help of any
object.
• It can be declared either in public or private part of the class.
POINTERS
• Pointer is a variable which stores the address of another variable.
• It defines the location to get the value of a specific data variable
instead of defining the actual data.
Pointer declaration
• Pointer declaration consists of datatype, * and a variable name.
Syntax:
Datatype * variablename;
Example:
int *p;
char *p1;
Initialization of Pointer Variable:
• Pointer variable can be initialized by storing the address of another
variable
Syntax:
pointervariable = &variablename;
Example:
int *num;
int x;
num = & x;
int a=10;
int *b;
b=&a;
a=10
&a = address(a)=2000
int *b;
b=&a; b=2000
&b=4000
Example:
int main( )
{
int *ptr;
int a = 10;
ptr = &a;
cout << “The value of ptr is” <<*ptr;
}
Output
The value of ptr is 10
Pointers Arithmetic
• Only addition and subtraction operation are allowed in pointers.
• The increment and decrement operators can be used as either prefix or suffix of an
expression.
#include<iostream>
int main( )
{
int a[3] = {10, 20, 30};
int *ptr;
ptr = a;
std::cout<<“Elements of array<<"n";
std::cout<<ptr[0]<<ptr[1]<<ptr[2];
return 0;
}
Output
Elements of array
10
20
30
#include<iostream>
int main( )
{
int a[3] = {10, 20, 30};
int *ptr;
ptr = a;
std::cout<<*ptr<<"n";
std::cout<<ptr<<"n";
std::cout<<*ptr++<<"n";
std::cout<<*ptr<<"n";
std::cout<<*(++ptr)<<"n";
return 0;
}
Output
10
0x7fff3d4a8d8c
10
20
30
REFERENCE VARIABLES
• Reference variable is an alias for an already defined variable.
• Both the variables refer to the same data object in the memory.
• A reference variable must be initialized using “&” operator during the
variable declaration as
data_type & reference_name = variable_name;
Output:
20 20
45 45
#include<iostream.h>
int main( )
{
int count = 20;
int &total = count;
cout <<count<< “/t” <<total ;
total = 45 ;
count << count << “/t” <<total ;
return 0;
}
Similarities between references and pointers
• Both references and pointers are used to change local variables of
one function inside another function.
• Both of them can be used to save copying objects when passed as
arguments to function.
ROLE OF THIS POINTER
• this is a keyword that refers to the current instance of the class.
• It can be used to pass current object as a parameter to another
method.
Purpose:
• As instance identity representation
• For differentiating data members from local variables.
• To pass current instance to external object
• To cast the current instance to different data type.
#include<iostream>
using namespace std;
class Test
{
private:
int x;
public:
void setX (int x)
{
this->x = x;
}
void print()
{
cout << "x = " << x << endl;
}
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
Output:
x = 20
STORAGE CLASSES
• A storage classes defines the lifetime and scope of the variables.
• Storage class specifiers tells the compiler where the objects are
declared and stored.
• A given object can have only one storage class.
• Storage classes are divided into four different classes.
The Automatic variable-auto storage class
• Local variables are variables declared within a function.
• Local variables are automatic by default.
• It is declared using the keyword ‘auto’.
• By default all local variables are auto so no need to explicitly add
keyword before variable.
void fn()
{
int x;
auto int y;
}
The register storage class
• The register storage class is used to define the local variables in a
register instead of memory (RAM).
• As it does not have a memory location ‘&’ operator cannot be applied
to it.
• It can be declared as
register int x;
• This tells the compiler to access the variable as fast as possible
The static storage class
• Static storage class instructs the compiler that the local variable retain
their values throughout the lifetime of the program(i.e.,)
• They maintain their same values between function calls.
static int x = 20;
# include <iostream. h>
# include <conio.h>
void display ()
{
static int x = 10;
x = x + 10;
cent<<x<<“n”;
}
void main( )
{
display();
display();
}
Output:
20
30
The extern storage class
• The extern storage class is used to declare a global variable or
function in another file
• By giving a reference of a global variable that is visible to all the
program files.
extern void display( );
File 1: CPP
# include <iostream.h>
int x;
extern void display( );
int main( )
{
x = 10;
display( );
return 0;
}
//display function defined in file2. CPP is used
here
File 2.CPP
#include<iostream.h>
extern int x;
void display( )
{
// the variable x is defined in file 1. CPP is used
here.
cout<< “the value of x is” <<x;
}
FUNCTION AS ARGUMENTS
• Function can be passed as an argument using the following function
prototype
return type function_name (return type1 (*new function) (datatype1));
• Example
void function(void(*f)(int));
• Here the parameter ‘f’ will be a pointer to a function which takes a single
parameter of ‘int’ datatype with ‘void’ return type.
#include <iostream.h>
#include<conio.h>
void function(void(*f)(int));
void display(intx)
{
cout<<x <<endl;
}
void function (void (*f) (int))
{
for (int c = 0; c < 5; c++)
{
(*f)(c);
}
}
void main ( )
{
function (display);
}
Output
0
1
2
3
4
C++ & Data Structure - Unit - first.pptx

C++ & Data Structure - Unit - first.pptx

  • 1.
    II YEAR /III SEMESTER 20IT302 - C++ AND DATA STRUCTURES
  • 2.
    UNIT I OBJECT ORIENTEDPROGRAMMING FUNDAMENTALS 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
  • 3.
    UNIT II OBJECT ORIENTEDPROGRAMMING CONCEPTS String Handling – Copy Constructor - Polymorphism – compile time and run time polymorphisms – function overloading – operators overloading – dynamic memory allocation - Nested classes - Inheritance – virtual functions.
  • 4.
    UNIT-III C++ PROGRAMMING ADVANCEDFEATURES 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.
  • 5.
    UNIT-IV ADVANCED NON-LINEAR DATASTRUCTURES AVL trees – B-Trees – Red-Black trees – Splay trees - Binomial Heaps – Fibonacci Heaps – Disjoint Sets – Amortized Analysis – accounting method – potential method – aggregate analysis.
  • 6.
    UNIT V GRAPHS Representation ofGraphs – 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.
  • 7.
  • 8.
    Classes: • A classis a collection of objects that have identical properties, common behavior and shared relationship. • Classes are user defined data types. A class can hold both data and functions. • For example: Fruit, Animal etc
  • 9.
    Objects: • Object isa basic unit of Object Oriented Programming. • They are instances of class • Interacts by sending messages to one another. Object is a basic unit of Object Oriented Programming. • They are instances of class which interacts by sending messages to one another. • Example: Apple, orange, mango are the objects of class fruit.
  • 10.
    Data Abstraction, Encapsulation& Data Hiding Data Abstraction: • Data Abstraction refers to the process of representing essential features without including background details or explanations. EXAMPLE: Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the scree
  • 11.
    Data Encapsulation: • Thewrapping of data and functions into a single unit (class) is called data encapsulation. • Encapsulation is a method of combining the data(variables) and functions(methods) inside a class. • The data is not accessible to the outside world. • Only the member function wrapped in the class access it.
  • 12.
    Hiding of datafrom direct access by the program is called as Information hiding or Data hiding Data hiding is a method used in object oriented programming to hide information within computer code.
  • 13.
    Inheritance • Inheritance isthe process by which one object can acquire and use the properties of another object. • The existing class is known as base class or super class or parent class. • The new class is known as derived class or sub class or child class. • The derived class shares some of the properties of the base class. Therefore a code from a base class can be reused by a derived class.
  • 15.
  • 16.
    Polymorphism • The abilityof an operator and function to take multiple forms is known as Polymorphism. There are two types of polymorphism. Compile time polymorphism: Object is bound to the function call at the compile time. Run time polymorphism: Object is bound to the function call only at the run time.
  • 17.
    • Overloading isa part of polymorphism, where a function or operator is made and defined many times to perform different functions. • There are two types of overloading o Operator Overloading o Function Overloading
  • 18.
    OPERATOR OVERLOADING The operatoris overloaded to provide the special meaning to the user-defined data type. • Example: Overloading ‘+’ operator to perform addition and concatenation of two strings. FUNCTIONS OVERLOADING Function overloading means two or more function have same name, but differ in the number of arguments or data type of arguments. Example: int add(int); int add(int, int); int add(int, float);
  • 19.
    Dynamic binding &Message Passing Dynamic binding: ◦ Binding is the process of connecting one program to another. ◦ Dynamic Binding refers to the process of linking a procedure call to the procedure code that will be executed only at run time.
  • 20.
    Message Passing: ◦ Objectscommunicate with one another by sending and receiving information to each other ◦ A message for an object is request for execution of procedure. ◦ Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent.
  • 21.
  • 22.
    Applications of OOP •Real time system • Simulation and Modelling • User Interface Design • Object Oriented Databases • AI and Expert Systems • Neural Networks and Parallel Programming • Decision Support and Office Automation System • CAD/CAM systems etc.,
  • 24.
    HEADER FILE # include<iostream.h> - To use the input and output statements. # - Preprocessor include - Keyword io - Input and Output. stream - Sequence of bytes. .h - Header file. # include <conio.h> - To use the clrscr( ) and getch( ) statements. # include<math.h> - To use the mathematical functions (Sine or Cos etc.,)
  • 25.
    CLASS DEFINITION: class classname { Accessspecifier://Can be private,public or protected Data Declaration;//Variables used Access specifier: Member function declaration or definition; };
  • 26.
    MEMBER FUNCTIONS Member FunctionDeclaration: returntype functionname (datatype variablename); • Returntype – void or int • Function name – User Defined Name • Datatype – int • Variable name - User Defined Name Member Function definition: returntype functionname (datatype variablename) { ------- }
  • 27.
    Main Function: The main()function is the first function in your program that is executed when it begins executing int main ( ) { classname object; object.functionname ( ); return 0; }
  • 28.
    EXAMPLE # include <iostream.h> classdisplay { int a,b,c; public: void dis( ) { cin>>a>>b; c=a+b; cout<<c; } }; int main( ) { display d; d.dis( ); return 0; }
  • 29.
    DATA ABSTRACTION • Providesonly the necessary details • As the name suggests, abstraction is the “abstract form of anything”. • In programming language abstraction is implemented using Interface and abstract class, which represents abstract view of methods and proper- ties of class. Two types of abstraction. They are • Data abstraction • Function abstraction
  • 30.
    DATA ABSTRACTION • Datathat can be used without knowing how it is stored is called Data Abstraction. Example : int x, y; FUNCTION ABSTRACTION Functions that can be used without knowing its implementation details is called Function Abstraction. Ex: • <iostream.h> : cin, cout • <string.h> : strcat( ), strcpy( ), strcmp( ), strlen( );
  • 31.
    Abstraction using access specifiers •Members defined with a public access specifiers are accessible to all parts of the program. • Members defined with a private access specifiers are not accessible to code that uses the class. The private section hides the implementation from code that uses the type.
  • 32.
    DATA ENCAPSULATION • Bindsdata and functions together • Keeps the data safe from outside interface and misuse. • The data is not accessible to the outside world and only those functions, which are wrapped in the class are able to access it. • Encapsulation is implemented using private and protected access specifiers.
  • 33.
    • The processby which one object can acquire the properties of another object: • A. Encapsulation • B. Inheritance • C. Polymorphism
  • 34.
    • An objectthat has more than one form is referred to as: • A. Inheritance • B. Interface • C. Abstract class • D. Polymorphism
  • 35.
    Basics of C++Program Basic Console I/O Statements in C++ The output operator is <<. To output to the console, use cout << expression; cout << “Hello World n”; cout << “236.99”; The input operator is >>. To input values from keyboard, use cin >> variables; int a,b; cin>>a>>b;
  • 36.
    Comments A comment inC++ can be given in a same way as we give in C. /* —— */ is a multiline comment and // is a single line comment. For Example /* This is a multiline comment and can Span for multiline. This comment is similar to C */ // This is a single line comment
  • 37.
    C++ Tokens • Keywords •Identifiers • Constants • Operators
  • 38.
  • 39.
    Identifiers • An identifieris formed with a sequence of letters (including ‘_ ‘) and digits • Examples of valid variable names are myname, jj, name123 • Examples of invalid variables 12B Invalid variable name since its starts with a number. Basic pay Invalid variable name since it has a space ABC,1 Invalid variable name since , is a special character
  • 40.
    Constants • Constants referto values that do not change during the execution of the program. Ex- amples for constants are 1998 Integer constant 25.789 Floating point constant “Hello World” String constant ‘a’ Character constant
  • 41.
    Operators : : ()[], ->,., typeid, casts, ! (negation), ~ (bit-not) new, delete ++, , - (unary), *(unary), & (unary), sizeof *, /, % (modulus) - + <<, >> <, <=, >, >= = =, !=
  • 42.
    Data Types • Builtin Data types • User Defined Data types • Derived Data types
  • 43.
    Built in DataTypes • Signed integer int x,y; long int a; • Unsigned integer unsigned short a; unsigned long x; • Character type char x;
  • 44.
    • Floating pointtypes double m; float f; • Boolean type bool logic;
  • 45.
    User Defined DataTypes • Structures, Unions and Classes • A structure is a collection of one or more variables; the variables may belong to different types, grouped together under a single name for easy handling. struct point { int x; int y; }p1,p2;
  • 46.
    Union • A unionis a user defined data type that may hold (at different times) objects of different types and sizes union u1 { int i; float f; char c; }u;
  • 48.
    CLASS • A Classis a user defined data-type which has data members and member functions. • Data members are the data variables • Member functions are the functions used to manipulate behavior of the objects in a Class class class_name { access_specifier 1 : member 1; access_specifier 2 : member 2; --- };
  • 49.
    • Access specifiersmodifies the access rights for the member and it contains three keywords. They are •Private •Protected •Public • Private members -accessible only from within the same class.It cannot be accessed outside the class. • Protected members - accessible from members of their same class and also from members of their derived classes. • Public members are accessible from anywhere. • By default, all members of a class have private access for all its members.
  • 50.
    class Rectangle { int x,y; public : void area( ); void display( ); };
  • 51.
    OBJECT • Object isan instance of a class. Syntax: classname object; Employee e1, e2; Example e1.tax_calculation( );
  • 52.
  • 53.
    CONSTRUCTORS AND DESTRUCTORS •Constructor in C++ is a special method that is invoked automatically at the time of object creation. • The constructor are used for object initialization or memory allocation. • The destructor performs deallocation of memory or other clean_up for objects. • The constructor has the same name as the class name and it doesn’t return any type. • The destructor also defined same as constructor with ‘~’ in front. • The compiler calls the constructor whenever an object is created and destructors are called when a class object goes out of scope.
  • 54.
    #include <iostream> using namespacestd; class sample { public : int x; public : sample( ) { x = 1; cout<<x; } }; int main( ) { sample s; return 0; } Output: 1
  • 55.
    Destructor class sample { int x; public: ~ sample( ) { delete x : } };
  • 56.
    Limitations • Constructors anddestructors cannot have return type • Pointers and references cannot be used on constructors and destructors • Constructors and destructors cannot be declared static, const or volatile • Constructors cannot be declared with the keyword virtual.
  • 57.
    STATIC MEMBERS • StaticMember of a class can contain static member data and static member function. • It must be declared with the keyword static. Static Data Member: • A variable is a part of a class which is not a part of an object is called a static member. • When a data member is declared as static only one copy of the data is maintained for all objects of the class. • (i.e) All other objects must share that copy. • It is automatically initialized to 0, when the first object of the class is created. • It must be initialized always outside the class using scope resolution operator ‘: :’ along with the class name.
  • 58.
    Syntax: static data_type data_member; •static is a keyword of the predefined library
  • 59.
    #include <iostream> using namespacestd; class GfG { public: static int i; }; int GfG::i=10; int main() { GfG obj1; GfG obj2; cout << obj1.i<<" "<<obj2.i; return 0; Output: 10 10 }
  • 60.
    • Static Memberfunction: The static member functions are special functions used to access the static data members or other static member functions. It can be declared with the keyword static. A static function will be called using the class name followed by scope resolution operator class_name : : function_name( ); A static function is common to the entire class.
  • 61.
    #include <iostream> using namespacestd; class Note { static int num; public: static int func () { return num; } }; int Note :: num = 5; int main () { cout << " The value of the num is: " << Note:: func () << endl; return 0; } Output: The value of the num is: 5
  • 62.
    CONSTANT MEMBERS Constant DataMember • Data Members of a class can be declared as constant using the keyword ‘const’ in the member declaration. • They are not initialized during the declaration. • Constant data members can be initialized using the constructor. • Once initialized it cannot be changed Syntax: const datatype variable_name;
  • 63.
    #include <iostream> using namespacestd; int main () { const int num = 25; num = num + 10; return 0; } Output: Compiler Error
  • 64.
    CONSTANT MEMBER FUNCTION •A const is a constant member function of a class that never changes any class data members, and it also does not call any non-const function. • It is also known as the read-only function. • We can create a constant member function of a class by adding the const keyword after the name of the member function.
  • 65.
    SYNTAX: return_type mem_fun() const { } theconst keyword is used after the name of the member function to make it constant
  • 66.
    #include <iostream> using namespacestd; class Data { int val=25; public: int getValue() const { return val; } }; int main() { Data d; cout << d.getValue(); return 0; }
  • 67.
    MEMBER FUNCTIONS •Member functionsare the functions that are declared inside the class definition and works on the data members (variables) of the class •Member functions can be defined inside or outside of the class. •If the member function is defined inside the class definition it is called Inline function, which can be defined directly.
  • 68.
    Member function isdefined inside the class definition #include <iostream> using namespace std; class area { public: int x=5; public: void square() { cout<<x*x; } }; int main() { area a; a.square(); return 0; } Output : 25
  • 69.
    •If it isdeclared outside the class, it should be defined using the scope resolution operator : : along with class name and function name. •Here the function must be declared inside the class definition first, and then defined outside. •By default, all member functions and variables are private to that class
  • 70.
    #include <iostream> using namespacestd; class area { public: int x=5; public: void square(); }; void area::square() { cout<<x*x; } int main() { area a; a.square(); return 0; } Output : 25
  • 72.
    Friend Function • Afunction that is declared with a keyword friend is known as friend function. • Function can be declared as a friend in any number of classes. • The function defined elsewhere in the program. • Function definition doesn’t use either keyword friend or scope resolution operator. • Friend function although not a member function, it has full rights to access the private members of a class
  • 73.
    Declaration class class-name { public: ….. friend returntypefunctionname(); //friend function declaration };
  • 74.
    Output: Hai #include <iostream> usingnamespace std; class one { private: friend void func(); }; void func() { cout<<"Hai"; } int main() { func(); return 0; }
  • 75.
    Output: #include <iostream> using namespacestd; class one { private: void func(); }; void one::func() { cout<<"Hai"; } int main() { one x; x.func(); return 0; }
  • 76.
    • Friend Class: A friend class can access private and protected members of other class in which it is declared as friend. • It is useful to allow a particular class to access private members of other class. Syntax for implementing a friend class is: class ClassB; class ClassA { // ClassB is a friend class of ClassA friend class ClassB; ... .. ... }; class ClassB { ... .. ... };
  • 77.
    Characteristics: • It’s notin the scope of the class. • Since it is not in the scope of the class it can’t be called using object of that class. • It can be invoked like a normal function without help of any object. • It can be declared either in public or private part of the class.
  • 79.
    POINTERS • Pointer isa variable which stores the address of another variable. • It defines the location to get the value of a specific data variable instead of defining the actual data. Pointer declaration • Pointer declaration consists of datatype, * and a variable name. Syntax: Datatype * variablename;
  • 80.
    Example: int *p; char *p1; Initializationof Pointer Variable: • Pointer variable can be initialized by storing the address of another variable Syntax: pointervariable = &variablename;
  • 81.
  • 82.
    int a=10; int *b; b=&a; a=10 &a= address(a)=2000 int *b; b=&a; b=2000 &b=4000
  • 83.
    Example: int main( ) { int*ptr; int a = 10; ptr = &a; cout << “The value of ptr is” <<*ptr; } Output The value of ptr is 10
  • 84.
    Pointers Arithmetic • Onlyaddition and subtraction operation are allowed in pointers. • The increment and decrement operators can be used as either prefix or suffix of an expression. #include<iostream> int main( ) { int a[3] = {10, 20, 30}; int *ptr; ptr = a; std::cout<<“Elements of array<<"n"; std::cout<<ptr[0]<<ptr[1]<<ptr[2]; return 0; } Output Elements of array 10 20 30
  • 85.
    #include<iostream> int main( ) { inta[3] = {10, 20, 30}; int *ptr; ptr = a; std::cout<<*ptr<<"n"; std::cout<<ptr<<"n"; std::cout<<*ptr++<<"n"; std::cout<<*ptr<<"n"; std::cout<<*(++ptr)<<"n"; return 0; } Output 10 0x7fff3d4a8d8c 10 20 30
  • 87.
    REFERENCE VARIABLES • Referencevariable is an alias for an already defined variable. • Both the variables refer to the same data object in the memory. • A reference variable must be initialized using “&” operator during the variable declaration as data_type & reference_name = variable_name;
  • 88.
    Output: 20 20 45 45 #include<iostream.h> intmain( ) { int count = 20; int &total = count; cout <<count<< “/t” <<total ; total = 45 ; count << count << “/t” <<total ; return 0; }
  • 89.
    Similarities between referencesand pointers • Both references and pointers are used to change local variables of one function inside another function. • Both of them can be used to save copying objects when passed as arguments to function.
  • 91.
    ROLE OF THISPOINTER • this is a keyword that refers to the current instance of the class. • It can be used to pass current object as a parameter to another method. Purpose: • As instance identity representation • For differentiating data members from local variables. • To pass current instance to external object • To cast the current instance to different data type.
  • 92.
    #include<iostream> using namespace std; classTest { private: int x; public: void setX (int x) { this->x = x; } void print() { cout << "x = " << x << endl; } }; int main() { Test obj; int x = 20; obj.setX(x); obj.print(); return 0; } Output: x = 20
  • 94.
    STORAGE CLASSES • Astorage classes defines the lifetime and scope of the variables. • Storage class specifiers tells the compiler where the objects are declared and stored. • A given object can have only one storage class. • Storage classes are divided into four different classes.
  • 95.
    The Automatic variable-autostorage class • Local variables are variables declared within a function. • Local variables are automatic by default. • It is declared using the keyword ‘auto’. • By default all local variables are auto so no need to explicitly add keyword before variable. void fn() { int x; auto int y; }
  • 96.
    The register storageclass • The register storage class is used to define the local variables in a register instead of memory (RAM). • As it does not have a memory location ‘&’ operator cannot be applied to it. • It can be declared as register int x; • This tells the compiler to access the variable as fast as possible
  • 97.
    The static storageclass • Static storage class instructs the compiler that the local variable retain their values throughout the lifetime of the program(i.e.,) • They maintain their same values between function calls. static int x = 20;
  • 98.
    # include <iostream.h> # include <conio.h> void display () { static int x = 10; x = x + 10; cent<<x<<“n”; } void main( ) { display(); display(); } Output: 20 30
  • 99.
    The extern storageclass • The extern storage class is used to declare a global variable or function in another file • By giving a reference of a global variable that is visible to all the program files. extern void display( );
  • 100.
    File 1: CPP #include <iostream.h> int x; extern void display( ); int main( ) { x = 10; display( ); return 0; } //display function defined in file2. CPP is used here File 2.CPP #include<iostream.h> extern int x; void display( ) { // the variable x is defined in file 1. CPP is used here. cout<< “the value of x is” <<x; }
  • 102.
    FUNCTION AS ARGUMENTS •Function can be passed as an argument using the following function prototype return type function_name (return type1 (*new function) (datatype1)); • Example void function(void(*f)(int)); • Here the parameter ‘f’ will be a pointer to a function which takes a single parameter of ‘int’ datatype with ‘void’ return type.
  • 103.
    #include <iostream.h> #include<conio.h> void function(void(*f)(int)); voiddisplay(intx) { cout<<x <<endl; } void function (void (*f) (int)) { for (int c = 0; c < 5; c++) { (*f)(c); } } void main ( ) { function (display); } Output 0 1 2 3 4