Object oriented programming
Object oriented programming
A class is a user-defined data type. It consists of data members and member functions, which can be accessed and used by
creating an instance of that class. It represents the set of properties or methods that are common to all objects of one type. A
class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share
some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and
wheels, speed limits, mileage are their properties
Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. 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. An object
has an identity, state, and behavior. Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the type of message accepted and type of response
returned by the objects.
Example
//Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
Inside class definition
Outside class definition
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and using the
dot syntax (.):
int main() {
MyClass myObj; // Create an object
of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Nested Classes in C+
+
A nested class is a class that is declared in another class. The nested class is also a member
variable of the enclosing class and has the same access rights as the other members.
However, the member functions of the enclosing class have no special access to the members
of a nested class.
Example
int main() {
MyClass myObj; // Create an object of
MyClass (this will call the constructor)
return 0;
}
Constructor Parameters
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Access Specifiers
class MyClass { // The class
public: // Access specifier
// class members goes here
};
In C++, there are three access specifiers:
•public - members are accessible from outside the class
•private - members cannot be accessed (or viewed) from outside the class
•protected - members cannot be accessed from outside the class, however, they can be accessed
in inherited classes.
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes
as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide
public get and set methods.
Example
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
Two Important property of Encapsulation
Types of Abstraction:
1.Data abstraction – This type only shows the required information about the data and
hides the unnecessary data.
2.Control Abstraction – This type only shows the required information about the
implementation and hides unnecessary information.
// C++ Program to Demonstrate the
// working of Abstraction
#include <iostream>
using namespace std;
class implementAbstraction {
private:
int a, b;
public:
// method to set values of
// private members
void set(int x, int y)
{
a = x;
b = y;
}
void display()
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
};
int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
S.NO Abstraction Encapsulation
Abstraction is the method of hiding the unwanted Whereas encapsulation is a method to hide the data in a single entity or
3.
information. unit along with a method to protect information from outside.
We can implement abstraction using abstract class and Whereas encapsulation can be implemented using by access modifier
4.
interfaces. i.e. private, protected and public.
In abstraction, implementation complexities are hidden While in encapsulation, the data is hidden using methods of getters and
5.
using abstract classes and interfaces. setters.
C++ 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. A real-life example of polymorphism is a
person who at the same time can have different characteristics. A man at the same time is a father, a
husband, and an employee. So the same person exhibits different behavior in different situations. This is
called polymorphism. Polymorphism is considered one of the important features of Object-Oriented
Programming.
Types of Polymorphism
•Compile-time Polymorphism
•Runtime Polymorphism
A. Function Overloading
When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded, hence this is known as Function Overloading. Functions
can be overloaded by changing the number of arguments or/and changing the type of
arguments
Below is the C++ program to show function overloading or compile-time polymorphism:
In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent):
Example
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
Inheritance type
• They are as follows:
• Single Inheritance.
• Multiple Inheritance.
• Multilevel Inheritance.
• Hierarchical Inheritance.
• Hybrid Inheritance.
Single Inheritance
• Single Inheritance in C++
• The inheritance in which a single derived class is inherited from a
single base class is known as the Single Inheritance
Ex. Of single inheritance
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11.int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl; cout<<"Bonus: "<<p1.bonu
s<<endl;
return 0;
}
Multiple Inheritance in C++
• Multiple Inheritance is a feature of C++ where a class can inherit
from more than one classes.
• A class can be derived from more than one base class.
• Eg:
• (i) A CHILD class is derived from FATHER and MOTHER class
(ii) A PETROL class is derived from LIQUID and FUEL class.
Multiple Inheritance example…
#include<iostream>
using namespace std;
class A
{
public:
A() { cout << "A's constructor called" << endl; }
};
class B
{
public:
B() { cout << "B's constructor called" << endl; }
};
int main()
{
C c;
return 0;
}
Multiple inheritance introduces potential
semantic problem
• Ambiguity in inheritance can be defined as when one class is
derived for two or more base classes then there are chances that
the base classes have functions with the same name. So it will
confuse derived class to choose from similar name functions.
A A
B c
D
Ambiguities occurs in replicated inheritance
and Shared inheritance.
• Repeated inheritance -It occurs whenever (as a result of multiple
inheritance) two or more of the ancestors of a class D have a
common parent A. D is then called a repeated descendant of A, and
A a repeated ancest or of D.
• Shared inheritance -
Inheritance is used when two classes in a program share the same
domain, and the properties of the class and its superclass should
remain the same
Multilevel Inheritance in C++ is the process of deriving a class from another derived class. When one class inherits another
class it is further inherited by another class. It is known as multi-level inheritance.
For example, if we take Grandfather as a base class then Father is the derived class that has features of Grandfather and then
Child is the also derived class that is derived from the sub-class Father which inherits all the features of Father.
Syntax:
// C++ program to implement
// Multilevel Inheritance
public:
void get_C_data()
{
cout << "Enter value of c: ";
cin >> c;
}
Hierarchical Inheritance
Inheritance is a feature of Object-Oriented-programming in which a derived class (child class) inherits the property (data member and member
functions) of the Base class (parent class). For example, a child inherits the traits of their parents.
// C++ program for Hierarchical Inheritance
#include<iostream>
using namespace std;
class A //superclass A
{
public:
void show_A() {
cout<<"class A"<<endl;
}
};
class B : public A //subclass B
{
public:
void show_B() {
cout<<"class B"<<endl;
}
};
Hybrid in C++ follows the following pattern - Multiple Inheritance, Single Inheritance, and Hierarchical Inheritances are combined together.
As stated earlier, in Multiple Inheritance, a sub-class derives properties from multiple superclasses.
Hybrid Inheritance in C++ is also known as multipath inheritance. This is known so due to the fact that a sub class derives or inherits
properties of the super class following various paths. Therefore, Hybrid Inheritance is generally applied where we need to apply more
than one form of Inheritance.
Mixed Inheritance
Mixin-based inheritance means that although every class (except for Object) has
exactly one superclass, a class body can be reused in multiple class hierarchies.
Value type and reference type
n certain computer programming languages, data types are classified as either value types or reference
types, where reference types are always implicitly accessed via references, whereas value type variables
directly contain the values themselves
Primitive data types, such as Booleans, fixed-size integers, floating-point values, and characters, are value types.
Objects, in the sense of object-oriented programming, belong to reference types i.e. Variable contain address of
value
Assigning to a variable of reference type simply copies the reference, whereas assigning to a variable of value
type copies the value.
str1 1004 800
}
Referance type example
• Ex. 5
• Int a=5; a
• Int &b=a; b
In this article, we will discuss the order of execution in the initializer list in
C++. Generally, the order of execution is from top to bottom and left to
right. But a rare condition arises where this rule fails is when the
initializer list is used in class.
What is Binding?
Binding refers to the linking between the function call and the function definition. In the code, at any point of time when a function is
called, then the program control binds to the address in memory where the function has been defined.
By default, C++ matches a function call with the correct function definition at compile time. This is called static binding. You can specify
that the compiler match a function call with the correct function definition at runtime; this is called dynamic binding.
#include <iostream>
using namespace std;
class A
{
public:
void m1()
{
cout << "m1 is invoked\n";
}
void m2()
{
cout << "m2 is invoked\n";
}
};
int main()
{
A obj;
obj.m1();
obj.m2();
return 0;
}
What is Static Binding?
Static binding happens at compile-time, i.e., the function call and the
function definition are linked during the compile time itself. So, it is also
called early binding.
This is because all the information needed to associate the function call to its
definition is available at the compile time.
When does static binding take place?
Static binding happens by default for any normal function calls in the
program. It also occurs during function overloading and operator
overloading.
class add {
}
}
What is Dynamic Binding?
Dynamic binding takes place during run time based on the type of object. Since it is delayed till the
run time, it is also called late binding or runtime binding. When the compiler cannot determine all the
information required to resolve a function call during compile time, these function calls are not
bound until run time.
}
}
C++ code for demonstrating Dynamic binding:
// C++ code to demonstrate the concept of dynamic binding
#include <iostream>
when basePtr points to the
using namespace std;
derived class object
class B
{ “derived”, it is important to
public:
// function f() is declared as virtual in the base class note that the pointer is of type
virtual void f()
{ base class and the object it
cout << "The base class function is called.\n";
};
} points to is of type derived
class D : public B
class. The function calls
{
public: basePtr->f() which gets
void f() //function overriding
{ resolved at run time, and
cout << "The derived class function is called.\n";
} hence the function f() of the
};
int main()
derived class is executed as
{
B base; // base class object
the object is of the derived
D derived; //derived class object
class. This is an example of
B *basePtr = &base; // base class pointer pointing to base class object
basePtr->f(); //calls function of base class function overriding, which is
basePtr = &derived; // base class pointer pointing to object of derived class possible because of dynamic
basePtr->f(); //calls function of derived class
binding/late binding.
return 0;
}
Difference between Static Binding and Dynamic Binding
When all the information needed to call a function is available at the compile When the compiler cannot determine all the information to resolve the function call, dynamic binding occurs.
time, static binding occurs.
It can be achieved during normal function calls, function overloading and It is achieved with the use of virtual functions.
operator overloading.
Execution becomes faster than dynamic binding because the function call gets As the function call is resolved at run time, sometimes it leads to slower code execution.
resolved before run time.
It provides less flexibility compared to the dynamic binding. It provides more flexibility as different types of objects at runtime can be handled by a single function call
making the source code more readable.
What is the difference between virtual and non virtual functions in C++?
Non- virtual member functions are resolved statically. That is, the member
function is selected statically (at compile-time) based on the type of the pointer
(or reference) to the object. In contrast, virtual member functions are
resolved dynamically (at run-time).
// C++ program to illustrate What is vtable?
// concept of Virtual Functions
The vTable, or Virtual
#include <iostream> Table, is a table of
class base {
function pointers that
public: is created by the
virtual void print() { cout << "print base class\n"; }
void show() { cout << "show base class\n"; }
compiler to support
}; dynamic
class derived : public base {
public:
polymorphism
void print() { cout << "print derived class\n"; }
void show() { cout << "show derived class\n"; }
};
int main() A virtual function (also known as virtual methods) is a
{ member function that is declared within a base class and
base* bptr; is re-defined (overridden) by a derived class. When you
derived d; refer to a derived class object using a pointer or a
bptr = &d; reference to the base class, you can call a virtual
// Virtual function, binded at runtime function for that object and execute the derived class’s
bptr->print(); version of the method.
e.g.
char mystring[]="Parag";
ii. Java
In Java, strings are supported by the String class, whose values are constant strings, and the
StringBuffer class, whose values are changeable and are more like arrays of single characters.
e.g.
String s="Parag";
String s1=new String("Parag");
StringBuffer s2=new StringBuffer("Parag");
Table 1. Character string data types
i. Concatenation: Concatenation is the process of appending one string to the end of another string. You concatenate strings by
using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs
ii. Relational operation on string: strings are compared using relational operators. =, <>, ><, <, <=, =<, >, >=
iii.Substring selection using positioning subsript: For substring manipulation of a string many language provides an operation for
slecting sunstring by giving the first and last character position. In python, Next = s[1:4] this assign the character from position to 10
position of string to next variable.
iv.Substring selection using pattern matching : A pattern marching operation takes one arguments as pattern data structure in
which the pattern states the form of a desires substring. The second argument is character string that is to be examined to find a
substring matches the specified by the pattern.
v.Dynamic string: String value may static or dynamic. A static string is stored in one location
• Many string operation defined iin standard header file string.h
• Library function used for character string in c and c++ are strcpy()
Which copy and assigned the string. strcat() which concatenate one
string into another. strcmp() which compare 2 string. strlen which return
number of character.
In Java
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:
Char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
• String s="javatpoint";
• In Java, strings are supported by an immutable String class, whose
value cannot be change and the mutable stringbuffer class which
values are changeable.
For Example:
String str =“Apple”
string str1=new string(“Mango”)
StringBuffer str2 =new stringbuffer(“Banana”);
• Fixed (static) length (fixed size determined at allocation)
• FORTRAN 77, Ada, COBOL
• A FORTRAN 90 example: CHARACTER (LEN = 15) NAME;
• Limited dynamic length (fixed maximum size at allocation, but actual
contents may be less)
• C and C++ char arrays: actual length is indicated by a null character
• Dynamic length (may grow and shrink after allocation)
• SNOBOL4, Perl
String Length Options
• There are three ways to support the dynamic allocation and de-allocation
which are required for dynamic length string.
• 1)String can be store in linked list.
• 2)Store string array of pointer to individual characters allocated in the
heap.
• 3)To store complete string in adjacent storage cell.
• 1)String can be store in linked list.
• Example 1
• Given a string s, convert it into a singly linked list and return the head /
starting pointer of the linked list.
• Input:
• s = “coding”
Output:
• c -> o -> d -> i -> n -> g
Note: We are supposed to return the address of the head of the linked list.
In this case, we are supposed to return the address of node c.
• Explanation:
• The head node of the linked list should be the first character of the string,
and so the head should be pointing to the first character of the string.
• 2)Store string array of pointer to individual characters allocated in
the heap.
3)To store complete string in adjacent
storage cell
• Strings as character arrays can be stored in two ways:
• char str[6] = "Ninja"; /*One extra for string terminator*/
• char str[6] = {‘N‘,‘i’, ‘n’, ‘j‘, ‘a‘, '\0'}; /* '\0' is string terminator */