Introduction and Definitions

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;  

Last updated