WHAT IS OOPs ?
Object-Oriented Programming System (OOPs) is a programming concept that works
on the principles of abstraction, encapsulation, inheritance, and polymorphism. It
allows users to create objects they want and create methods to handle those objects.
NEED FOR OOPS
1. OOPs provides a clear modular structure for programs.
2. OOPs helps users to understand the software easily, although they don’t
know the actual implementation. (data abstraction)
3. Objects created for OOPs can be reused in other programs. Thus it saves
significant development cost.
4. Improved software maintainability: Since the design is modular, part of the
system can be updated in case of issues without a need to make large-scale
changes.
STRUCTURE vs CLASS
Features Structure Class
If no access specifier is
If no access specifier is defined,
Basic specified, all members are set to
all members are set to 'private'.
'public'.
Structure instance is called the
Instance A class instance is called 'object'.
'structure variable'.
Inheritance It does not support inheritance. It supports inheritance.
Memory is allocated on the
Memory Allocated Memory is allocated on the heap.
stack.
Nature Value Type Reference Type
Data abstraction and further
Purpose Grouping of data.
inheritance.
CLASS
The building block of C++ that leads to Object-Oriented programming is a Class. It
is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class
(i.e. object). A class is like a blueprint for an object.
OBJECT
An object refers to the instance of the class, which contains the instance of the
members and behaviors defined in the class template. In the real world, an object is
an actual entity to which a user interacts. So the objects consume space and have
some characteristic behavior. For example, a specific car.
Q.How much memory does a class occupy?
Ans. Classes do not consume any memory. They are just a blueprint based on
which objects are created. Now when objects are created, they actually initialize the
class members and methods and therefore consume memory.
ACCESS MODIFIERS
1. Private: A private member variable or function cannot be accessed, or even viewed
from outside the class.
But friend functions can access private members.
2. Protected: A protected member variable or function is very similar to a private
member but it provides one additional benefit that they can be accessed in child
classes which are called derived classes.
3. Public: A public member is accessible from anywhere outside the class but within a
program.
FRIEND CLASS
A friend class can access private and protected members of other class in which it
is declared as friend.
class Node {
private:
int key;
Node* next;
// Now class LinkedList can access private members of Node
friend class LinkedList;
};
FRIEND FUNCTION
Like friend class, a friend function can be given a special grant to access private
and protected members.
class Node {
private:
int key;
Node* next;
// Only search() of linkedList class can access internal members
friend int LinkedList::search();
};
CONSTRUCTOR
A constructor is a special type of member function of a class which is used to
initialize the data members of object of a class.
A constructor is different from normal functions in following ways:
1. Constructor has same name as the class itself
2. Constructors don’t have return type
3. It must be placed in public section of class.
4. A constructor is automatically called when an object is created.
TYPES OF CONSTRUCTORS
1. Default constructor: It is the constructor which doesn’t take any argument. It
has no parameters.
2. Parameterized constructor: The constructors that take some arguments are
known as parameterized constructors.
3. Copy constructor: A copy constructor is a member function that initializes
an object using another object of the same class.
Note: Point p2=p1 is the same as Point p2(p1).
DEEP COPY vs SHALLOW COPY
Shallow Copy Deep Copy
● Shallow Copy stores the ● Deep copy stores copies of the
reference of the object. object’s value.
● Shallow Copy reflects changes ● Deep copy doesn’t reflect changes
made to the new/copied object in made to the new/copied object in
the original object. the original object.
● Shallow copy is faster. ● Deep copy is comparatively slower.
COPY CONSTRUCTOR vs ASSIGNMENT OPERATOR
Copy constructor is called when a new object is created from an existing object.
An assignment operator is called when an already initialized object is assigned a
new value from another existing object.
Test t1, t2;
t2 = t1; // calls assignment operator
Test t3 = t1; // calls copy constructor, same as "Test t3(t1);"
DESTRUCTOR
Destructor is an instance member function which is invoked automatically whenever
an object is going to destroy. Destructors have same name as the class preceded
by a tilde (~).
STATIC KEYWORD
Static keyword has different meanings when used with different types.
1. Static variables in a function : Even if the function is called multiple times,
space for the static variable is allocated only once and the value of variable in
the previous call gets carried through the next function call.
2. Static variables in a class : The static variables in a class are shared by the
objects. Also because of this reason static variables can not be initialized
using constructors.
3. Class objects as static : Just like variables, objects also when declared as
static have a scope till the lifetime of program.
4. Static functions in a class : Static member functions are allowed to access
only the static data members or other static member functions.
ABSTRACT CLASS
● It is a class that has at least one pure virtual function (i.e., a function that has no
definition). The classes inheriting the abstract class must provide a definition for the
pure virtual function; otherwise, the subclass would become an abstract class itself.
● Abstract class cannot be instantiated.
Consider an example of a Shape base class with sub-classes (Triangle and Rectangle)
that inherit the Shape class. Now, suppose we need a function to return the area of a
shape. The function will be declared in the Shape class; however, it cannot be defined
there as the formula for the area is different for each shape.
ABSTRACT CLASS vs INTERFACE
The main difference between the two is that, when an interface is implemented, the
subclass must define all its methods and provide its implementation. Whereas when an
abstract class is inherited, the subclass does not need to provide the definition of its
abstract method, until and unless the subclass is using it. Also, an abstract class can
contain abstract methods as well as non-abstract methods.
VIRTUAL FUNCTION vs PURE VIRTUAL FUNCTION
Virtual function Pure virtual function
● A pure virtual function is a member
● A virtual function is a member function of base class whose only
function of base class which declaration is provided in base class
can be redefined by derived and should be defined in derived
class. class otherwise derived class also
becomes abstract.
● Classes having virtual functions ● Base class containing pure virtual
are not abstract. function becomes abstract.
● Base class having virtual ● Base class having pure virtual
function can be instantiated i.e. function becomes abstract i.e. it
its object can be made. cannot be instantiated.
● Syntax :
virtual<func_type><func_name> ● Syntax :
() { virtual<func_type><func_name>() =
// code 0;
}
FINAL KEYWORD
Sometimes you don’t want to allow derived class to override the base class’ virtual
function. So, to prevent overriding of virtual function, we use final specifier.
class Base {
public:
virtual void myfun() final
{
cout << "myfun() in Base";
}
};
class Derived : public Base {
void myfun()
{
cout << "myfun() in Derived\n";
}
};
This code will show error.
final specifier in C++ can also be used to prevent inheritance of class / struct. If a
class or struct is marked as final then it becomes non inheritable and it cannot be
used as base class/struct.
class Base final {
};
class Derived : public Base {
};
This code will also show error.
THIS KEYWORD
‘this’ pointer refers to the current object.
Uses :
1) When local variable’s name is same as member’s name.
void setX (int x) {
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
NEW KEYWORD
In c++ new keyword is used to allocate the memory on the heap at execution time.
Allocated memory does not free by the compiler automatically need to free by the user. It
returns a pointer to the allocated memory.
Eg. int *arr = new int[10];
CONST KEYWORD
The const variable must be initialized at the time of declaration. It cannot be assigned a
value later anywhere in the program.
Eg. const int x = 7;
POLYMORPHISM
● The word polymorphism means having many forms. In OOPs, Polymorphism refers
to the process by which some code, data, method, or object behaves differently
under different circumstances.
● A real-life example of polymorphism, a person at the same time can have
different characteristics. Like a man at the same time is a father, a husband,
an employee. So the same person posses different behavior in different
situations.
In C++ polymorphism is mainly divided into two types:
1) Compile time polymorphism: also known as early binding and static binding.
This type of polymorphism is achieved by function overloading or operator
overloading.
1. Function overloading : When there are multiple functions with same name
but different parameters then these functions are said to be overloaded.
Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
2. Operator overloading : C++ also provide option to overload operators. For
example, we can make the operator (‘+’) for string class to concatenate two
strings. We know that this is the addition operator whose task is to add two
operands. So a single operator ‘+’ when placed between integer operands ,
adds them and when placed between string operands, concatenates them.
2) Runtime polymorphism: also known as dynamic binding or late binding. This
type of polymorphism is achieved by Function Overriding.
Function Overriding : It occurs when a derived (child) class has a definition for
one of the member functions of the base class. That base function is said to
be overridden.
VIRTUAL CLASS
The virtual base class is used when a derived class has multiple copies of the base class.
class A {
public:
void show() {
cout << "Hello form A \n";
}
};
class B : public A {
};
class C : public A {
};
class D : public B, public C {
};
int main() {
D object;
object.show(); // error
}
In the above example, both B & C inherit A, they both have a single copy of A. However, D
inherits both B & C, therefore D have two copies of A, one from B and another from C.
The above code will generate error, as compiler can't differentiate between two copies of
A in D. To remove multiple copies of A from D, we must inherit A in B and C as virtual
class.
class A {
public:
void show() {
cout << "Hello from A \n";
}
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main() {
D object;
object.show(); // Now, D have only one copy of A
}
INHERITANCE*
● The capability of a class to derive properties and characteristics from another
class is called Inheritance.
● The class that inherits properties from another class is called Sub class or
Derived Class.
● The class whose properties are inherited by sub class is called Base Class or
Super class.
Use of Inheritance :
1. For Method Overriding (so runtime polymorphism can be achieved).
2. For Code Reusability.
Real life example : **Refer to last page for figure**
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Modes of Inheritance :
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A { // 'private' is default for classes
// x is private
// y is private
// z is not accessible from D
};
TYPES OF INHERITANCE
1. Single Inheritance: one derived class inherits from only one base class.
Example -
class Derived : public Base {
};
2. Multiple Inheritance: a single derived class may inherit from two or
more than two base classes. Example -
class Derived : public Base1, public Base2 {
};
3. Multilevel Inheritance: a derived class is created from another derived
class.
4. Hierarchical Inheritance: multiple derived classes inherits from a
single base class.
5. Hybrid (Virtual) Inheritance: It is implemented by combining more than
one type of inheritance.
ENCAPSULATION
Encapsulation is the process of binding data members and methods of a program
together to do a specific job, without revealing unnecessary details. Encapsulation
is a way to implement Abstraction.
Real life example : The automatic cola vending machine is a class. It contains both
data i.e. Cola cans and operations i.e. service mechanism and they are
wrapped/integrated under a single unit Cola Vending Machine. This is
called Encapsulation.
class EncapsulationExample
{
private:
// data hidden from outside world
int x;
public:
// function to set value of
// variable x
void set(int a)
{
x = a;
}
// function to return value of
// variable x
int get()
{
return x;
}
};
ABSTRACTION
An abstraction is a way of hiding the implementation details and showing only the
functionality to the users. In other words, it ignores the irrelevant details and shows
only the required one.
Real life example - Consider a real life example of a man driving a car. The man
only knows that pressing the accelerators will increase the speed of car or applying
brakes will stop the car but he does not know about how on pressing accelerator
the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car.
How to achieve :
1. Using Classes: Class helps us to group data members and member functions
using available access specifiers. A Class can decide which data member will
be visible to outside world and which is not.
2. Using Header files: consider the pow() method present in math.h header file.
EXCEPTION HANDLING
An exception is a problem/error that arises during the execution of a program. Exception
Handling in C++ is a process to handle runtime errors. We perform exception
handling so the normal flow of the application can be maintained even after runtime
errors.
C++ exception handling is built upon three keywords: try, catch, and throw.
try: represents a block of code that can throw an exception.
catch: represents a block of code that is executed when a particular
exception is thrown.
throw: Used to throw an exception.
GARBAGE COLLECTION
All the objects which are created dynamically are allocated memory in the heap.
If we go on creating objects we might get Out Of Memory error. So we need to
clear heap memory by releasing memory for all those objects which are no
longer referenced by the program (or the unreachable objects) so that the space
is made available for subsequent new objects. This memory can be released by
the programmer itself but it seems to be an overhead for the programmer, here
garbage collection comes to our rescue, and it automatically releases the heap
memory for all the unreferenced objects.+
Diagram of real life example of Inheritance