Unit 5 Classesnobjects
Unit 5 Classesnobjects
(KCS-054)
Unit 5
Object and Classes in C++, polymorphism
Topic Covered
❑Basics of object and class in C++
❑Destructors
❑Operator overloading
Topic Covered
❑Type conversion
❑Types of inheritance: single, multiple with Example and multilevel, hierarchical, hybrid
with Example
class name::function-name;
Friend function
➢A friend class can access private and protected members of other
class in which it is declared as friend.
➢A function can be declared friend in any number of classes
➢ It is sometimes useful to allow a particular class to access private
members of other class.
➢A friend function possesses:-
-it is not in the scope of the class to which it has been declared
as friend
-since it is not the scope of the class, it cannot be called using
object of that class
-it can be invoked like a normal function without the help of any
object
Friend function: syntax
Friend function: example program
Advantages of Friend Function
➢allows the programmer to generate more efficient codes.
➢It allows sharing of private class information by a non-member
function.
➢It accesses non-public members of a class easily.
➢It is widely used in cases when two or more classes contain the
interrelated members relative to other parts of the program.
➢It allows additional functionality that is not used by the class
commonly.
Review Questions
• What is class? How does it accomplice data hiding?
• What are objects? How are they created?
• How is member function of a class defined?
• When do we declare a member of a class static?
• Why do we need friend functions? Give an example of C++
code.
Constructor functions in c++ class
• It is a special ‘MEMBER FUNCTION’ having same name as that of its class
• It is used to initialize some valid values to data members of an object.
• It is executed automatically whenever an object of a class is created.
• only restriction that applies to constructor is that it must not have a return
type or void.
• constructor is automatically called by the compiler
Types of Constructors
• Default constructors- a constructor with no parameters.
• Copy constructors-
• Parametrized constructors-
Program on default Constructors
❑constructor for code below
is invoked as soon as the
object is created to
initialize its data members.
❑A constructor is executed
repeatedly whenever the
objects of a class are
created.
Parameterized Constructors
#include <iostream>
❑Unlike default constructors using namespace std;
which do not take any
parameters, it is however class myclass
possible to pass one or more {
arguments to a constructor. int a, b;
public:
❑A constructors that can take
arguments are known as myclass(int i, int j)
parameterized constructors. { a=i; b=j; }
void show()
{ cout<< a << " " << b; }
};
int main()
{ myclass ob(3, 5);
ob.show();
return 0;}
Copy Constructors
❑The copy constructor is used to
duplicate an existing object
when generating a new object.
In C++, it is a common method
of copying objects.
❑As an argument, it accepts a
reference to an object of the
same class.
When is copy constructor called in C++?
❑A copy constructor in C++ is a constructor that creates a new object using an
existing object of the same class and initializes each data member of a newly
created object with corresponding data members of the existing object passed
as argument.
❑Since it creates a copy of an existing object, so it is called copy constructor,
❑The copy constructor is used to duplicate an existing object when
generating a new object.
❑As an argument, it accepts a reference to an object of the same class.
Destructor function in C++
• Destructors have same class name preceded by (~) tilde symbol.
• It removes and destroys the memory of the object, which the
constructor allocated during the creation of an object.
Need for Destructor function
➢A destructor never takes any argument nor does it return any value.
➢It will be implicitly invoked by the compiler upon exit from the
program to clean up storage that is no longer accessible.
➢It is a good practice to declare destructors in a program since it
releases memory space for future use.
Inheritance
Single, Multiple, Multilevel
What is inheritance?
➢key concepts in Object-Oriented Programming language like C++, enabling
you to organize classes in a hierarchical form.
➢Just like a child inherits the characteristics of his parents and add specific
new attributes of his own.
➢With help of Inheritance, we use previously defined code
➢ in C++, a new class can inherit the existing class’s data members and
member functions and add members of its own. This process of creating a
new class from an existing class is known as Inheritance.
➢The existing class that is inherited is called the base class, and the new
class that inherits the functionality is called the derived class.
Illustrate Inheritance
Type of inheritance
Single Inheritance
➢Single inheritance is defined as the inheritance in which a derived
class is inherited from the only one base class.
Multilevel Inheritance
➢A class can also be derived from one
class, which is already derived from
another class.
Multiple Inheritance
➢A class can also be derived
from more than one base
class, using a comma-
separated list.
Hierarchical Inheritance Class Parent
➢A Hierarchical Inheritance in C++ refers to the {
type of inheritance that has a hierarchical statement(s); };
structure of classes. Class Derived1: public Parent
➢A single base class can have multiple derived {
classes, and other subclasses can further statement(s); };
inherit these derived classes, forming a Class Derived2: public Parent
hierarchy of classes. {
statement(s); };
} };
class B:public A
{ public:
void display() {
cout << "Derived Class is invoked"<<endl
;
} };
int main()
{ * a is the base class pointer
A* a; //pointer of base class and can only access base
B b; //object of derived class class members but not
a = &b; members of the derived
a->display(); //Late Binding occurs class
}
class A
{
public:
virtual void display()
Virtual { cout << "Base class is invoked"<<endl;
Functions: } };
Example class B:public A
using { public:
keyword void display() {
virtual cout << "Derived Class is invoked"<<endl;
} };
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Pure Virtual Functions
• It is not used for performing any task. It only serves as a placeholder.
• When function has no definition, such function is known as "do-
nothing" function.
• It is a function declared in base class that has no definition relative to
base class.
• A class containing pure virtual function cannot be used to declare
objects of its own, such classes are known as abstract base classes.
• main objective of base class is to provide traits to the derived classes
and to create the base pointer used for achieving the runtime
polymorphism.
Example :
Pure virtual
functions
When to use pure virtual functions?
• It is useful when we have a function that we want to put in base
class, but only derived classes know what it should return.
• This is because, base class can not be instantiated, and the
derived classes are forced to define these functions before
they can be instantiated.
• This helps ensure derived classes do not forget to redefine
functions that the base class was expecting them to.
• like normal virtual functions, pure virtual functions can be called
using a reference (or pointer) to a base class:
Operator Overloading
Overloading unary operator
Overloading binary operator
Operator Overloading?
• In C++, we can change the way operators work for user-defined types
like objects and structures. This is known as operator overloading.
• Since operator overloading allows us to change how operators work,
we can change the definition of ‘+’ or ‘-’ to add or substract two
objects.
• Operator overloading is a compile-time polymorphism.
• It is an idea of giving special meaning to an existing operator in C++
without changing its original meaning.
Why Operator Overloading?
Defining Operator Overloading
▪ To define an additional task to an operator, specify what it means in
relation to class to which operator is applied.
▪ This is done with help of a special function, called operator function.
▪ General form of an operator function is:-
Overloading
Unary Operator
increment
operator(++)
Overloading Binary Operator
• An operator which contains two operands to perform a
mathematical operation is called the Binary Operator Overloading.
• It is a polymorphic compile technique where a single operator can
perform various functionalities by taking two operands from the
programmer or user.
Addition of complex number
C++ Program to Add and subtract two complex numbers
using Binary Operator Overloading
Two complex number obj1 and obj2 are:-
obj1.display();
obj2.display();
ptr++
Pointer value will be now 1004
New_address=old_address+i*size(data type)
Addition/substraction on Pointers
For addition following rule is followed:-
new_address= current_address + (number * size_of(data type))
new_address= current_address -(number * size_of(data type))
Example: if a pointer address is 2000 and we add 4
p=p+4
Value of p after this operation will be 2016
p=p-4
Value of p after this operation will be 1984
Pointers to an Objects
• Pointers to objects aim to make a pointer that can access the
object, not the variables.
• Pointer to object in C++ refers to accessing an object.
• There are two approaches by which you can access an object.
-directly
-using a pointer to an object
Review Questions
• What is operator overloading?
• Why it is necessary to overload an operator?
• Name the operators that can not be overloaded in C++.
• Can a pointer of base class type point to an object of the derived
class? Explain.
• Why do we need virtual function?
• How is polymorphism achieved at (a) compile time (b) run time?
• Explain with an example, how would you create space for an array of
objects using pointers.
• When do we make a virtual function ‘pure’?