👨‍💻
Cracking-Interview
  • Data Structures and Algorithms
  • Arrays
    • 1. Two Sums
    • 2. Rotate Array
    • 3.Remove Duplicates from sorted array
    • 4.Merge Two Sorted Array
    • 5.Majority Element
    • 6.Rotate Image
    • 7.Merge Intervals
    • 8.Increasing Triplet Subsequence
    • 9.Set Matrix Zeroes
    • 10.Product of Array Except Self
    • 11.Container With Most Water
    • 12.Next Permutation
    • 13.Next Greater Element III
    • 14.Largest Number
    • 15.Candy
    • 16.Shortest Unsorted Continuous Subarray
    • 17.Sort Colors(Sort array of 0, 1, 2)
    • 18.Queue Reconstruction by Height
    • 19.Task Scheduler
    • 20.Trapping Rain Water
    • 21.Search a 2D Matrix II
    • 22. Spiral Matrix
    • 23.Median of Two Sorted Arrays
    • 24.Count inversion of an array
    • 25. Reverse Pairs
    • 26. Count Servers that Communicate
    • 27. 3Sum
    • 28. 4Sum
    • 29. Game of Life
    • 30. Sort the Matrix Diagonally
    • 31. Push Dominoes
    • 32. Corporate Flight Bookings
    • 33. Rotating the Box
    • 34. Interval List Intersections
    • 35. Insert Interval
    • 36. Minimum Moves to Equal Array Elements II
    • 37. Pairs of Songs With Total Durations Divisible by 60
    • 38. Remove Covered Intervals
    • Juggling Algorithm
    • Moore’s Voting Algorithm
    • Two Pointer Method
  • Linked List
    • 1.Odd-Even Linked List
    • 2.Add Two Numbers
    • 3. Insert in a Sorted List
    • 4.Rotate List
    • 5.Palindrome Linked List
    • 6.Point of insertion between two Linked List
    • 7.Delete Node in a Linked List
    • 8.Middle of the Linked List
    • 9.Linked List Cycle
    • 10. Swapping Nodes in a Linked List
    • 11.Swap Nodes in Pairs
    • 12.Merge Two Sorted Lists
    • 13.Reverse a Linked List
    • 14. Reverse Linked List II
    • 15.Copy List with Random Pointer
    • 16.Remove Duplicates from Sorted List
    • 17. Merge k Sorted Lists
    • 18. Remove Nth Node From End of List
    • 19. Sort List
    • 20. Reverse Nodes in k-Group
    • 21. Partition List
    • 22. Flattening a Linked List
    • Basic Implementation of Singly Linked List
    • Basic Implementation of Doubly Linked List
  • Strings
    • 1.Reverse Words in a String
    • 2. Is Subsequence
    • 3.Valid Anagram
    • 4.Add Binary
    • 5.Longest Common Prefix
    • 7.Valid Palindrome
    • 8.Implement strStr()
    • 9.String to Integer (atoi)
    • 10.Count and Say
    • 11.Longest Substring Without Repeating Characters
    • 12. Longest Substring with At Most K Distinct Characters
    • 13. Longest Substring with At Least K Repeating Characters
    • 14. Find All Anagrams in a String
    • 15. Permutation in String
    • 16. Maximum Number of Vowels in a Substring of Given Length
    • 17. Partition Labels
    • 18. Minimum Window Substring
    • 19. Compare Version Numbers
    • 20. Shortest Distance to a Character
    • 21. Count Number of Homogenous Substrings
    • 22. Remove Duplicate Letters
    • 23. Count Sorted Vowel Strings
    • 24. Get Equal Substrings Within Budget
    • 25. Sentence Similarity III
    • 26. Shifting Letters
    • 27. Longest Happy Prefix (imp)
    • 28. Sort Characters By Frequency
    • 29. String Compression
    • 30. Palindrome Pairs
    • 31. Shortest Palindrome(Imp)
    • 32. One Edit Distance
    • 33. Can Make Palindrome from Substring
    • 34. Greatest Common Divisor of Strings
    • KMP Algorithm for Pattern Searching
    • Rabin-Karp Algorithm for Pattern Searching
  • Binary Tree
    • Terminology and Formula
    • N-ary Tree
      • 1. N-ary Tree Preorder Traversal
      • 2. N-ary Tree Postorder Traversal
      • 3. N-ary Tree Level Order Traversal
    • Tree Traversals
      • 1.In-order Traversal
      • 2.Pre-order Traversal
      • 3.Post-order Traversal
      • 4.Level-order Traversal
      • 5.Vertical Order Traversal
      • 6. Binary Tree Level Order Traversal II
    • Problems Related to Binary Trees
      • 1.Maximum/Minimum Depth of Binary Tree
      • 2.Lowest Common Ancestor of a Binary Tree
      • 3.Symmetric Tree
      • 4.Path Sum
      • 5.Tree : Top View
      • 6. Diameter of Binary Tree
      • 7.Populating Next Right Pointers in Each Node
      • 8.Balanced Binary Tree
      • 9.Binary Tree Zigzag Level Order Traversal
      • 10.Invert Binary Tree
      • 11.Binary Tree Right Side View
      • 12.Validate Binary Tree Nodes
      • 13.Merge Two Binary Trees
      • 14.Flatten Binary Tree to Linked List
      • 15. Construct Binary Tree from Preorder and Inorder Traversal
      • 16. Construct Binary Tree from Inorder and Postorder Traversal
      • 17. Binary Tree Maximum Path Sum
      • 18. Sum Root to Leaf Numbers
      • 19. Subtree of Another Tree
      • 20. Even Odd Tree
      • 21. Delete Nodes And Return Forest
      • 22. Maximum Binary Tree
      • 23. Linked List in Binary Tree
      • 24. Longest Univalue Path
      • 25. Sum of Distances in Tree
      • 26. Distribute Coins in Binary Tree
      • 27. Find Duplicate Subtrees
      • 28. Serialize and Deserialize BST
      • 29. Serialize and Deserialize Binary Tree
      • 30. Path Sum III
      • 31. Delete Leaves With a Given Value
      • 32. All Possible Full Binary Trees
      • 33. All Nodes Distance K in Binary Tree
      • 34. Maximum Width of Binary Tree
  • Stack and Queue
    • Problems
      • 1.Min Stack
      • 2. Max Stack
      • 3.Valid Parentheses
      • 4.Evaluate Reverse Polish Notation
      • 5.Infix And Prefix and Postfix Conversions
      • 6.Next Greater Element I
      • 7.Next Greater Element II
      • 8.Sliding Window Maximum
      • 9.Gas Station (Circular Tour Problem)
      • 10.Daily Temperatures
      • 11.Decode String
      • 12. Largest Rectangle in Histogram
      • 13. Maximal Rectangle
      • 14. Minimum Remove to Make Valid Parentheses
      • 15. Map of Highest Peak
      • 16. Longest Valid Parentheses
      • 17. Online Stock Span
      • 18. Score of Parentheses
      • 19. Remove K Digits(imp)
      • 20. Design a Stack With Increment Operation
      • 21. Final Prices With a Special Discount in a Shop
      • 22. Valid Parenthesis String
      • 23. Reveal Cards In Increasing Order
      • 24. Remove All Adjacent Duplicates In String
      • 25. Number of Visible People in a Queue
      • 26.Number following a pattern
    • Implementation
      • Implementation of Queue
      • Implementation of Stack
      • Implementation of Circular Queue
      • Implement Queue using Stacks
      • Implement Stack using Queues
  • Hash Table
    • Designing and Definitions
      • Techniques of hashing and collision resolution
      • Design HashSet
      • Design HashMap
    • Problems
      • 1.Intersection of Two Arrays
      • 2.Happy Number
      • 3.Contains Duplicate
      • 4.Find the Duplicate Number
      • 5. Find All Duplicates in an Array
      • 6. Isomorphic Strings
      • 7. Group Anagrams
      • 8. Single Number
      • 9.Valid Sudoku
      • 10.Jewels and Stones
      • 11.First Missing Positive
      • 12. LRU Cache (V.IMP)
      • 13. Encode and Decode TinyURL
      • 14. Alphabet Board Path
  • Binary Search
    • Template I
      • Basic Binary Search
      • 1.Search in a Sorted Rotated Array
      • 5.Sqrt(x)
    • Template II
      • 2.Find Minimum in Rotated Sorted Array
    • Template III
      • 3.Find Peak Element
      • 4. Find First and Last Position of Element in Sorted Array
  • Binary Search Tree
    • 1.Is This a Binary Search Tree
    • 2.Search in a Binary Search Tree
    • 3.Insert into a Binary Search Tree
    • 4.Delete Node in a BST
    • 5.Lowest Common Ancestor of a Binary Search Tree
    • 6.Construct Binary Search Tree from Preorder Traversal
    • 7.Convert Sorted Array to Binary Search Tree
    • 8. Convert Sorted List to Binary Search Tree
    • 9.Kth Smallest Element in a BST
    • 10.Trim a Binary Search Tree
    • 11.Two Sum IV - Input is a BST
    • 12. Binary Search Tree to Greater Sum Tree / Greater Tree
    • 13. Balance a Binary Search Tree
    • 14. Binary Search Tree Iterator
    • 15. Unique Binary Search Trees
    • 16. Unique Binary Search Trees II
    • 17. Inorder Successor in BST
  • Bit manipulation
    • Bitwise Operations
    • 1.Reverse Bits
    • 2.Counting Bits
    • 3.Number of 1 Bits
    • 4.Hamming Distance
    • 5. Power of Two
    • 6. Complement of Base 10 Integer
  • Graph
    • 1.Maximum number of edges to be removed to contain exactly K connected components in the Graph
    • 2. Social Networking Graph
    • 3.The Flight Plan
    • 4.Is it a tree?
    • 5.Possible Bipartition
    • 6.Longest path in an undirected tree
    • 7.Keys and Rooms
    • 8.Is Graph Bipartite?
    • 9.Number of Islands
    • 10. Number of Provinces
    • 11.Surrounded Regions
    • 12. All Paths From Source to Target
    • 13.Word Ladder
    • 14.Rotting Oranges
    • 15.Course Schedule
    • 16.Course Schedule II
    • 17. Minimum Number of Vertices to Reach All Nodes
    • 18.Network Delay Time
    • 19. 01 Matrix
    • 20. Cheapest Flights Within K Stops
    • 21. Critical Connections in a Network
    • 22.Word Search
    • 23. Minimum Time to Collect All Apples in a Tree
    • 24. Time Needed to Inform All Employees
    • 25. As Far from Land as Possible
    • 26. Clone Graph
    • 27. Min Cost to Connect All Points
    • 28. Find the City With the Smallest Number of Neighbors at a Threshold Distance
    • 29. Number of Operations to Make Network Connected
    • 30. Open the Lock
    • 31. Word Search II
    • 32. Number of Ways to Arrive at Destination
    • 33. Knight On Chess Board
    • 34. Shortest Bridge
    • 35. Pacific Atlantic Water Flow
    • 36. Making A Large Island
    • 37. Path with Maximum Probability
    • Graph Algorithms
      • 1.DFS
      • 2.BFS
      • 3.Prim's MST
      • 4.Kruskal (MST)
      • 5.Dijkstra’s Algorithm(Single Source Shortest Path)
      • 6. Floyd Warshall's Algorithm(All Pair Sortest Path)
      • 7. Topological Sort
      • 8. Find if the given edge is a bridge in graph.
  • Disjoint Sets(Union-Find)
    • 1.Implementation of union find
    • 2.Social Network Community
    • 3. Graph Connectivity With Threshold
    • 4. Redundant Connection
    • 5. Smallest String With Swaps
    • 6. Accounts Merge
  • Heap and Priority Queue
    • Concepts of Heap
      • Building Max Heap
    • 1.Kth Largest Element in an Array
    • 2.Kth Largest Element in a Stream
    • 3.Top K Frequent Elements
    • 4.Kth Smallest Element in a Sorted Matrix
    • 5. Find Kth Largest XOR Coordinate Value
    • 6. Top K Frequent Words
    • 7. Find Median from Data Stream
    • 8. Maximum Average Pass Ratio
    • 9. Longest Happy String
    • 10. K Closest Points to Origin
    • 11. Reorganize String
    • 12. Find the Kth Largest Integer in the Array
    • 13. Smallest range in K lists
  • Trie
    • 1. Implement Trie (Prefix Tree)
    • 2. Replace Words
    • 3.Design Add and Search Words Data Structure
    • 4. Search Suggestions System
  • Dynamic Programming
    • 1.House Robber
    • 2.Climbing Stairs
    • 3.Longest Palindromic Substring
    • 4.Longest Palindromic Subsequence
    • 5.Best Time to Buy and Sell Stock
    • 6.Best Time to Buy and Sell Stock with Cooldown
    • 7.Unique Paths
    • 8.Minimum Path Sum
    • 9.Longest Increasing Subsequence
    • 10.Longest Common Subsequence
    • 11.Longest Consecutive Sequence
    • 12.Coin Change
    • 13.Coin Change 2
    • 14.Target Sum
    • 15.Partition Equal Subset Sum
    • 16. Last Stone Weight II
    • 17.Word Break
    • 18. Word Break II
    • 19.Burst Balloons
    • 20. Uncrossed Lines
    • 21. Wildcard Matching
    • 22. Maximal Square
    • 23. Perfect Squares
    • 24. Decode Ways
    • 25. Minimum Cost For Tickets
    • 26. Number of Dice Rolls With Target Sum
    • 27. Delete Operation for Two Strings
    • 28. Maximum Length of Repeated Subarray
    • 29. Longest String Chain
    • 30. Maximum Length of Pair Chain
    • 31. Minimum Falling Path Sum
    • 32. Predict the Winner
    • 33. Delete and Earn
    • 34. House Robber III
    • 35. Partition to K Equal Sum Subsets
    • 36. Different Ways to Add Parentheses
    • 37. Count Square Submatrices with All Ones
    • 38. 2 Keys Keyboard
    • 39. Palindrome Partitioning II
    • 40. Integer Break
    • 41.Cutting a Rod
    • 42. Number of Longest Increasing Subsequence
    • 43. Russian Doll Envelopes
    • 44. 0-1 Knapsack
    • 45. Interleaving String
    • 46. Edit Distance
    • 47. Minimum Insertion Steps to Make a String Palindrome
    • 48.Jump Game
    • 49. Shortest Common Supersequence
    • 50. Length of Longest Fibonacci Subsequence
    • 51. Maximum Alternating Subsequence Sum
    • 52. Palindromic Substrings
    • 53. Distinct Subsequences
    • 54. Best Team With No Conflicts
    • 55. Partition Array for Maximum Sum
    • 56. Ones and Zeroes
  • Greedy Algorithms
    • 1.Activity Selection
    • 2. N meetings in one room
    • 3.Minimum Platforms
    • 4. Car Pooling
    • 5. Maximum Population Year
    • 6.Meeting Rooms
    • 7. Equal Sum Arrays With Minimum Number of Operations
    • 8. Two City Scheduling
    • 9. Non-overlapping Intervals
    • 10. Minimum Number of Arrows to Burst Balloons
    • 11. Maximum Profit in Job Scheduling{IMP}
    • 12.Huffman Coding
    • 13. Minimum Cost Tree From Leaf Values
    • 14.Maximum Number of Events That Can Be Attended
    • 15. Video Stitching
    • 16. Minimum Number of Taps to Open to Water a Garden
  • Backtracking
    • 1.Subsets and Subset II
    • 2.Combinations
    • 3.Generate Parentheses
    • 4.Letter Combinations of a Phone Number
    • 5.Palindrome Partitioning
    • 6.Combination Sum and Combination Sum II
    • 7.Permutations
    • 8. Permutations II
    • 9. Letter Case Permutation
    • 10. Split a String Into the Max Number of Unique Substrings
    • 11. Path with Maximum Gold
    • 12. N-Queens
    • 13. N-Queens II
    • 14. Sudoku Solver
    • 15. Permutation Sequence
    • 16. Beautiful Arrangement
  • Sub Array and Sliding Window Problems
    • 1.Maximum Subarray Sum
    • 2.Maximum Product Subarray
    • 3.Maximum Sum Circular Subarray
    • 4. Maximum Absolute Sum of Any Subarray
    • 5. K-Concatenation Maximum Sum
    • 6.Subarray Sum Equals K
    • 7. Continuous Subarray Sum
    • 8. Contiguous Array
    • 9.Minimum Size Subarray Sum >=k (positive no)
    • 10. Max Subarray sum of positive no <= k
    • 11. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
    • 12. Maximum Subarray Sum with One Deletion
    • 13. Shortest Subarray with Sum at Least K (Negative Numbers)
    • 14. Frequency of the Most Frequent Element
    • 15. Count Number of Nice Subarrays
    • 16. Binary Subarrays With Sum
    • 17.Number of Substrings Containing All Three Characters
    • 18. Find Two Non-overlapping Sub-arrays Each With Target Sum
    • 19. Maximum Points You Can Obtain from Cards
    • 20. Longest Repeating Character Replacement
    • 21. Subarrays with K Different Integers
    • 22. Replace the Substring for Balanced String
    • 23. Maximize the Confusion of an Exam / Max Consecutive Ones III
    • 24. Subarray Sums Divisible by K
  • Design
    • 1. Design Twitter
    • 2. Design Browser History
    • 3. Snapshot Array
  • Maths
    • Formula
    • 1.Count Prime
    • 2.Pascal's Triangle
    • 3.Extra Long Factorials
    • 4.Factorial Trailing Zeroes
    • 5.Excel Sheet Column Number
    • 6.HCF and LCM
    • 7. Fizz Buzz
    • 8. Rearrange an array so that arr[i] becomes arr[arr[i]]
    • 9. XOR Queries of a Subarray
    • 10. Find second largest element
  • Sorting-Algorithms
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Selection Sort
    • Bubble Sort
    • Insertion Sort
  • Expected Interview MCQ and Questions c++
  • Concepts in C++
  • System Design Questions
  • 💾DBMS
    • Introduction
    • RBMS
    • JOINS
    • SQL
  • 🖥️OS
    • OS and Its Types
    • Process Concept and Threads
    • Process Synchronization
    • Deadlock in Operating System
    • Memory Management
    • Imp Questions of OS for Interviews
  • 🚙OOPS
    • Introduction and Definitions
  • 📨COMPUTER-NETWORKS
    • OSI | TCP IP Model
    • Topology
    • Network Devices
    • IP Address
Powered by GitBook
On this page
  • 1. Object-oriented programming
  • 2. Class:
  • 3 .Object:
  • 4. Main Characteristics of Oops
  • 1. Data Encapsulation
  • 2. Data Abstraction
  • 3. Inheritance
  • 4. Polymorphism:
  • 5. Dynamic Binding:
  • 6. Message Passing:
  • 5. Function Overriding
  • 6. Operator overloading
  • 7. Virtual Functions
  • 8. Abstract Class and Pure virtual function
  • 9. Difference Between Struct and Class
  • 10. Access Modifiers in C++
  • Modes of Inheritance
  • 11 . Types of Inheritance
  • Single Inheritance:
  • Multiple Inheritance:
  • Multilevel Inheritance:
  • Hierarchical Inheritance:
  • Hybrid (Virtual) Inheritance:
  • Java does not support multiple inheritance
  • 12. Static Binding and Dynamic Binding
  • 13. Friend Class and functions
  • 14. Why C++ and Java is partially Object Oriented Language?
  • 15. Copy Constructors
  • When is user-defined copy constructor needed?
  • 16. What is destructor?
  • 17. Dynamic Memory allocation in C++

Was this helpful?

  1. OOPS

Introduction and Definitions

PreviousImp Questions of OS for InterviewsNextOSI | TCP IP Model

Last updated 4 years ago

Was this helpful?

1. Object-oriented programming

The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

2. 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.

3 .Object:

An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. No memory is allocated for static variables No memory is allocated for member functions

4. Main Characteristics of Oops

Characteristics of an Object Oriented Programming language

The following are the major characteristics of Oop’s

Objects Classes Data Encapsulation Data Abstraction Inheritance Polymorphism

1. Data Encapsulation

Encapsulation is defined as wrapping up of data and information under a single unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulate them. We encapsulate data members as private and we provide getters and setter methods to access them Encapsulation also leads to data abstraction or hiding. As using encapsulation also hides the data.

2. Data Abstraction

Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.

  • Abstraction using Classes: We can implement Abstraction in C++ using classes. The 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 the outside world and which is not.

  • Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate the power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating the power of numbers.

3. Inheritance

The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.

  • Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.

  • Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.

  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

4. Polymorphism:

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.

In C++ polymorphism is mainly divided into two types:

  • Operator Overloading: The process of making an operator to exhibit different behaviours in different instances is known as operator overloading.

  • Function Overloading: Function overloading is using a single function name to perform different types of tasks. [Achieved during compile time]

  • Function Overriding: [Achieved at run time] Polymorphism is extensively used in implementing inheritance.

Example:

5. Dynamic Binding:

In dynamic binding, the code to be executed in response to function call is decided at runtime. C++ has virtual functions to support this.

6. Message Passing:

A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function and the information to be sent.

5. Function Overriding

It is the redefinition of base class function in its derived class with same signature i.e return type and parameters. When a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

  • It can only be done in derived class.

  • It is achieved using virtual functions

#include <bits/stdc++.h> 
using namespace std; 
  
class base 
{ 
public: 
    virtual void print () 
    { cout<< "print base class" <<endl; } 
   
    void show () 
    { cout<< "show base class" <<endl; } 
}; 
   
class derived:public base 
{ 
public: 
    void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly 
    { cout<< "print derived class" <<endl; } 
   
    void show () 
    { cout<< "show derived class" <<endl; } 
}; 
  
//main function 
int main()  
{ 
    base *bptr; 
    derived d; 
    bptr = &d; 
       
    //virtual function, binded at runtime (Runtime polymorphism) 
    bptr->print();  
       
    // Non-virtual function, binded at compile time 
    bptr->show();  
  
    return 0; 
}  

6. Operator overloading

C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. Adding additional task to the existing operator. + operators are designed to work on predefined data types: Class are user defined data types. If we want to add two objects it can be done with the help of operator overloading.

Example:-

class sum
{
public:
    int a, b;

    sum(int x, int y)
    {
        a = x;
        b = y;
    }

    void operator+(sum obj1)
    {
        a = obj1.a + a;
        b = obj1.b + b;
    }

    void get()
    {
        cout << a << " " << b << "\n";
    }
};

int main()
{
    sum s1 = sum(10, 15);
    sum s2 = sum(10, 15);
    s1 + s2;
    s1.get();
}

We cannot overload '.', ' :: ', ' .*', 'sizeof()' , '?'

7. Virtual Functions

A virtual function is a member function which is declared within a base class and is re-defined (Overridden) by a derived class.

When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

  • Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.

  • They are mainly used to achieve Runtime polymorphism

  • Functions are declared with a virtual keyword in base class.

  • The resolving of function call is done at Run-time.

8. Abstract Class and Pure virtual function

Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class. - A class is abstract if it has at least one pure virtual function. - A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. - If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.

// An abstract classclass
class Test
{
    // Data members of class

public:
    // Pure Virtual Function
    virtual void show() = 0;

    // Other members
};

9. Difference Between Struct and Class

The most important of them is security. A Structure is not secure and cannot hide its implementation details from the end user while a class is secure and can hide its programming and designing details. - Members of a class are private by default and members of a struct are public by default. - When deriving a struct default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.

10. Access Modifiers in C++

There are 3 types of access modifiers available in C++:

  1. Public

  2. Private

  3. Protected

If we do not specify any access modifiers for the members inside the class then by default the access modifier for the members will be Private.

  • Public: All the class members declared under the public specifier will be available to everyone. The data members and member functions declared as public can be accessed by other classes and functions too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.

  • Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.

  • Protected: Protected access modifier is similar to private access modifier in the sense that it can’t be accessed outside of it’s class unless with the help of friend class, the difference is that the class members declared as Protected can be accessed by any subclass(derived class) of that class as well.

Modes of Inheritance

  1. Public mode: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class.

  2. Protected mode: If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class.

  3. Private mode: If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class.

Note : The private members in the base class cannot be directly accessed in the derived class, while protected members can be directly accessed

11 . Types of Inheritance

Types of Inheritance in C++

Single Inheritance:

In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only.

Multiple Inheritance:

Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes.

Syntax:-

class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
  //body of subclass
};

Multilevel Inheritance:

Hierarchical Inheritance:

In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than one derived class is created from a single base class.

Hybrid (Virtual) Inheritance:

Java does not support multiple inheritance

12. Static Binding and Dynamic Binding

13. Friend Class and functions

Friend Class:- A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class

class Node { 
private: 
    int key; 
    Node* next; 
    /* Other members of Node Class */
  
    // Now class  LinkedList can 
    // access private members of Node 
    friend class LinkedList; 
}; 

Friend Function: Like friend class, a friend function can be given special grant to access private and protected members. A friend function can be: a) A method of another class b) A global function

class Node { 
private: 
    int key; 
    Node* next; 
  
    /* Other members of Node Class */
    friend int LinkedList::search(); 
    // Only search() of linkedList 
    // can access internal members 
}; 

Following are some important points about friend functions and classes: 1) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically. 2) Friendship is not inherited (In C++, friendship is not inherited. If a base class has a friend function, then the function doesn’t become a friend of the derived class) 3) The concept of friends is not there in Java.

14. Why C++ and Java is partially Object Oriented Language?

  1. Main function is outside the class : C++ supports object-oriented programming, but OO is not intrinsic to the language.

  2. Concept of Global variable : In C++, we can declare a variable globally, which can be accessible from anywhere and hence, it does not provides complete privacy to the data as no one can be restricted to access and modify those data and so, it provides encapsulation partially whereas.

  3. Availability of Friend function: Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class. Therefore, again the Object oriented features can be violated by C++

15. Copy Constructors

What is a copy constructor? A copy constructor is a member function which initializes an object using another object of the same class. A copy constructor has the following general function prototype:

    ClassName (const ClassName &old_obj); 

Implementation

class car
{

public:
    int milage;
    string name;

    car(int ml, string nn)
    {
        milage = ml;
        name = nn;
    }

    void getDetails()
    {
        cout << name << " " << milage << "\n";
    }

    //Copy Constructor
    car(const car &c1)
    {
        milage = c1.milage;
        name = c1.name;
    }
};

int main()
{
    car c1 = car(15, "Audi"); // Normal constructor is called here 
    car c2 = c1; // Copy constructor is called here 
    c2.getDetails();
}

When is user-defined copy constructor needed?

If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects. We need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like file handle, a network connection..etc.

16. What is destructor?

Destructor is a member function which destructs or deletes an object.

Syntax:

~constructor-name();

17. Dynamic Memory allocation in C++

It is done using new and delete operator

  • Initialize memory: We can also initialize the memory using new operator:

    pointer-variable = new data-type(value);
    Example:
    int *p = new int(25);
    float *q = new float(75.25);
  • Allocate block of memory: new operator is also used to allocate a block(an array) of memory of type data-type.

    pointer-variable = new data-type[size];
// Release memory pointed by pointer-variable
delete pointer-variable;  

Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

Polymorphism-in-CPP

In this type of inheritance, a derived class is created from another derived class.filter_none

Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. Below image shows the combination of hierarchical and multiple inheritance:

Default constructor does only shallow copy.

Deep copy is possible only with user defined copy constructor. In user defined copy constructor, we make sure that pointers (or references) of copied object point to new memory locations. Now if we make changes in 1st object the changes will also be reflected in the second object.

🚙
shallow
deep-300x179