0% found this document useful (0 votes)
15 views

Unit 5 Classesnobjects

unit 5 notes

Uploaded by

kshamatomer2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit 5 Classesnobjects

unit 5 notes

Uploaded by

kshamatomer2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Object Oriented System Design

(KCS-054)

Unit 5
Object and Classes in C++, polymorphism
Topic Covered
❑Basics of object and class in C++

❑Private and public members, static data and function members

❑Constructors and Types

❑Destructors

❑Operator overloading
Topic Covered
❑Type conversion

❑Inheritance: Concept of Inheritance, Access Modifiers

❑Types of inheritance: single, multiple with Example and multilevel, hierarchical, hybrid
with Example

❑Polymorphism: Pointers in C++, Implementing polymorphism

❑Pointers and Objects, this pointer

❑virtual function, pure virtual functions


Defining Classes

➢ Classes are the central feature of C++ that supports object-oriented


programming and are often called user-defined types.
➢ A Class holds its own data members and member functions, which can
be accessed and used by creating an instance of that class.
Defining Classes
• A class defines a blueprint for a data type.
• A class definition starts with the keyword class followed by the class name; and the class
body, enclosed by a pair of curly braces.
• A class definition must be followed either by a semicolon or a list of declarations.
• Example- A class for box is defined where attributes are length, breadth and height.
Defining Objects
• A class provides blueprints for objects, so basically an object is created from
a class.
• one can declare objects of a class with exactly the same sort of declaration
that we declare variables of basic types.
• Following statements declare two objects of class Box Box1, Box2
• Both of the objects Box1 and Box2 will have their own copy of data members.
Basic definitions(1)
Member function- it is a function that has its definition or its prototype
within the class definition like any other variable.
Class Access Modifiers- A class member can be defined as public,
private or protected. By default members would be assumed as private.
Class constructor and destructor-it is a special function in a class
that is called when a new object of the class is created. A destructor is
also a special function which is called when created object is deleted.
Copy constructor- it is a constructor which creates an object by
initializing it with an object of the same class, which has been created
previously.
Basic definitions(2)
Friend function- A friend function is permitted full access to private and
protected members of a class..
‘this’ pointer - Every object has a special pointer this which points to the object
itself.
Static members of class-Both data members and function members of a
class can be declared as static.
Access Modifiers in Class in c++
• main features of OOP language like C++ is data hiding.
• Data hiding refers to restricting access to data members of a class.
• This is to prevent other functions and classes from tampering with
the class data.
• It allows us to determine which class members are accessible to other
classes and functions or not.
• There are 3 modifiers in C++
-Private
-Public
-Protected
Public Access modifier

➢‘public’ keyword is used to


create public members (data and
functions).
➢They public members are
accessible from any part of the
program.
Private Access modifier

➢‘priavte’ keyword is used to


create private members (data
and functions).
➢private members can only be
accessed from within the class
➢However, friend classes and
friend functions can access
private members
Protected Access modifier

➢‘protected’ keyword is used to


create protected members (data
and functions).
➢private members can only be
accessed from within the class
➢protected members can be
accessed within the class and
from the derived class
Defining member functions
➢A member function of a class is a
function that has its definition or
its prototype within the class
definition like any other variable.
➢It operates on any object of the
class of which it is a member,
and has access to all the
members of a class for that
object.
➢Member functions can be defined
within the class definition or
separately using scope
resolution operator
Here, function is defined within class
definition
Defining member functions outside class
➢you can define the same function outside the class using the scope
resolution operator (::) as follows −
Static data members in a class
➢A data member of a class can be declared as static
➢A static data member has following properties:-
-It is initialized to zero when the first object of its class is created
-only one copy of that member is created for the entire class
-it is visible only within the class but its lifetime is entire program

➢ Type and scope of each static member variable must be defined


outside the class
➢ Because static data members are stored separately rather than part of
object
➢ They are known as class variables
Static data
member:
Example
program
Static Member functions
➢A member function that is declared static has following properties:-
- a static function can have access to only other static members
(functions or variables) declared in the same class.
- a static member function can be called using the class
name(instead of objects)

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 newderived1: public Derived1


{
statement(s); };

class newderived2: public Derived2


{
statement(s);
};
class A
{
Hybrid Inheritance // data members and member functions()
➢The process of combining more than one type }:
of Inheritance together while deriving class B: public A // single inheritance
subclasses in a program is called a Hybrid {
Inheritance. // data members and member
functions();
➢Hybrid in C++ follows following pattern -
};
Multiple Inheritance, Single Inheritance, and
class C
Hierarchical Inheritances are combined
{
together.
// data members and member
➢Hybrid Inheritance in C++ is process by which functions();
a sub class follows multiple types of };
inheritance while deriving properties from the class D: public B, public C // multiple
base or super class. inheritance
➢This is also known as Multipath Inheritance {
for the same reason. // data members and member
functions();
};
Polymorphism
• It simply means ‘one name multiple forms”
• The overloaded member functions are selected for invoking by
matching arguments both type and number.
• Information is known to compiler at compile time and so compiler is
able to select the appropriate function for a particular call at the
compile time itself.
• Functional overloading save the memory space, consistency and
readability.
▪ This example shows
Overloading functions
and polymorphism
▪ Three forms of function
‘area’ have been
defined
▪ Three function with
different arguments
and data type
Binding in C++
▪ Binding refers to process that is used for converting functions and
variables into machine language addresses.
▪ C++ supports two types of binding: static or early binding and dynamic or
late binding.

Static (Early) Binding:


▪ By default, matching of function call with correct function definition happens at
compile time.
▪ This is called static binding or early binding or compile-time binding.
▪ Static binding is achieved using function overloading and operator overloading.
▪ Even though there are two or more functions with same name, compiler uniquely
identifies each function depending on parameters passed to those functions
Late Binding
▪ C++ provides facility to specify that compiler should match function calls
with the correct definition at run time; this is called dynamic binding or
late binding or run-time binding.
▪ Dynamic binding is achieved using virtual functions, base class pointer
points to derived class object and Inheritance.
Virtual Functions
▪ It is a member function that is declared within a base class and is
redefined by derived class.
▪ To create a virtual function, precede functions declaration in base
class with keyword ‘virtual’.
▪ It signals compiler that we don’t want static linkage for this function.
▪ when a class containing virtual function is inherited, derived class
redefines virtual function to fit its own needs, definition creates a
specific method.
Rules for Virtual Functions
• Virtual functions must be members of some class.
• Virtual functions cannot be static members.
• They are accessed through object pointers.
• They can be a friend of another class.
• A virtual function must be defined in the base class, even though it is not
used.
• The prototypes of a virtual function of the base class and all the derived
classes must be identical. If the two functions with the same name but
different prototypes, C++ will consider them as the overloaded functions.
• We cannot have a virtual constructor, but we can have a virtual destructor
class A
Virtual {
public:
Functions: void display()
Example { cout << "Base class is invoked"<<endl;

} };
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:-

Their addition should give:-


class complex
{ int a, b;
C++ addition public:
of complex void get_data(){
cout << "Enter the value of Complex Numbers a, b: "<<endl;
number cin >> a >> b;
}
complex operator+(complex ob)// overaloded operator function +
{ complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);}
complex operator-(complex ob)// overaloded operator function -
{ complex t;
t.a = a - ob.a;
t.b = b - ob.b;
return (t);}
void display(){
cout << a << "+" << b << "i" << endl;
}};
int main()
C++ addition {
complex obj1, obj2, result, result1;
of complex obj1.get_data();
number obj2.get_data();

result = obj1 + obj2;


result1 =obj1 - obj2;
cout << "Input Values:"<<endl;

obj1.display();
obj2.display();

cout << "Result:";


result.display();
result1.display();
return 0;
}
Operator Overloading of equal to (==) operator
class Time
{ int hour, mins, secs;
Example: C++
public:
program to check Time(){
if two clocks are hour=0, mins=0; secs=0;
showing the same }
time or not , The // parameterized constructor
Time(int h, int m, int s)
clock gives time in
{
hour, minutes and if(h>=0 && h <=23 && m >=0 && m <=59 && s >0 && s <=59)
seconds. { hour=h; mins=m; secs=s;}
else
cout << "Invalid format values would be 00:00:00" << endl;
}
bool operator == (const Time& t2)
{
return (hour == t2.hour && mins == t2.mins && secs == t2.secs);
}};
Pointer in C++
What is a pointer?
Pointer arithmetic etc.
What are pointers?
• In C++, a pointer refers to a variable that holds address of another
variable.
• Like regular variables, pointers have a data type.
• Example-a pointer of type integer can hold address of a variable of type
integer.
• A pointer of character type can hold address of a variable of character
type.
• It is a symbolic representation of a memory address.
• With pointers, programs can simulate call-by-reference.
• They can also create and manipulate dynamic data structures.
• It refers to a variable pointing to a specific address in a memory
pointed by another variable.
Pointer Declaration Syntax
Reference operator (&) and Deference
operator (*)
• reference operator (&) returns the variable’s address.
• dereference operator (*) helps us get the value that has been stored in a
memory address.
Pointer Arithmetic
• C++ allows a few arithmetic operations such as increment,
decrement, adding and subtracting a number from a pointer
• arithmetic operations on a number changes its value, likewise using
arithmetic operation on pointer changes address value.
Increment operation on pointers
let us consider that ptr is an integer pointer which points to the address
1000. Assuming 32-bit integers.

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’?

You might also like