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.
STRING HANDLING
• Strings are objects that represent characters.
C++ provides two types of string
representations:
• The C - style character string
• The string class type introduced with standard C++.
• To use the string class, include the header file
as :
#include <string.h>
• String can be used in a similar way as built in
data types, by declaring a variable name (or)
string object.
string name ;
Member function Purpose
append ( ) a part of the string is appended to
another string.
find ( ) searches for the occurrence of a specified
substring
length ( ) length of a string isreturned.
replace ( ) replaces the specified characters within a
given string
size ( ) returns the size of the string
swap() swaps two strings
Operators in string handling
Operator Function Purpose
= Assign =
Ex : String S1;
String S2; S1 = S2;
assign one string to other string
+ Concatenate +
Ex : String S1 (“Sugu”);
String S2 (“maran”);
String S3 ;
S3 = S1 + S2; // Sugumaran
Concatenation of two strings
+= append + =
Ex : String S1 (“Ela”)
String S2 (“maran”) S1 + = S2 ;
// S1 = Elamaran
appends the specified string to
this character sequence
== Equity = =
Ex : String S1 (“abc”);
String S2 (“xyz”)
If (S1==S2)
Checks for equality of two
strings. Returns true if two
strings are equal
< lessthan<
flag = (S1 < S2);
returns true if S1 is less than S2
> greaterthan>
flag = (S1 > S2);
returns true if S1 is greater than
S2
The C - Style character string
• The C - Style character string is actually a one -
dimensional array of characters which is
terminated by a NULL character
#include<iostream>
using namespace std;
void main( )
{
char name [6] = {‘M’, ‘a’, ‘r’, ‘a’, ‘n’, ‘o’};
cout<<name ;
}
The String class in C++
The standard C++ library provides a string class type that
supports all the string operations.
#include<iostream>
#include<string.h>
using namespace std;
void main( )
{
string name = “Maran”;
cout<<name ;
}
Programs using string class to perform string functions
#include<iostream.h>
#include<string.h>
using namespace std;
int main( )
{
string S1 = “Kishore”;
string S2 = “Kumar”;
string S3 ;
int len;
S3 = S1;
cout<< “S3 : ” <<S3;
S3 = S1 + S2;
cout<< “S1 + S2 : ” <<S3;
len = S3.size( );
cout<<“S3.size( ) :”
<<len<<endl ;
return 0;
}
Output :
S3 : Kishore
S1 + S2 :Kishorekumar
S3.Size ( ) : 12
#include <iostream.h>
#include <string.h>
using namespace std;
int main( )
{
string str1 = “Delhi”;
string str2 = “Chennai”;
cout<< “str1 is :” << str1;
cout<< “str2 is :” << str2;
str1.swap(str2) ;
cout<< “str1 is : ” << str1;
cout<< “str2 is : ” << str2;
return 0;
}
Output :
str 1 is : Delhi
str 2 is :Chennai
str1 is : Chennai
str2 is : Delhi
Constructor
• A class constructor is a special member function
of a class that is executed whenever a new
objects of that class is created.
• The constructor has the same name as the class
and it doesn’t return any type.
• The constructor is used to initialize values to
object member after storage is allocated to the
object.
• Constructor is automatically called when object is
created
class sample
{
int x;
public :
sample( )
{
i=1;
cout<<x;
}
};
• Constructors can be defined either inside the
class definition or outside class definition
using class name and scope resolution
operator (: :).
class sample
{
int x;
public :
sample( );
};
sample::sample( )
{
x=1;
cout<<x;
}
Characteristics of Constructors
• Constructor name must be same as class name.
• They should be declared only in the public
section.
• They are invoked automatically when the objects
are created.
• They should not have any return type
• They cannot be inherited
• They cannot be used as a member of union or
structure.
• They can have default arguments.
• They can not be virtual.
• Constructors make use of “new” for allocating
memory and “delete” for releasing memory.
• They cannot refer to their addresses
#include<iostream>
class sample
{
int x;
public :
sample( )
{
i=1;
cout<<x;
}
};
int main()
{
sample s;
return 0;
}
Output:
1
Types of Constructor
• Default Constructor
• ParameterizedConstructor
• CopyConstructor
• DynamicConstructor
• Default Constructor
Default Constructor is the constructor
which doesn’t take any argument
• Parametrized Constructor
A constructor that receives arguments is
called parameterized constructor
• Dynamic Constructor
Dynamic Constructor is used to allocate
the memory to the objects at the run time using
new operator.
Copy Constructor
• A copy constructor is a member function that
initializes an object using another object of the
same class.
classname newobject (oldobject);
or
classname newobject = oldobject;
• Copy constructor is used to :
- Copy constructor is used to initialize the members
of a newly created object by copying the members
of an already existing object.
• Copy constructor takes a reference to an
object of the same class as an argument.
Sample(Sample &t)
{
id=t.id;
}
#include <iostream>
using namespace std;
A
{
public:
int x;
A(int a)
{
x=a;
}
A(A &i)
{
x = i.x;
}
};
int main()
{
A a1(20);
A a2=a1;
cout<<a2.x;
return 0;
}
O/P:
20
Polymorphism
• Polymorphism means the ability to take more than one form.
• It gives different meanings or functions to the operations or
methods.
A person is one object.
He behaves as an employee in office as well as the
father in the house and customer in departmental
store. So the concept is here one name many forms.
Type of polymorphism
Compile time Polymorphism Run-timePolymorphism
Operator
Overloading
Function
Overloading
Virtual
functions
Polymorphism
Compile time Polymorphism
• In the compile time polymorphism compiler
know which method is going to call at compile
time called compile-time or Static
polymorphism.
• Since the function call is determined during
compilation. It is also called as Early Binding or
Static Binding.
• Compile time polymorphism is achieved using
operator and function overloading.
FUNCTION OVERLOADING
• In function overloading, two or more
functions can have the same name but either
the number of arguments or data type can be
different.
• Function overloading means the same method
name but the type of parameter should be
different
• Functions differ
- In terms of data types of arguments
- In terms of number of arguments
Ex:
int Add(int x, int y);
int Add(int x, int y, int z);
float Add(int x,float y);
#include<iostream>
using namespace std;
void add(int i,int j)
{
cout<<"n"<<i+j;
}
void add(float i,float j)
{
cout<<"n"<<i+j;
}
int main()
{
int a=10,b=12;
float x=2.25,y=3.69;
add(a,b);
add(x,y);
return 0;
}
Output:
OPERATOR OVERLOADING
• Operator overloading is a compile-time
polymorphism
• Operator overloading is a concept of overloading
of existing operators, so that they can be used in
customized ways.
• Operator overloading is used to overload or
redefines most of the operators available in C++
• It is used to perform the operation on the user-
defined data type.
• The keyword “Operator” is used for overloading
of operators.
Syntax:
Return type operator symbol ([arguments])
{
statements ;
}
List of operators which can be overloaded
+ - * / % 
=
-
& = ( )
delete [ ]
& ~ ! ,
< > <= >= ++
<< >> = = != &&
+ = -= / = % = 
 * = <<= >>= [ ]
  * new new [ ] delete
List of operators which cannot be overloaded
• Scope operator (::)
• Sizeof
• member selector(.)
• member pointer selector(*)
• ternary operator(?:)
Limitations of Operator Overloading
• Assignment operator (=) and address operator
(&) need not to be overloaded, as these two
operators are already overloaded in
C++library.
• Operator overloading cannot change the
precedence and associativity of operators.
• Only order of evaluation can be changed if
parenthesis are used.
• Preprocessing symbols # and ## cannot be
overloaded.
class class_name
{
………………….
…………………..
public :
Return_type operator symbol (argument ())
{
……………….
……………….
}
………………………….
};
Rules for operator overloading
• Only built-in operators can be overloaded.
• Precedence and associativity of the operators
cannot be changed.
• Types of Operator Overloading
–Unary Operator Overloading
–Binary Operator Overloading
Unary Operator Overloading
• Operators which work on a single operand are
called unary operators.
• The unary operators operate an a single
operand with the user defined data types.
• Examples: Increment operators(++),
Decrement operators(–),unary minus
operator(-), Logical not operator(!) etc…
• #include<iostream>
using namespace std;
class sample
{
int a, b;
public:
void accept()
{
cin>>a;
cin>>b;
}
void operator-()
{
a=-a
b=-b
}
void display()
{
cout<<a;
cout<<b;
}
};
int main()
{
sample id;
id.accept();
-id;
id.display();
return 0;
}
o/p
A 10
B 20
A -10
B -20
Binary Operator Overloading
• Binary Operator overloading operates on two
operands with the user defined data types.
• Here, the first operand becomes the operator
overloaded function caller and the second is
passed as an argument.
syntax
return_type :: operator binary_operator_symbol (arg)
{
// function definition
}
#include<iostream.h>
#include<conio.h>
class complex
{
int a, b;
public:
void getvalue()
{
cout << "Enter the value of
Complex Numbers a,b:";
cin >> a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
}
void display()
{
cout << a << "+" << b << "i“;
}
};
void main()
{
complex obj1, obj2,
result;
obj1.getvalue();
obj2.getvalue();
result = obj1 + obj2;
cout << "Input Values:";
obj1.display();
obj2.display();
cout << "Result:";
result.display();
getch();
}
o/p
Enter the value of
Complex Numbers a, b
4 5
Enter the value of
Complex Numbers a, b
2 2
Input Values
4 + 5i
2 + 2i
Result
6 + 7i
DYNAMIC MEMORY ALLOCATION
• Dynamic memory allocation is the allocation and
ownership of memory for a certain data structure
during runtime. This makes data sizes to be
flexible and allows creation of objects
dynamically.
• Dynamic memory should be utilized through
pointers.
• New operator is used to dynamically allocate
memory
• Delete operator is used for dellocating the
previously allocated memory.
• Allocating space with new operator
• To allocate space dynamically, use the unary
operator new, followed by the type being
allocated.
new int; // dynamically allocates an int
new int [10]; // dynamically allocates an array
of 10 ints.
Syntax for declaring a new pointer
• Pointer_var = new Datatype;
• Pointer_var = new Datatype[number of
elements];
Deallocating space with Delete
Operator
• To dellocate memory that was created with
“new”, the unary operator “delete” is used.
int* ptr = new int; // dynamically created int
delete ptr ; // deletes the space that ptr points
To dellocate dynamic memory , the following
syntax is used
delete [ ] ptr;
#include<iostream.h>
#include<new.h>
int main( )
{
inti, n ;
int*ptr;
cout<< “Enter the toal no. of
elements” ;
cin>> n;
ptr = new int[n];
if (ptr = =NULL)
cout<< “Error message :
memory not alloted”;
else
{
for (i = 0; i<n; i++)
{
cout<< “Enter number : ”;
cin>>ptr[i];
}
cout<< “Entered elements are”;
for (i = 0; i< n; i++)
cout<<ptr[i] << “t” ;
delete[ ] ptr;
}
NESTED CLASSES
• Classes that are defined inside other classes
are called nested classes
• The surrounding class has no special privileges
towards the nested class, but the nested class
has full control over the accessibility of its
members by the surrounding class.
#include<iostream.h>
class outerclass
{
public :
class innerclass
{
private :
int s;
public :
void add(int a, int b)
{
s = a + b;
}
void display( )
{
cout<< “sum = ” << s ;
}
};
};
void main( )
{
Outerclass : : Innerclass obj;
Obj.add(10, 20);
Obj.display( );
}
Inheritance
• The capability of a class to derive properties
and characteristics from another class is
called Inheritance.
• The new class created from an existing class is
called derived class and the existing class is
called base class.
Types of Inheritance
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Derived class uses the colon ( : ) to extract the
features of base class.
Syntax
class derived_class : member access specifier base_class
{
-----
};
Member
Access specifier
Utilization of base class members in derived class
Private
Protected
Public
* Private members of the base class are inaccessible to the
derived class.
* Protected members of the base class become private
members of the derived class.
* Public members of the base class become private members
of the derived class.
* Private members of the base class are inaccessible to the
derived class.
* Protected members of the base class become protected
members of the derived class.
* Public members of the base class become protected
members of the derived class.
* Private members of the base class are inaccessible to the
derived class.
* Protected members of the base class become protected
members of the derived class.
* Protected members of the base class become public
members of the derived class.
Single Inheritance
• Single inheritance enables a derived class to
inherit properties and behaviour from a single
base class
• Single inheritance is defined as the
inheritance in which a derived class is
inherited from the only one base class.
Syntax
class derived_class :Access specifier base_class
{
---
};
#include<iostream>
using namespace std;
class base
{
public:
int a=1;
};
class derived:public base
{
public:
int p=50;
};
int main(void)
{
derived d1;
cout<<"base : a = "<<d1.a<<endl;
cout<<"derived : p ="<<d1.p;
return 0;
}
Output:
base : a = 1
derived : p =50
#include <iostream>
using namespace std;
class Account
{
public:
float salary = 60000;
};
class Programmer: public Account
{
public:
float bonus = 5000;
};
int main(void)
{
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
Output:
Salary : 60000
Bonus : 5000
Multiple Inheritance
• one derived class inherits from multiple base
classes.
Base Class 1
Base Class 2
Derived Class
class A
{
... .. ...
};
class B
{ ... .. ...
};
class C: public A,public B
{
... ... ...
};
#include<iostream>
using namespace std;
class A
{
public:
int a=1;
};
class B
{
public:
int b=2;
};
class Programmer:public A,public B
{
public:
int p=50;
};
int main(void)
{
Programmer p1;
cout<<"Class A : a = "<<p1.a<<endl;
cout<<"Class B: b= "<<p1.b<<endl;
return 0;
}
Output:
Class A : a = 1
Class B: b= 2
Multilevel Inheritance
• A class is derived from another derived class
Base Class
Derived Class 1
Derived Class 2
• Syntax
Class Base
{
______
______
______
};
Class derived1 :Access Specifier Base
{
____
____
____
};
Class derived2 :Access Specifier derived1
{
____
____
____
};
#include<iostream.h>
#include<conio.h>
class A
{
public :
int a;
void getdata( )
{
cin>>a;
}
};
class B : public A
{
public:
int b;
void square( )
{
b=a*a;
cout<<b;
}
};
class C: public B
{
public:
int c;
void cube( )
{
c=b*a;
cout<<cc;
}
};
void main( )
{
C ob;
ob.getdata();
ob.square();
ob.cube();
}
Hierarchical Inheritance
• Parent class is inherited by multiple
subclasses
Syntax
class base
{
_____
};
class derived1 :Access Specifier base
{
____
};
class derived2 :Access Specifier base
{
____
};
class derived3 :Access Specifier base
{
____
};
#include<iostream.h>
#include<conio.h>
class A
{
public:
int a;
void getdata( )
{
cin>>a;
}
};
class B: public A
{
public:
void square( )
{
cout<<(a*a);
}
};
Class C: public A
{
public:
void cube( )
{
cout<<(a*a*a);
}
};
void main( )
{
B b1;
b1.getdata();
b1.square();
C c1;
c1.getdata();
c1.cube();
}
Hybrid Inheritance
• combination of hierarchical and Multiple
Inheritance
A
B
C
D
Syntax
Class A
{
};
Class B :Access Specifier A
{
};
Class C :Access Specifier A
{
};
Class D :Access Specifier B, Access Specifier C
{
};
#include<iostream>
using namespace std;
class A
{
public:
int a=1;
};
class B : public A
{
public:
int b=2;
};
class C : public A
{
public:
int c=3;
};
class D:public B,public C
{
public:
int d=4;
};
int main( )
{
B b1;
cout<<b1.a<<endl;
C c1;
cout<<c1.a<<endl;
D d1;
cout<<d1.b<<endl;
cout<<d1.c<<endl;
return 0;
}
VIRTUAL FUNCTIONS
• A virtual function is a member function that is
declared within a base class and redefined by
a derived class.
• The keyword “virtual” precedes the function
declaration in the base class in order to create
the virtual functions.
• When a class containing virtual function is
inherited, the derived class redefines the
virtual function.
Syntax
Class B
{
virtual member function( )
{
--
}
}
class C : access specifier B
{
member function( )
{
---
}
}
class D : access specifier B
{
member function( )
{
---
}
}
Rules for virtual functions
• The virtual function must be member of base
class
• Virtual function is defined in the base class using
the keyword “virtual”.
• They are accessed by using object pointers.
• They cannot be static member.
• A virtual function can be friend function of
another class.
• Virtual function in base class must be defined
even though it is not used.
• Prototype of virtual function in base class &
derived class must be unique.
#include<iostream.h>
class B
{
public:
virtual void display()
{
cout<<“Content of base class”;
}
};
class D1 : public B
{
public:
void display( )
{ cout<<“Content of first derived class”;
}
};
class D2 : public B
{
public:
void display( )
{ cout<<“Content of second derivedclass”;
}
};
void main( )
{
B *b;
D1 d1;
D2 d2;
/* b->display(); // You cannot use this code here
because the function of base class is virtual.*/
b =&d1;
b->display(); /* calls display( ) of class
derived D1 */
b =&d2;
b->display(); /* calls display( ) of class
derived D2 */
}
Output
Content of first derived class.
Content of second derived class
Pure virtual functions
• A pure virtual function is a function declared
in a base class but has no definition
(i.e. virtual function with no body)
• A pure virtual function is the virtual function
whose declaration is assigned a value 0
• A pure virtual function simply acts as a place
holder that is meant to be redefined by
derived classes.
Syntax
class Base class
{
public :
virtual void func( ) = 0;
}

c++ UNIT II.pptx

  • 1.
    UNIT II OBJECTORIENTED 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.
  • 2.
    STRING HANDLING • Stringsare objects that represent characters. C++ provides two types of string representations: • The C - style character string • The string class type introduced with standard C++. • To use the string class, include the header file as : #include <string.h>
  • 3.
    • String canbe used in a similar way as built in data types, by declaring a variable name (or) string object. string name ;
  • 4.
    Member function Purpose append( ) a part of the string is appended to another string. find ( ) searches for the occurrence of a specified substring length ( ) length of a string isreturned. replace ( ) replaces the specified characters within a given string size ( ) returns the size of the string swap() swaps two strings
  • 5.
    Operators in stringhandling Operator Function Purpose = Assign = Ex : String S1; String S2; S1 = S2; assign one string to other string + Concatenate + Ex : String S1 (“Sugu”); String S2 (“maran”); String S3 ; S3 = S1 + S2; // Sugumaran Concatenation of two strings += append + = Ex : String S1 (“Ela”) String S2 (“maran”) S1 + = S2 ; // S1 = Elamaran appends the specified string to this character sequence
  • 6.
    == Equity == Ex : String S1 (“abc”); String S2 (“xyz”) If (S1==S2) Checks for equality of two strings. Returns true if two strings are equal < lessthan< flag = (S1 < S2); returns true if S1 is less than S2 > greaterthan> flag = (S1 > S2); returns true if S1 is greater than S2
  • 7.
    The C -Style character string • The C - Style character string is actually a one - dimensional array of characters which is terminated by a NULL character #include<iostream> using namespace std; void main( ) { char name [6] = {‘M’, ‘a’, ‘r’, ‘a’, ‘n’, ‘o’}; cout<<name ; }
  • 8.
    The String classin C++ The standard C++ library provides a string class type that supports all the string operations. #include<iostream> #include<string.h> using namespace std; void main( ) { string name = “Maran”; cout<<name ; }
  • 9.
    Programs using stringclass to perform string functions #include<iostream.h> #include<string.h> using namespace std; int main( ) { string S1 = “Kishore”; string S2 = “Kumar”; string S3 ; int len; S3 = S1; cout<< “S3 : ” <<S3; S3 = S1 + S2; cout<< “S1 + S2 : ” <<S3; len = S3.size( ); cout<<“S3.size( ) :” <<len<<endl ; return 0; } Output : S3 : Kishore S1 + S2 :Kishorekumar S3.Size ( ) : 12
  • 10.
    #include <iostream.h> #include <string.h> usingnamespace std; int main( ) { string str1 = “Delhi”; string str2 = “Chennai”; cout<< “str1 is :” << str1; cout<< “str2 is :” << str2; str1.swap(str2) ; cout<< “str1 is : ” << str1; cout<< “str2 is : ” << str2; return 0; } Output : str 1 is : Delhi str 2 is :Chennai str1 is : Chennai str2 is : Delhi
  • 11.
    Constructor • A classconstructor is a special member function of a class that is executed whenever a new objects of that class is created. • The constructor has the same name as the class and it doesn’t return any type. • The constructor is used to initialize values to object member after storage is allocated to the object. • Constructor is automatically called when object is created
  • 12.
    class sample { int x; public: sample( ) { i=1; cout<<x; } };
  • 13.
    • Constructors canbe defined either inside the class definition or outside class definition using class name and scope resolution operator (: :).
  • 14.
    class sample { int x; public: sample( ); }; sample::sample( ) { x=1; cout<<x; }
  • 15.
    Characteristics of Constructors •Constructor name must be same as class name. • They should be declared only in the public section. • They are invoked automatically when the objects are created. • They should not have any return type • They cannot be inherited
  • 16.
    • They cannotbe used as a member of union or structure. • They can have default arguments. • They can not be virtual. • Constructors make use of “new” for allocating memory and “delete” for releasing memory. • They cannot refer to their addresses
  • 17.
    #include<iostream> class sample { int x; public: sample( ) { i=1; cout<<x; } }; int main() { sample s; return 0; } Output: 1
  • 18.
    Types of Constructor •Default Constructor • ParameterizedConstructor • CopyConstructor • DynamicConstructor
  • 19.
    • Default Constructor DefaultConstructor is the constructor which doesn’t take any argument • Parametrized Constructor A constructor that receives arguments is called parameterized constructor • Dynamic Constructor Dynamic Constructor is used to allocate the memory to the objects at the run time using new operator.
  • 20.
    Copy Constructor • Acopy constructor is a member function that initializes an object using another object of the same class. classname newobject (oldobject); or classname newobject = oldobject; • Copy constructor is used to : - Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object.
  • 21.
    • Copy constructortakes a reference to an object of the same class as an argument. Sample(Sample &t) { id=t.id; }
  • 22.
    #include <iostream> using namespacestd; A { public: int x; A(int a) { x=a; } A(A &i) { x = i.x; } }; int main() { A a1(20); A a2=a1; cout<<a2.x; return 0; } O/P: 20
  • 23.
    Polymorphism • Polymorphism meansthe ability to take more than one form. • It gives different meanings or functions to the operations or methods. A person is one object. He behaves as an employee in office as well as the father in the house and customer in departmental store. So the concept is here one name many forms.
  • 24.
    Type of polymorphism Compiletime Polymorphism Run-timePolymorphism Operator Overloading Function Overloading Virtual functions Polymorphism
  • 25.
    Compile time Polymorphism •In the compile time polymorphism compiler know which method is going to call at compile time called compile-time or Static polymorphism. • Since the function call is determined during compilation. It is also called as Early Binding or Static Binding. • Compile time polymorphism is achieved using operator and function overloading.
  • 26.
    FUNCTION OVERLOADING • Infunction overloading, two or more functions can have the same name but either the number of arguments or data type can be different. • Function overloading means the same method name but the type of parameter should be different
  • 27.
    • Functions differ -In terms of data types of arguments - In terms of number of arguments Ex: int Add(int x, int y); int Add(int x, int y, int z); float Add(int x,float y);
  • 28.
    #include<iostream> using namespace std; voidadd(int i,int j) { cout<<"n"<<i+j; } void add(float i,float j) { cout<<"n"<<i+j; } int main() { int a=10,b=12; float x=2.25,y=3.69; add(a,b); add(x,y); return 0; } Output:
  • 29.
    OPERATOR OVERLOADING • Operatoroverloading is a compile-time polymorphism • Operator overloading is a concept of overloading of existing operators, so that they can be used in customized ways. • Operator overloading is used to overload or redefines most of the operators available in C++ • It is used to perform the operation on the user- defined data type. • The keyword “Operator” is used for overloading of operators.
  • 30.
    Syntax: Return type operatorsymbol ([arguments]) { statements ; }
  • 31.
    List of operatorswhich can be overloaded + - * / %  = - & = ( ) delete [ ] & ~ ! , < > <= >= ++ << >> = = != && + = -= / = % =   * = <<= >>= [ ]   * new new [ ] delete
  • 32.
    List of operatorswhich cannot be overloaded • Scope operator (::) • Sizeof • member selector(.) • member pointer selector(*) • ternary operator(?:)
  • 33.
    Limitations of OperatorOverloading • Assignment operator (=) and address operator (&) need not to be overloaded, as these two operators are already overloaded in C++library. • Operator overloading cannot change the precedence and associativity of operators. • Only order of evaluation can be changed if parenthesis are used. • Preprocessing symbols # and ## cannot be overloaded.
  • 34.
    class class_name { …………………. ………………….. public : Return_typeoperator symbol (argument ()) { ………………. ………………. } …………………………. };
  • 35.
    Rules for operatoroverloading • Only built-in operators can be overloaded. • Precedence and associativity of the operators cannot be changed.
  • 36.
    • Types ofOperator Overloading –Unary Operator Overloading –Binary Operator Overloading
  • 37.
    Unary Operator Overloading •Operators which work on a single operand are called unary operators. • The unary operators operate an a single operand with the user defined data types. • Examples: Increment operators(++), Decrement operators(–),unary minus operator(-), Logical not operator(!) etc…
  • 38.
    • #include<iostream> using namespacestd; class sample { int a, b; public: void accept() { cin>>a; cin>>b; } void operator-() { a=-a b=-b } void display() { cout<<a; cout<<b; } }; int main() { sample id; id.accept(); -id; id.display(); return 0; } o/p A 10 B 20 A -10 B -20
  • 39.
    Binary Operator Overloading •Binary Operator overloading operates on two operands with the user defined data types. • Here, the first operand becomes the operator overloaded function caller and the second is passed as an argument.
  • 40.
    syntax return_type :: operatorbinary_operator_symbol (arg) { // function definition }
  • 41.
    #include<iostream.h> #include<conio.h> class complex { int a,b; public: void getvalue() { cout << "Enter the value of Complex Numbers a,b:"; cin >> a>>b; } complex operator+(complex ob) { complex t; t.a = a + ob.a; t.b = b + ob.b; return (t); } void display() { cout << a << "+" << b << "i“; } };
  • 42.
    void main() { complex obj1,obj2, result; obj1.getvalue(); obj2.getvalue(); result = obj1 + obj2; cout << "Input Values:"; obj1.display(); obj2.display(); cout << "Result:"; result.display(); getch(); } o/p Enter the value of Complex Numbers a, b 4 5 Enter the value of Complex Numbers a, b 2 2 Input Values 4 + 5i 2 + 2i Result 6 + 7i
  • 43.
    DYNAMIC MEMORY ALLOCATION •Dynamic memory allocation is the allocation and ownership of memory for a certain data structure during runtime. This makes data sizes to be flexible and allows creation of objects dynamically. • Dynamic memory should be utilized through pointers. • New operator is used to dynamically allocate memory • Delete operator is used for dellocating the previously allocated memory.
  • 44.
    • Allocating spacewith new operator • To allocate space dynamically, use the unary operator new, followed by the type being allocated. new int; // dynamically allocates an int new int [10]; // dynamically allocates an array of 10 ints.
  • 45.
    Syntax for declaringa new pointer • Pointer_var = new Datatype; • Pointer_var = new Datatype[number of elements];
  • 46.
    Deallocating space withDelete Operator • To dellocate memory that was created with “new”, the unary operator “delete” is used. int* ptr = new int; // dynamically created int delete ptr ; // deletes the space that ptr points To dellocate dynamic memory , the following syntax is used delete [ ] ptr;
  • 47.
    #include<iostream.h> #include<new.h> int main( ) { inti,n ; int*ptr; cout<< “Enter the toal no. of elements” ; cin>> n; ptr = new int[n]; if (ptr = =NULL) cout<< “Error message : memory not alloted”; else { for (i = 0; i<n; i++) { cout<< “Enter number : ”; cin>>ptr[i]; } cout<< “Entered elements are”; for (i = 0; i< n; i++) cout<<ptr[i] << “t” ; delete[ ] ptr; }
  • 48.
    NESTED CLASSES • Classesthat are defined inside other classes are called nested classes • The surrounding class has no special privileges towards the nested class, but the nested class has full control over the accessibility of its members by the surrounding class.
  • 50.
    #include<iostream.h> class outerclass { public : classinnerclass { private : int s; public : void add(int a, int b) { s = a + b; } void display( ) { cout<< “sum = ” << s ; } }; }; void main( ) { Outerclass : : Innerclass obj; Obj.add(10, 20); Obj.display( ); }
  • 51.
    Inheritance • The capabilityof a class to derive properties and characteristics from another class is called Inheritance. • The new class created from an existing class is called derived class and the existing class is called base class.
  • 52.
    Types of Inheritance •Single Inheritance • Multiple Inheritance • Multilevel Inheritance • Hierarchical Inheritance • Hybrid Inheritance
  • 54.
    Derived class usesthe colon ( : ) to extract the features of base class. Syntax class derived_class : member access specifier base_class { ----- };
  • 56.
    Member Access specifier Utilization ofbase class members in derived class Private Protected Public * Private members of the base class are inaccessible to the derived class. * Protected members of the base class become private members of the derived class. * Public members of the base class become private members of the derived class. * Private members of the base class are inaccessible to the derived class. * Protected members of the base class become protected members of the derived class. * Public members of the base class become protected members of the derived class. * Private members of the base class are inaccessible to the derived class. * Protected members of the base class become protected members of the derived class. * Protected members of the base class become public members of the derived class.
  • 57.
    Single Inheritance • Singleinheritance enables a derived class to inherit properties and behaviour from a single base class
  • 58.
    • Single inheritanceis defined as the inheritance in which a derived class is inherited from the only one base class.
  • 59.
    Syntax class derived_class :Accessspecifier base_class { --- };
  • 60.
    #include<iostream> using namespace std; classbase { public: int a=1; }; class derived:public base { public: int p=50; }; int main(void) { derived d1; cout<<"base : a = "<<d1.a<<endl; cout<<"derived : p ="<<d1.p; return 0; } Output: base : a = 1 derived : p =50
  • 61.
    #include <iostream> using namespacestd; class Account { public: float salary = 60000; }; class Programmer: public Account { public: float bonus = 5000; }; int main(void) { Programmer p1; cout<<"Salary: "<<p1.salary<<endl; cout<<"Bonus: "<<p1.bonus<<endl; return 0; } Output: Salary : 60000 Bonus : 5000
  • 62.
    Multiple Inheritance • onederived class inherits from multiple base classes. Base Class 1 Base Class 2 Derived Class
  • 63.
    class A { ... ..... }; class B { ... .. ... }; class C: public A,public B { ... ... ... };
  • 64.
    #include<iostream> using namespace std; classA { public: int a=1; }; class B { public: int b=2; }; class Programmer:public A,public B { public: int p=50; }; int main(void) { Programmer p1; cout<<"Class A : a = "<<p1.a<<endl; cout<<"Class B: b= "<<p1.b<<endl; return 0; } Output: Class A : a = 1 Class B: b= 2
  • 65.
    Multilevel Inheritance • Aclass is derived from another derived class Base Class Derived Class 1 Derived Class 2
  • 66.
    • Syntax Class Base { ______ ______ ______ }; Classderived1 :Access Specifier Base { ____ ____ ____ }; Class derived2 :Access Specifier derived1 { ____ ____ ____ };
  • 67.
    #include<iostream.h> #include<conio.h> class A { public : inta; void getdata( ) { cin>>a; } }; class B : public A { public: int b; void square( ) { b=a*a; cout<<b; } }; class C: public B { public: int c; void cube( ) { c=b*a; cout<<cc; } }; void main( ) { C ob; ob.getdata(); ob.square(); ob.cube(); }
  • 68.
    Hierarchical Inheritance • Parentclass is inherited by multiple subclasses
  • 69.
    Syntax class base { _____ }; class derived1:Access Specifier base { ____ }; class derived2 :Access Specifier base { ____ }; class derived3 :Access Specifier base { ____ };
  • 70.
    #include<iostream.h> #include<conio.h> class A { public: int a; voidgetdata( ) { cin>>a; } }; class B: public A { public: void square( ) { cout<<(a*a); } };
  • 71.
    Class C: publicA { public: void cube( ) { cout<<(a*a*a); } }; void main( ) { B b1; b1.getdata(); b1.square(); C c1; c1.getdata(); c1.cube(); }
  • 72.
    Hybrid Inheritance • combinationof hierarchical and Multiple Inheritance A B C D
  • 73.
    Syntax Class A { }; Class B:Access Specifier A { }; Class C :Access Specifier A { }; Class D :Access Specifier B, Access Specifier C { };
  • 74.
    #include<iostream> using namespace std; classA { public: int a=1; }; class B : public A { public: int b=2; }; class C : public A { public: int c=3; }; class D:public B,public C { public: int d=4; }; int main( ) { B b1; cout<<b1.a<<endl; C c1; cout<<c1.a<<endl; D d1; cout<<d1.b<<endl; cout<<d1.c<<endl; return 0; }
  • 75.
    VIRTUAL FUNCTIONS • Avirtual function is a member function that is declared within a base class and redefined by a derived class. • The keyword “virtual” precedes the function declaration in the base class in order to create the virtual functions. • When a class containing virtual function is inherited, the derived class redefines the virtual function.
  • 76.
    Syntax Class B { virtual memberfunction( ) { -- } } class C : access specifier B { member function( ) { --- } } class D : access specifier B { member function( ) { --- } }
  • 77.
    Rules for virtualfunctions • The virtual function must be member of base class • Virtual function is defined in the base class using the keyword “virtual”. • They are accessed by using object pointers. • They cannot be static member. • A virtual function can be friend function of another class. • Virtual function in base class must be defined even though it is not used. • Prototype of virtual function in base class & derived class must be unique.
  • 78.
    #include<iostream.h> class B { public: virtual voiddisplay() { cout<<“Content of base class”; } }; class D1 : public B { public: void display( ) { cout<<“Content of first derived class”; } }; class D2 : public B { public: void display( ) { cout<<“Content of second derivedclass”; } }; void main( ) { B *b; D1 d1; D2 d2; /* b->display(); // You cannot use this code here because the function of base class is virtual.*/ b =&d1; b->display(); /* calls display( ) of class derived D1 */ b =&d2; b->display(); /* calls display( ) of class derived D2 */ }
  • 79.
    Output Content of firstderived class. Content of second derived class
  • 80.
    Pure virtual functions •A pure virtual function is a function declared in a base class but has no definition (i.e. virtual function with no body) • A pure virtual function is the virtual function whose declaration is assigned a value 0 • A pure virtual function simply acts as a place holder that is meant to be redefined by derived classes.
  • 81.
    Syntax class Base class { public: virtual void func( ) = 0; }