Oops Notes
Oops Notes
“Object-Oriented Programming is basically a programming style that we used to follow in modern programming. It primarily revolves around classes and
objects. Object-Oriented programming or OOPs refers to the language that uses the concept of class and object in programming.”
Class
A class is a logical entity used to define a new data type. A class is a user-defined type that describes what a particular kind of object will look like. Thus, a
class is a template or blueprint for an object. A class contains variables, methods, and constructors.
Syntax:
class class_name {
};
Object
An object is an instance of a Class. It is an identifiable entity with some characteristics and behavior. Objects are the basic units of object-oriented programming. It may be any
real-world object like a person, chair, table, pen, animal, car, etc.
Syntax to create an object in C++:
class_name objectName;
Syntax to create an object dynamically in C++:
class_name * objectName = new class_name();
The class’s default constructor is called, and it dynamically allocates memory for one object of the class. The address of the memory allocated is assigned to the pointer, i.e.,
objectName.
Features of OOPs:
Four major object-oriented programming features make them different from non-OOP languages:
Abstraction is the property by virtue of which only the essential details are displayed to the user.
Inheritance allows you to create class hierarchies, where a base class gives its behavior and attributes to a derived class.
Polymorphism ensures that it will execute the proper method based on the calling object’s type.
Encapsulation allows you to control access to your object’s state while making it easier to maintain or change your implementation at a later date.
Need of object-oriented programming?
To make the development and maintenance of projects more effortless.
To provide the feature of data hiding that is good for security concerns.
We can solve real-world problems if we are using object-oriented programming.
It ensures code reusability.
It lets us write generic code: which will work with a range of data, so we don't have to write basic stuff over and over again.
Class
A class is a logical entity used to define a new data type. A class is a user-defined type that describes what a particular kind of object will look like. A class contains
variables(data members), methods, and constructors. Class is a blueprint or a set of instructions to build a specific type of object. It is a fundamental concept of Object-Oriented
Programming which revolves around real-life entities. Class determines how an object will behave and what the object will contain. Data encapsulation is supported with
"class". The class consists of both data and functions. The data in a class is called a member, while functions in the class are called methods.
Data Members: The variables declared inside a class. They are also called instance variables.
Methods: A method is function inside a class. A method accepts parameters as arguments, manipulates these, and then produces an output when the method is
called on an object.
Constructor: Constructors are special class functions that perform the initialization of every object. In C++, the constructor is automatically called when an object is
created. It is a special method of the class because it does not have any return type. It has the same name as the class itself.
Object:-
An object is an instance of a Class. It is an identifiable entity with some characteristics and behavior. To access the members defined inside the class, we need to create the
object of that class. Objects are the basic units of object-oriented programming. It may be any real-world object like a person, chair, table, pen, animal, car, etc.
Syntax to create an object in C++:
class_name objectName;
Syntax to create an object dynamically in C++:
class_name * objectName = new class_name();
The class’s default constructor is called, and it dynamically allocates memory for one object of the class. The address of the memory allocated is assigned to the pointer, i.e.,
objectName.
Access Specifier:-
Access Specifiers in a class are used to assign access to the class members. It sets some restrictions on the class members from accessing the outside functions directly.
There are three types of access specifiers in C++:
1. Public: Accessed from anywhere(inside and outside the class).
class person {
public:
string name;};
2. Private: Only be accessed by the member function inside the class.
class person {
private:
int fb_password; };
3. Protected: The access level of a protected modifier is within the class and outside the class through child class(or subclass).If you do not make the child class, it
cannot be accessed outside the class.
class person {
protected:
string assets;};
By default, in C++, all class members are private if you don't specify an access specifier.
QUESTIONS:-
Interview Questions
Constructor
Special member function automatically called when an object is created.
Does not have any return type.
Has the same name as the class itself.
Initializes the class data members with garbage value if we don’t put any value to it explicitly.
must be placed in the public section of the class, because we want the class to be instantiated anywhere.
For every object in its lifetime constructor is called only once at the time of creation.
class Class_name {
int data_member1;
string data_member2;
// creating constructor
public:
class_name() { }
};
Types of Constructor
Default Constructor
Parameterized Constructor
Copy Constructor
1. Default Constructor A constructor that doesn't take any argument or has no parameters is known as a default constructor
class Class_name {
int data_member1;
string data_member2;
public:
// default constructor
class_name() {
data_member1 = 0;
data_member2 = "chetan";}
};
2. Parameterized Constructor This is another type of Constructor with parameters. The parameterized constructor takes its arguments provided by the programmer.
These arguments help initialize an object when it is created.
class Class_name {
int data_member1;
string data_member2;
public:
// parameterized constructor
class_name(int a, string b) {
data_member1 = a;
data_member2 = b;
}};
3. Copy Constructor These are a particular type of constructor that takes an object as an argument and copies values of one object’s data members into another
object.
class Class_name {
int data_member1;
string data_member2;
public:
// copy constructor
class_name(Class_name &obj) {
// copies data of object parameter
data_member1 = obj.data_member1;
data_member2 = obj.data_member2; }
};
Constructor Overloading
Constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task.
class Class_name {
int data_member1;
string data_member2;
public:
// default constructor
class_name() {
data_member1 = 0;
data_member2 = "chetan";
}
// parameterized constructor
class_name(int a, string b) {
data_member1 = a;
data_member2 = b;
}
// copy constructor
class_name(Class_name &obj) {
// copies data of object parameter
data_member1 = obj.data_member1;
data_member2 = obj.data_member2;}
};
NOTE: Default constructor is available only till we don't create any constructor in the class. If we create any constructor then default constructor is not available, so
total number of constructors in a class is equal to number of constructors we create in the class.
Destructor:-
A destructor is a special member function that works just opposite to a constructor.
Unlike constructors that are used for initializing an object, destructors destroy (or delete) the object.
The purpose of the destructor is to free the resources that the object may have acquired during its lifetime.
~class_name() {
// body of destructor
}
Like the constructor, the destructor name should exactly match the class name.
A destructor declaration should always begin with the tilde(~) symbol, as shown in the syntax above.
If the object is created by using new or the constructor uses new to allocate memory that resides in the heap memory or the free store, the destructor should use
delete to free the memory.
Interview Questions
1. Does C++ compiler create a default constructor when we write our own?
In C++, compiler by default creates a default constructor for every class. But, if we define our own constructor, compiler doesn’t create the default constructor.
This pointer
this pointer holds the address of the current object.
In simple words, you can say that this pointer points to the current object of the class.
This pointer is accessible within non-static member functions of a class. Static member functions do not have a this pointer.
This pointer can be used to,
refer to a current class instance variable.
pass the current object as a parameter to another method.
declare indexers.
Example:
class mobile
{
string model;
int year_of_manufacture;
public:
void set_details(string model, int year_of_manufacture)
{
this->model = model;
this->year_of_manufacture = year_of_manufacture;
}
void print()
{
cout << this->model << endl;
cout << this->year_of_manufacture << endl;
}
};
int main()
{
mobile redmi;
redmi.set_details("Note 7 Pro", 2019);
redmi.print();
}
// Output:
// Note 7 Pro
// 2019
Shallow copy
An object is created by simply copying the data of all variables of the original object.
Both objects will reference the exact memory location, then change made by one will reflect those change in another object as well.
Default copy constructor is a shallow copy constructor.
It is not recommended to use shallow copy.
A shallow copy can be made by simply copying the reference.
class students()
{
int age;
char* names; // names is a pointer to a char array
public:
students(int age, char* names)
{
this->age = age;
// shallow copy
this->names = names;
// here we are putting the same array.
// we are just copying the reference }
};
Deep copy
A deep copy is a copy of an object in which the copied object is completely independent of the original object.
Separate memory is allocated for the copied object. So changes made in any object will not affect the other object.
An object is created by copying all the fields, and it also allocates similar memory resources with the same value to the object.
To perform Deep copy, we need to** explicitly define the copy constructor** and assign dynamic memory as well if required. Also, it is necessary to allocate
memory to the other constructors’ variables dynamically.
class student()
{
int age;
char* names;
public:
student(int age, char* names)
{
this->age = age; // deep copy
this->names = new char[strlen(names) + 1];
strcopy(this->names, names);
// Created new array and copied data
}
};
Interview Questions
1. What is this pointer?
this pointer is accessible only inside the member functions of a class and points to the object that has called this member function.
Pillars of OOPs
Encapsulation
Abstraction
Inheritance
Polymorphism
Encapsulation
Encapsulation is about wrapping data and methods into a single class and protecting it from outside intervention.
The general idea of this mechanism is simple. For example, you have an attribute that is not visible from the outside of an object. You bundle it with methods that
provide read or write access. Encapsulation allows you to hide specific information and control access to the object’s internal state.
It is achieved using access modifiers like public, private, protected.
Create public member functions to access private data members from class object.
Abstraction
Abstraction is the process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have
the information on what the object does instead of how it does it.
Advantages Of Abstraction
Only you can make changes to your data or function, and no one else can.
It makes the application secure by not allowing anyone else to see the background details.
Increases the reusability of the code.
Avoids duplication of your code
Encapsulation and Abstraction are two different concepts. Encapsulation is about binding the data and methods together into a single unit. Abstraction is about hiding the
implementation details from the user.
Inheritance
Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object.
It allows us to create a new class (derived class) from an existing class (base class).
It is an important part of object-oriented programming and is used to achieve runtime polymorphism.
The existing class is called the base class, and the new class is referred to as the derived class.
Syntax
class parent_class {
// Body of parent class
};
class child_class : access_modifier_parent_class {
// Body of child class
};
Modes of inheritance
1. Public Inheritance: If we derive a subclass from a public base class. Then, the base class’s public members will become public in the derived class, and protected
class members will become protected in the derived class.
2. Protected Inheritance: If we derive a subclass from a protected base class. Then, the base class’s both public and protected members will become protected in the
derived class.
3. Private Inheritance: If we derive a subclass from a private base class. Then, the base class’s both public and protected members will become private in the derived
class.
Polymorphism
Polymorphism is the ability of an object to take on many forms.
Types of Polymorphism
1. Compile Time Polymorphism
2. Run Time Polymorphism
1. Compile Time Polymorphism
Compile time polymorphism is also known as static polymorphism.
It is achieved by function overloading or operator overloading.
Function overloading is a technique in which more than one function can have the same name but different parameters.
Operator overloading is a technique in which we can change the behavior of an operator.
2. Run Time Polymorphism
Run time polymorphism is also known as dynamic polymorphism.
It is achieved by function overriding.
Function overriding is a technique in which we can change the behavior of a function in the child class.
Interview Questions
1. What is Encapsulation in C++? Why is it called Data hiding?
The process of binding data and corresponding methods (behavior) into a single unit is called encapsulation in C++.
In other words, encapsulation is a programming technique that binds the class members (variables and methods) together and prevents them from accessing other classes.
Thereby we can keep variables and methods safes from outside interference and misuse.
If a field is declared private in the class, it cannot be accessed by anyone outside the class and hides the fields. Therefore, Encapsulation is also called data hiding.
a. Inheritance represents the parent-child relationship between two classes. On the other hand, polymorphism takes advantage of that relationship to make the program more
dynamic.
b. Inheritance helps in code reusability in child class by inheriting behavior from the parent class. On the other hand, polymorphism enables child class to redefine already
defined behavior inside parent class.
Without polymorphism, a child class can’t execute its own behavior.
Virtual functions
A virtual function is a member function in the base class that we expect to redefine in derived classes. It is declared using the virtual keyword. A virtual function is
used in the base class to ensure that the function is overridden. This especially applies to cases where a pointer of base class points to a derived class object.
C++ determines which function is invoked at the runtime based on the type of object pointed by the base class pointer when the function is made virtual.
Virtual function mainly used to achieve run time polymorphism.
class Base {
public:
virtual void print()
{
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print()
{
cout << "Derived Function" << endl;
}
};
int main()
{
Derived derived1;
// pointer of Base type that points to derived1
Base* base1 = &derived1;
// calls member function of Derived class
base1->print();
return 0;
}
// Output :
// Derived Function
Pure virtual functions
A pure virtual function is a virtual function in C++ for which we need not write any function definition and only have to declare it. It is declared by assigning 0 in the
declaration.
A pure virtual function (or abstract function) in C++ is a virtual function for which we can implement, But we must override that function in the derived class;
otherwise, the derived class will also become an abstract class.
class A {
public:
virtual void s() = 0;
// Pure Virtual Function
};
Abstract class
Abstract classes can’t be instantiated, i.e., we cannot create an object of this class. However, we can derive a class from it and instantiate the object of the derived
class. An Abstract class has at least one pure virtual function.
If we do not override the pure virtual function in the derived class, then the derived class also becomes an abstract class.
We cannot create objects of an abstract class. However, we can derive classes from them and use their data members and member functions (except pure virtual
functions).
Properties of the abstract classes:
It can have normal functions and variables along with pure virtual functions.
Prominently used for upcasting(converting a derived-class reference or pointer to a base-class. In other words, upcasting allows us to treat a derived type as a base
type), so its derived classes can use its interface.
If an abstract class has a derived class, they must implement all pure virtual functions, or they will become abstract.
class Base {
public:
virtual void s() = 0; // Pure Virtual Function
};
int printLength(Rectangle b)
{
b.length += 10;
return b.length;
}
int main()
{
Rectangle b;
cout << "Length of Rectangle: " << printLength(b) << endl;
return 0;
}
// Output :
// Length of Rectangle : 20
Characteristics of friend function:
A friend function can be declared in the private or public section of the class.
It can be called a normal function without using the object.
A friend function is not in the scope of the class, of which it is a friend.
A friend function is not invoked using the class object as it is not in the class’s scope.
A friend function cannot access the private and protected data members of the class directly. It needs to make use of a class object and then access the members
using the dot operator.
A friend function can be a global function or a member of another class.
Interview Questions
class Box
{
double width;
public:
friend void printWidth(Box box);
void setWidth(double wid);
};
int main()
{
Box box;
box.setWidth(10.0);
printWidth(box);
return 0;
}
Answer: 20
Explanation:
We are using the friend function for print width and multiplied the width value by 2, So we got the output as 20
General ⚙️
tie(w,x,y,z) = make_tuple(10,20,30,40) :- w=10,x=20,y=30,z=40
unordered_set,unordered_map are faster than set and maps.
set uses self balancing binery search trees therefore O(nlogn).
unordered_set uses hashing therefore O(1) same for the map and unordered_map.
auto keyword can be used for declaring variables, it automatically set the type of that variable.
lower_bound : find >= elem , upper_bound : find > element
when we want to find element equal to we use lower_bound else upper_bound
is_sorted : Returns true if the container is sorted else false.
In Global we can declare array of bool upto 10^8 or int array upto 10^7.
In Local we can declare array of bool upto 10^7 or int array upto 10^6.
Faster operations ⏩⏩
a>>1 == divide a by 2.
a<<1 == multiply a with 2.
if (a&1)==0 == number is even.
if (a&1)==1 == number is odd, make sure you use the brackets.
swap numbers == a=a^b;b=a^b;a=a^b;
We should use emplace_back to push pair in vector insteed of pb(mp()) or pb({}).
std::string 🧵
temp.find(B) != string::npos, find B is in string or not.
s.insert(pos, string), insert string at pos position.
std::vector 🔼
v.erase(iterator) to delete elem while traversing in vector. Remember to do it--.
auto it = lower_bound(v.begin(), v.end(),elem);
int index = it - v.begin(); OR index = it - v;
std::set 🍁
auto it = s.lower_bound(elem);
int elem = *it;
s.count() returns 1 if element is present in set else 0.
NOTE: for vector and other containers which contains duplicate elements count returns count of the number.
std::map 🗺️
mp.count() returns 1 if element is present in map else 0.
NOTE: for vector and other containers which contains duplicate elements it returns count of the number.