0% found this document useful (0 votes)
13 views18 pages

Polymorphism: 4pillars - Poly, Encapsulation, Inheritance, Abstraction

The document discusses the four pillars of object-oriented programming: polymorphism, encapsulation, inheritance, and abstraction. It explains concepts such as compile-time and runtime polymorphism, pure virtual functions, abstract classes, and the differences between classes and structs. Additionally, it covers memory management in C++ including stack vs heap allocation, and the characteristics and types of constructors.

Uploaded by

Soham Kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views18 pages

Polymorphism: 4pillars - Poly, Encapsulation, Inheritance, Abstraction

The document discusses the four pillars of object-oriented programming: polymorphism, encapsulation, inheritance, and abstraction. It explains concepts such as compile-time and runtime polymorphism, pure virtual functions, abstract classes, and the differences between classes and structs. Additionally, it covers memory management in C++ including stack vs heap allocation, and the characteristics and types of constructors.

Uploaded by

Soham Kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

4Pillars – poly, encapsulation, inheritance, abstraction

(https://www.youtube.com/watch?v=1ONhXmQuWP8&t=40s&ab_channel=KeepOnCoding)

Polymorphism
1. Compile time (static/early)
a. Func/method overloading (type, no of args)
b. Operator overloading
c. Templates

2. Runtime (dynamic/late)
a. Method overriding (During inheritance)
i. Achieved using virtual functions
https://www.youtube.com/watch?
v=oIV2KchSyGQ&ab_channel=TheCherno
ii. https://www.geeksforgeeks.org/virtual-function-cpp/
#:~:text=Rules%20for%20Virtual%20Functions,type%20to
%20achieve%20runtime%20polymorphism.
iii. https://www.javatpoint.com/cpp-virtual-function

Ex. Parent class, Child class both have method show()


Parent* p = new Parent()
p -> show() //show of parent
Child* c = new Child()
c -> show() // show of child
Parent* pc = new Child()
pc -> show() //show of parent not child

Virtual functions let us do dynamic dispatch which compilers implement via v-


table. V-table contains a mapping for all the virtual functions of the base class
so we can map them to the correct overridden function during runtime.
Just write the keyword virtual in front of the base class function
Note: In cpp11+ new keyword ‘override’ which is not compulsory to be written
in front of the derived class overridden method but it makes the code readable
and also, editors can point of if you make spelling errors in method name.
Ex:
virtual string getName() { … }
string getName() override { … } //override keyword is optional

 Late binding (Runtime) is done in accordance with the content of pointer


(i.e. location pointed to by pointer)
 Early binding (Compile time) is done according to the type of pointer,
 By default, all the instance methods in Java are considered as the Virtual
function except final, static, and private methods as these methods can
be used to achieve polymorphism.

What is pure virtual function?


A pure virtual function is a virtual function that has no definition within the
class.

Let, shape is the base class while rectangle, square and circle are the
derived class. Since we are not providing any definition to the virtual
function, so it will automatically be converted into a pure virtual function.

https://www.javatpoint.com/virtual-function-vs-pure-virtual-function-in-cpp
https://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-
classes/

Characteristics of a pure virtual function - used for data


abstraction

o A pure virtual function is a "do nothing" function. Here "do nothing"


means that it just provides the template, and derived class
implements the function.
o It can be considered as an empty function means that the pure
virtual function does not have any definition relative to the base
class.
o Programmers need to redefine the pure virtual function in the
derived class as it has no definition in the base class.
o A class having pure virtual function cannot be used to create direct
objects of its own. It means that the class is containing any pure
virtual function then we cannot create the object of that class. This
type of class is known as an abstract class. (ptr can be of derived
class or base class but object should be of derived class only)
o Ex:

Base *bptr;
Derived obj_d
bptr = & obj_d

Syntax

There are two ways of creating a virtual function:

1. virtual void display() = 0;

2. virtual void display() {}


Pure Virtual Function
o A virtual function is not used for performing any task. It only serves
as a placeholder.
o When the function has no definition, such function is known as "do-
nothing" function.
o The "do-nothing" function is known as a pure virtual function. A
pure virtual function is a function declared in the base class that has
no definition relative to the base class.
o A class containing the pure virtual function cannot be used to
declare the objects of its own, such classes are known as abstract
base classes.
o The main objective of the base class is to provide the traits to the
derived classes and to create the base pointer used for achieving
the runtime polymorphism.

Abstract classes
https://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/

 A class is abstract if it has at least one pure virtual function .


 If we do not override the pure virtual function in derived class, then
derived class also becomes abstract class.
 An abstract class can have constructors.
 We can have pointers and references of abstract class type.

Comparison with Java https://www.geeksforgeeks.org/abstract-classes-in-


java/
In Java, a class can be made abstract by using abstract keyword. Similarly a
function can be made pure virtual or abstract by using abstract keyword.
Following are some important observations about abstract
classes in Java.
1. An instance of an abstract class cannot be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract
method.
4. Abstract classes can not have final methods because
when you make a method final you can not override it
but the abstract methods are meant for overriding.
ie. Yes, there may be "final" methods in "abstract"
class. But, any "abstract" method in the class can't be
declared final. It will give "illegal combination of
modifiers: abstract and final" error.
5. We are not allowed to create object for any abstract
class.
6. We can define static methods in an abstract class

https://stackoverflow.com/questions/391483/what-is-the-difference-between-
an-abstract-method-and-a-virtual-method
 A virtual function provides a default implementation and it can exist on
either an abstract class or a non-abstract class.
 An abstract function has no implementation and it can only be declared
on an abstract class. This forces the derived class to provide an
implementation.
public abstract class myBase
{
//If you derive from this class you must implement this
method. notice we have no method body here either
public abstract void YouMustImplement();

//If you derive from this class you can change the behavior
but are not required to
public virtual void YouCanOverride()
{
}
}

public class MyBase


{
//This will not compile because you cannot have an
abstract method in a non-abstract class
public abstract void YouMustImplement();
}
Abstraction
Data Abstraction can be achieved in two ways:

o Abstraction using classes


o Abstraction in header files.

Abstraction using classes: An abstraction can be achieved using


classes. A class is used to group all the data members and member
functions into a single unit by using the access specifiers. A class has the
responsibility to determine which data member is to be visible outside and
which is not.

Abstraction in header files: An another type of abstraction is header


file. For example, pow() function available is used to calculate the power
of a number without actually knowing which algorithm function uses to
calculate the power. Thus, we can say that header files hides all the
implementation details from the user.

Access Specifiers Implement Abstraction:

o Public specifier: When the members are declared as public,


members can be accessed anywhere from the program.
o Private specifier: When the members are declared as private,
members can only be accessed only by the member functions of the
class.

https://www.geeksforgeeks.org/difference-between-abstraction-and-
encapsulation-in-c/
Static variable (not object
specific)
https://www.youtube.com/watch?v=qRCEdWQ0f4Q&ab_channel=Telusko

Example CEO of a company is the same for all employees, so you can make it
static so its not object specific it will be the same.
So, if you change the value of static var for one object it changes for all
Ex: Suppose 2 objects (obj1, obj2) and class (emp)
static String ceo;
obj1.ceo = “Rahul”

Print obj1.ceo //Rahul


Print obj2.ceo //Rahul
//can directly use class name instead of object name
Classname.ceo = “Nikita”

This means that you do not need to create objects for static variables as you
can directly use class name. Similarly for static methods.
So, in java public static void main() -> you do not need object to call this main
method
Now if you initialize static var in constructor every time an object is created the
static variable will be the assigned the value, but this is unnecessary so we
have a static block where you can directly initialize the static vars so it will be
executed only once.
Static
{
ceo = “larry”;
}

In simple words, initialization of:


 Non-static vars: constructor
 static vars: static block //executed when u load a class

 Static block -> executed first (C++ doesn’t support static blocks.)
 Cannot access non static members in static methods
 Static variables can be accessed by static and non static methods
 They cannot access this or super
 In the static method, the method use compile-time or early binding.
For this reason, we can access the static method without creating an
instance. In a non-static method, the method use runtime or dynamic
binding. So that we cannot access a non-static method without
creating an instance.
 In the static method, we cannot override a static method, because of
early binding.
Ex 1:
int x = 9;
Public static void main()
Print x //error-> cant

Ex 2:
Static int x = 9;
Public static void main()
Print x //prints 9

//cpp
https://www.geeksforgeeks.org/static-keyword-cpp/
Static vars must be initialized outside the class containing static vars and also
outside the non-static function like main
class GfG
{
public:
static int i; //if u try to make i=0 or anything here, gives
err

GfG(){ //do nothing }


};

int GfG::i = 1;
//if u don’t write this here but directly in main->gives error

int main()
{
GfG obj;
// prints value of i
cout << obj.i;
}
Class objects as static: Just like variables, objects also when declared as static
have a scope till the lifetime of program.
The object is declared inside the if block as non-static. So, the scope of variable
is inside the if block only. So when the object is created the constructor is
invoked and soon as the control of if block gets over the destructor is invoked
as the scope of object is inside the if block only where it is declared.
Inside Constructor
Inside Destructor
End of main
But if in main we declare the object static then flow is
Inside Constructor
End of main
Inside Destructor

Static functions in a class: Just like the static data members or static variables
inside the class, static member functions also do not depend on object of class.
We are allowed to invoke a static member function using the object and the ‘.’
operator but it is recommended to invoke the static members using the class
name and the scope resolution operator.
Static member functions are allowed to access only the static data members or
other static member functions, they can not access the non-static data
members or member functions of the class.

class GfG
{
public:
static void printMsg()
{
cout<<"Welcome to GfG!";
}
};

int main()
{
GfG::printMsg();
}

Constructors
1. Special characteristics of Constructors:
2. They should be declared in the public section
3. They do not have any return type, not even void
4. They get automatically invoked when the objects are created
5. They cannot be inherited though derived class can call the base class
constructor
6. Like other functions, they can have default arguments
7. You cannot refer to their address
8. Constructors cannot be virtual

C++ offers four types of constructors. These are:

1. Do nothing constructor
2. Default constructor
3. Parameterized constructor
4. Copy constructor

C++ provides a special type of constructor which takes an object as an argument


and is used to copy values of data members of one object into another object. In this
case, copy constructors are used to declaring and initializing an object from another
object.

Example:
1. Calc C2(C1);
2. Calc C2 = C1;
A special case of hybrid inheritance : Multipath inheritance
A derived class with two base classes and these two base classes have one
common base class is called multipath inheritance. An ambiguity can arise in
this type of inheritance.
https://www.geeksforgeeks.org/inheritance-in-c/
In the above example, both ClassB & ClassC inherit ClassA, they both have
single copy of ClassA. However ClassD inherit both ClassB & ClassC, therefore
ClassD have two copies of ClassA, one from ClassB and another from ClassC.
If we need to access the data member a of ClassA through the object of ClassD,
we must specify the path from which a will be accessed, whether it is from
ClassB or ClassC, bco’z compiler can’t differentiate between two copies of
ClassA in ClassD.

1. Avoiding ambiguity using scope resolution operator

obj.ClassB::a = 10;
obj.ClassC::a = 100;
//a = base class 1; b, c derived from a; obj of d derived from b, c

2. Avoiding ambiguity using virtual base class


 Java doesn’t support multiple inheritances as it causes a diamond
problem
 https://www.geeksforgeeks.org/java-and-multiple-inheritance/
 Multiple inheritance is not supported by Java using classes, handling
the complexity that causes due to multiple inheritances is very
complex. It creates problems during various operations like casting,
constructor chaining, etc

Classes vs Structs
https://www.youtube.com/watch?v=ObIxxHy8yY8&ab_channel=SeanAllen

https://www.youtube.com/watch?v=fLgTtaqqJp0&t=4s&ab_channel=TheCherno

Classes: reference types (like google docs- shared and changes reflected)
 Have inheritance
 If copy is updated original class is also updated
 Default: private
 More complex
 Saved in heap memory

Structs: value types (like sending a copy of excel, doesn’t matter what the
other person changes in their excel copy, your copy is safe)
 A structure is a user-defined data type in C/C++. A structure creates a
data type that can be used to group items of possibly different types into a
single type.
 No inheritance
 Cleaner
 Copy created original one not changed
 Default: public
 Saved in stack memory

Why CPP has struct?


To maintain backward compatibility with C, since C doesn’t have classes.
In C++, the struct keyword is optional before in declaration of a variable. In C, it
is mandatory.
https://www.geeksforgeeks.org/structures-in-cpp/

How to access structure elements?


Structure members are accessed using dot (.) operator.
What is a structure pointer?
Like primitive types, we can have pointer to a structure. If we have a pointer to
structure, members are accessed using arrow ( -> ) operator instead of the dot
(.) operator.
What is an array of structures?
Like other primitive data types, we can create an array of structures.
Class
Struct

Stack memory vs Heap memory


The stack is the memory set aside as scratch space for a thread of execution.
When a function is called, a block is reserved on the top of the stack for local
variables and some bookkeeping data. When that function returns, the block
becomes unused and can be used the next time a function is called. The
stack is always reserved in a LIFO (last in first out) order; the most recently
reserved block is always the next block to be freed. This makes it really
simple to keep track of the stack; freeing a block from the stack is nothing
more than adjusting one pointer.

The heap is memory set aside for dynamic allocation. Unlike the stack,
there's no enforced pattern to the allocation and deallocation of blocks from
the heap; you can allocate a block at any time and free it at any time. This
makes it much more complex to keep track of which parts of the heap are
allocated or free at any given time; there are many custom heap allocators
available to tune heap performance for different usage patterns.

Each thread gets a stack, while there's typically only one heap for the
application (although it isn't uncommon to have multiple heaps for different
types of allocation).

To answer your questions directly:

To what extent are they controlled by the OS or language runtime?


The OS allocates the stack for each system-level thread when the thread is
created. Typically the OS is called by the language runtime to allocate the
heap for the application.

What is their scope?


The stack is attached to a thread, so when the thread exits the stack is
reclaimed. The heap is typically allocated at application startup by the
runtime, and is reclaimed when the application (technically process) exits.

What determines the size of each of them?


The size of the stack is set when a thread is created. The size of the heap is
set on application startup, but can grow as space is needed (the allocator
requests more memory from the operating system).

What makes one faster?


The stack is faster because the access pattern makes it trivial to allocate and
deallocate memory from it (a pointer/integer is simply incremented or
decremented), while the heap has much more complex bookkeeping involved
in an allocation or deallocation. Also, each byte in the stack tends to be
reused very frequently which means it tends to be mapped to the processor's
cache, making it very fast. Another performance hit for the heap is that the
heap, being mostly a global resource, typically has to be multi-threading safe,
i.e. each allocation and deallocation needs to be - typically - synchronized
with "all" other heap accesses in the program.
1. The stack is for static (fixed size) data

a. At compile time, the compiler reads the variable types used in


your code.

i. It allocates a fixed amount of memory for these variables.


ii. This size of this memory cannot grow.

b. The memory is contiguous (a single block), so access


is sometimes faster than the heap

c. An object placed on the stack that grows in memory during


runtime beyond the size of the stack causes a stack overflow
error
2. The heap is for dynamic (changing size) data

a. The amount of memory is limited only by the amount of empty


space available in RAM
i. The amount used can grow or shrink as needed at runtime

b. Since items are allocated on the heap by finding empty space


wherever it exists in RAM, data is not always in a contiguous
section, which sometimes makes access slower than the stack

c. Programmers manually put items on the stack with


the new keyword and MUST manually deallocate this memory when
they are finished using it.
i. Code that repeatedly allocates new memory without deallocating
it when it is no longer needed to a memory leak.

You might also like