Object Oriented Programming notes provided

dummydoona 40 views 16 slides Dec 27, 2024
Slide 1
Slide 1 of 16
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16

About This Presentation

edc


Slide Content

OBJECT ORIENTED PROGRAMMING
●Object-Oriented Programmingis a methodologyor paradigm to design a
program usingclasses and objects. It simplifies thesoftware development
and maintenance byproviding some concepts definedbelow :
●Classis a user-defined data type which definesits properties and its
functions. Class is the only logical representationof the data. For
example, Humanbeing is a class. The body parts ofa human being are its
properties, and the actionsperformed by the bodyparts are known as
functions. The class does not occupy anymemory spacetill the time an
object is instantiated.
C++ Syntax(for class) :
classstudent{
public:
intid;// data member
intmobile;
string name;
intadd(intx,inty){// member functions
returnx + y;
}
};
●Objectis a run-time entity. It is an instanceof the class. An object can
represent a person, place or any other item. An objectcan operate on
both datamembers and member functions.
C++ Syntax(for object):
student s =newstudent();
Note:When an object is createdusinga new keyword,then space is
allocated for thevariable in a heap, and the startingaddress is stored in
the stack memory. When anobject is createdwithouta new keyword,
then space is not allocated in the heapmemory, andthe object contains
the null value in the stack.
APNI KAKSHA

● Inheritance
Inheritance is a process in which one objectacquires all the properties and
behaviors of its parent object automatically. In sucha way, you canreuse,
extend ormodifythe attributes and behaviors whichare defined in other
classes.
InC++,theclasswhichinheritsthemembersofanotherclassiscalled
derivedclassandtheclasswhosemembersareinheritediscalledbaseclass.
The derived class is thespecialized class for thebase class.
C++ Syntax:
class derived_class :: visibility-mode base_class;
visibility-modes= {private, protected, public}
Types of Inheritance :
1.Single inheritance:When one class inherits anotherclass, it is known
as singlelevel inheritance
2.Multiple inheritance:Multiple inheritance isthe process of deriving
a new classthat inherits the attributes from twoor more classes.
3.Hierarchical inheritance:Hierarchical inheritanceis defined as the
process ofderiving more than one class from a baseclass.
4.Multilevel inheritance:Multilevel inheritanceis a process of deriving a
class fromanother derived class.
5.Hybrid inheritance:Hybrid inheritance is a combinationof
simple, multipleinheritance and hierarchical inheritance.
●Encapsulation
Encapsulation is the process of combiningdata and functions into asingle
unit called class. In Encapsulation, the data is notaccessed directly; it is
accessedthrough the functions present inside theclass. In simpler words,
attributes of the classare kept private and publicgetter and setter methods
are provided to manipulate theseattributes. Thus,encapsulation makes the
concept of data hiding possible. (Data hiding:a languagefeature to restrict
access to members of an object, reducing the negativeeffect due to
dependencies. e.g. "protected", "private" featurein C++).
APNI KAKSHA

●Abstraction
We try to obtain anabstract view,model orstructure of a real lifeproblem,
and reduce its unnecessary details. With definitionof properties of
problems,including the data which are affected andthe operations which
are identified, the modelabstracted from problemscan be a standard
solution to this type of problems. It is anefficientway since there are
nebulous real-life problems that have similar properties.
Data binding:Data binding is a process of bindingthe application UI and
business logic.Any change made in the business logicwill reflect directly to the
application UI.
●Polymorphism
Polymorphism is the ability to present thesame interface for differing
underlying forms (data types). With polymorphism,each of these classes
will havedifferent underlying data. A point shapeneeds only two
coordinates (assuming it's in atwo-dimensional spaceof course). A circle
needs a center and radius. A square orrectangle needstwo coordinates for
the top left and bottom right corners and (possibly)arotation. An irregular
polygon needs a series of lines. Precisely, Poly means‘many’ andmorphism
means ‘forms’.
Types of PolymorphismIMP
1. Compile Time Polymorphism (Static)
2. Runtime Polymorphism (Dynamic)
Let’s understand them one by one :
●Compile Time Polymorphism:The polymorphism whichis implemented at
the compiletime is known as compile-time polymorphism.Example -
Method Overloading
APNI KAKSHA

Method Overloading: Method overloading is a technique which allows you
to have morethan one function with the same functionname but with
different functionality. Methodoverloading can bepossible on the
following basis:
1. The return type of the overloaded function.
2. The type of the parameters passed to the function.
3. The number of parameters passed to the function.
Example :
#include<bits/stdc++.h>
using namespacestd;
classAdd{
public:
intadd(inta,intb){
return(a + b);
}
intadd(inta,intb,intc){
return(a + b + c);
}
};
intmain(){
Add obj;
intres1,res2;
res1 = obj.add(2,3);
res2 = obj.add(2,3,4);
cout << res1 <<" "<< res2 << endl;
return0;
}
/*
Output : 5 9
add() is an overloaded function with a different numberof parameters. */
APNI KAKSHA

●Runtime Polymorphism:Runtime polymorphism is also known asdynamicpolymorphism.Function overriding is an example ofruntime
polymorphism. Functionoverriding means when the childclass contains
the method which is already present inthe parentclass. Hence,the child
class overrides the method of the parent class.Incase of function
overriding, parent and child classes both containthe same function witha
different definition. The call to the function isdetermined at runtime is
known asruntime polymorphism.
C++ Sample Code :
#include <bits/stdc++.h>
using namespacestd;
classBase_class{
public:
virtual voidshow(){
cout <<"Apni Kaksha base"<< endl;
}
};
classDerived_class:publicBase_class{
public:
voidshow(){
cout <<"Apni Kaksha derived"<< endl;
}
};
intmain(){
Base_class* b;
Derived_class d;
b = &d;
b->show();// prints the content of show() declaredin derived
classreturn0;
APNI KAKSHA

}
// Output : Apni Kaksha derived
●Constructor:Constructor is a special method whichis invoked automatically
at the timeof object creation. It is used to initializethe data members of
new objects generally. Theconstructor in C++ hasthe same name as class or
structure.
There can betwo typesof constructors in C++.
1.Default constructor:A constructor which has noargument is known
as defaultconstructor. It is invoked at the timeof creating an
object.
2.Parameterized constructor:Constructor which hasparameters is
called aparameterized constructor. It is used toprovide
different values to distinctobjects.
3.Copy Constructor:A Copy constructor is anoverloaded
constructor used todeclare and initialize an objectfrom another
object. It is of two types - defaultcopy constructorand user
defined copy constructor.
C++ Sample Code :
#include <bits/stdc++.h>
using namespacestd;
classgo{
public:
intx;
go(inta){// parameterized constructor.
APNI KAKSHA

x=a;
}
go(go &i){// copy constructor
x = i.x;
}
};
intmain(){
goa1(20);// Calling the parameterized constructor.
goa2(a1);// Calling the copy constructor.
cout << a2.x << endl;
return0;
}
// Output : 20
●Destructor:A destructor works opposite to constructor;it destructs theobjects ofclasses. It can be definedonly onceina class. Like constructors, it
is invokedautomatically. A destructor is definedlike a constructor. It must
have the same name asclass, prefixed with atildesign (~).
Example:
#include<bits/stdc++.h>
using namespacestd;
classA{
public:
// constructor and destructor are called automatically,
oncethe object is instantiated
A(){
cout <<"Constructor in use"<< endl;
}
~A(){
cout <<"Destructor in use"<< endl;
}
};
intmain(){
APNI KAKSHA

A a;
A b;
return0;
}
/*
Output: Constructor in use
Constructor in use
Destructor in use
Destructor in use
*/
●‘this’ Pointer:thisis a keyword that refers tothecurrent instance of the
class.Therecan be 3 main uses of ‘this’ keyword:
1. It can be usedto pass the current object as aparameter to
another method
2. It can be usedto refer to the current class instancevariable.
3. It can be usedto declare indexers.
C++ Syntax:
structnode{
intdata;
node *next;
node(intx){
this->data = x;
this->next =NULL;
}
}
●Friend Function:Friend function acts as a friendof the class.It can accessthe privateand protected members of the class.Thefriend function is not
APNI KAKSHA

a member of the class,but it must be listed in the class definition. The
non-member function cannot access theprivate dataof the class.
Sometimes, it is necessary for the non-member functiontoaccess the data.
The friend function is a non-member function and hasthe abilityto
access the private data of the class.
Note:
1. A friend function cannot access the private membersdirectly, it has
to use anobject name and dot operator with each membername.
2. Friend function uses objects as arguments.
ExampleIMP:
#include <bits/stdc++.h>
using namespacestd;
classA{
inta = 2;
intb = 4;
public:
// friend function
friend intmul(A k){
return(k.a * k.b);
}
};
intmain(){
A obj;
intres = mul(obj);
cout << res << endl;
return0;
}
// Output : 8
●Aggregation:It is a process in which one classdefines another class as
APNI KAKSHA

any entityreference.It is another way to reuse the class.It is a form of
association thatrepresents the HAS-A relationship.
●Virtual FunctionIMP:A virtual function is usedto replace the
implementationprovided by the base class. The replacementis always
called whenever the object inquestion is actuallyof the derived class, even
if the object is accessed by a base pointerratherthan a derived pointer.
1. A virtual function is a member function which ispresent in the
base classand redefined by the derived class.
2. When we use the same function name in both baseand derived
class,thefunction in base class is declared witha keyword
virtual.
3. When the function is made virtual, then C++ determinesat run-time
whichfunction is to be called based on the type ofthe object pointed
by the base class
pointer.Thus, by making the base class pointer topoint to
different objects,we can execute different versionsof the virtual
functions.
Key Points:
1.Virtual functions cannot be static.
2.A class may have a virtual destructor but it cannothave a virtual
constructor.
C++ Example:
#include <bits/stdc++.h>
APNI KAKSHA

using namespacestd;
classbase{
public:
// virtual function (re-defined in the derived class)
virtual voidprint(){
cout <<"print base class"<< endl;
}
voidshow(){
cout <<"show base class"<< endl;
}
};
classderived:publicbase {
public:
voidprint(){
cout <<"print derived class"<< endl;
}
voidshow(){
cout <<"show derived class"<< endl;
}
};
intmain(){
base* bptr;
derived d;
bptr = &d;
// virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
}
/*
output :
APNI KAKSHA

print derived class // (impact of virtual function)
show base class
*/
●Pure Virtual Function:
1. A pure virtual function is not used for performingany task. It only
serves as aplaceholder.
2. A pure virtual function is a function declaredin the base class
that has nodefinition relative to the base class.
3. A class containing the pure virtual function cannotbe used to declare
the objectsof its own, such classes are known asabstract base
classes.
4. The main objective of the base class is to providethe traits to the
derived classesand to create the base pointer usedfor achieving the
runtime polymorphism.
C++ Syntax:
virtual voiddisplay() = 0;
C++ Example :
#include<bits/stdc++.h>
using namespacestd;
classBase{
public:
virtual voidshow() = 0;
};
classDerived:publicBase {
public:
voidshow() {
cout <<"You can see me !"<< endl;
}
};
intmain(){
Base *bptr;
APNI KAKSHA

Derived d;
bptr = &d;
bptr->show();
return0;
}
// output : You can see me !
●Abstract Classes:In C++ class is made abstractby declaring at least one ofitsfunctions as apure virtual function.A pure virtualfunction is specified
by placing "= 0"in its declaration.Its implementationmust be provided
by derived classes.
Example :
#include<bits/stdc++.h>
using namespacestd;
// abstract class
classShape{
public:
virtual voiddraw()=0;
};
classRectangle:Shape{
public:
voiddraw(){
cout <<"Rectangle"<< endl;
}
};
classSquare:Shape{
public:
voiddraw(){
cout <<"Square"<< endl;
}
};
intmain(){
Rectangle rec;
Square sq;
APNI KAKSHA

rec.draw();
sq.draw();
return0;
}
/*
Output :
Rectangle
Square
*/
●Namespaces in C++:
1.The namespace is a logical division of the codewhich is designed to
stop thenaming conflict.
2. The namespace defines the scope where the identifierssuch as
variables, class,functions are declared.
3.The main purpose of using namespace in C++ is toremove the
ambiguity.Ambiguity occurs when a different taskoccurs with the
same name.
4. For example: if there are two functions with thesame name such as
add(). Inorder to prevent this ambiguity, the namespaceis used.
Functions are declared indifferent namespaces.
5. C++ consists of a standard namespace, i.e., stdwhich contains
inbuilt classesand functions. So, by using the statement"using
namespace std;" includes thenamespace "std" in ourprogram.
C++ Example:
#include <bits/stdc++.h>
using namespacestd;
// user-defined namespace
namespaceAdd {
inta = 5, b = 5;
intadd(){
return(a + b);
}
}
APNI KAKSHA

intmain(){
intres = Add :: add();// accessing the functioninside namespace
cout << res;
}
// output : 10
●Access SpecifiersIMP:The access specifiers areused to define how functions
andvariables can be accessed outside the class. Thereare three types of
access specifiers:
1.Private:Functions and variables declared as privatecan be accessed only
withinthe same class, and they cannot be accessedoutside the class they
aredeclared.
2.Public:Functions and variables declared under publiccan be accessed from
anywhere.
3.Protected:Functions and variables declared as protectedcannot be
accessedoutside the class except a child class. Thisspecifier is generally
used ininheritance.
Key Notes
●Deleteis used to release a unit of memory,delete[]is used to release an array.
●Virtual inheritancefacilitates you to create onlyone copy of each object
even if theobject appears more than one in the hierarchy.
●Functionoverloading:Functionoverloadingisdefinedaswecanhavemore
thanoneversionofthesamefunction.Theversionsofafunctionwillhave
different signaturesmeaning that they have a differentset of parameters.
APNI KAKSHA

Operator overloading:Operator overloading is defined as the standard
operator can beredefined so that it has a differentmeaning when applied to
the instances of a class.
●Overloadingis static Binding, whereas Overridingis dynamic Binding.
Overloading isnothing but the same method with differentarguments,
and it may or may not return thesame value in thesame class itself.
Overridingis the same method name with the same argumentsand
return typesassociated with the class and its childclass.
APNI KAKSHA
Tags