Oops
Oops
1. Class Definition
In C++, a class defines the properties (data members) and behaviors (member functions) of
an object.
2. Constructor
A constructor is a special member function of a class that gets called automatically when an
object is created. It is used to initialize the object's data members.
3. Object Declaration
An object is an instance of a class. When an object is created, the constructor initializes the
data members.
Example in C++
#include <iostream>
using namespace std;
public:
// Constructor to initialize the data members
Person(string n, int a) {
name = n;
age = a;
}
int main() {
// Create an object of the Person class
Person person1("Alice", 30);
return 0;
}
Explanation
1. Class Definition (Person): The Person class has two private data members (name
and age) and a public constructor to initialize them.
2. Constructor (Person(string n, int a)): This constructor initializes the name and
age attributes when an object is created.
3. Object Declaration (Person person1): In the main function, the person1 object is
created. The constructor is called with the arguments "Alice" and 30 to initialize the
object.
4. Displaying Information (displayInfo): The displayInfo() method is called to
print the details of the person1 object.
1.Inheritance in OOP
Inheritance is an Object-Oriented Programming (OOP) concept where one class (called the
derived or child class) inherits properties and behaviors (attributes and methods) from another
class (called the base or parent class). This allows for code reusability and the creation of a
hierarchical relationship between classes.
Types of Inheritance
1. Single Inheritance: The child class inherits from a single parent class.
2. Multiple Inheritance: The child class inherits from more than one parent class.
3. Multilevel Inheritance: A class is derived from a child class, which is also derived
from another parent class.
4. Hierarchical Inheritance: Multiple child classes inherit from a single parent class.
5. Hybrid Inheritance: A combination of two or more types of inheritance.
#include <iostream>
using namespace std;
// Base class
class Person {
protected:
string name;
int age;
public:
// Constructor to initialize the base class attributes
Person(string n, int a) {
name = n;
age = a;
}
public:
// Constructor to initialize derived class and base class attributes
Student(string n, int a, int id) : Person(n, a) {
studentID = id;
}
int main() {
// Create an object of the derived class
Student student1("Alice", 20, 101);
return 0;
}
Explanation
• Code Reusability: The derived class can use the properties and behaviors of the base
class without rewriting code.
• Access Specifiers (protected, public, private): Control the accessibility of the
base class members in the derived class.
• Constructor in Inheritance: The derived class's constructor can call the base class's
constructor to initialize its members.
THIS KEYWORD
The this keyword in C++ is a pointer that refers to the current object of a class. It is used to
distinguish between data members of a class and parameters with the same name, or to return
the current object instance from a method. It points to the memory address of the object that
invoked the method.
Example Code
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int width;
public:
// Constructor using 'this' to distinguish between member variables and
parameters
Rectangle(int length, int width) {
this->length = length;
this->width = width;
}
int main() {
// Create a Rectangle object
Rectangle rect(10, 5);
return 0;
}
Explanation
• Using this to Reference Data Members: When a parameter has the same name as a
data member, this-> helps to specify that you are referring to the class's data
member.
• Method Chaining: Returning this allows you to chain multiple method calls
together, making the code more concise.
• Returning the Current Object: Returning this in methods allows the current object
instance to be used in further method calls.
2.Abstraction In C++
Data abstraction is one of the most essential and important features of
object-oriented programming in C++. Abstraction means displaying only
essential information and ignoring the details. Data abstraction refers to
providing only essential information about the data to the outside world,
ignoring unnecessary details or implementation.
#include <iostream>
class implementAbstraction {
private:
int a, b;
public:
// private members
a = x;
b = y;
void display()
};
int main()
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
Output
a = 10
b = 20
You can see in the above program we are not allowed to access the
variables a and b directly, however, one can call the function set() to set
the values in a and b and the function display() to display the values of a
and b.
3. Encapsulation in C++
Encapsulation in C++ is defined as the wrapping up of data and
information in a single unit. In Object Oriented Programming,
Encapsulation is defined as binding together the data and the functions
that manipulate them.
Consider a real-life example of encapsulation, in a company, there are
different sections like the accounts section, finance section, sales section,
etc. Now,
• The finance section handles all the financial transactions and
keeps records of all the data related to finance.
• Similarly, the sales section handles all the sales-related
activities and keeps records of all the sales.
Now there may arise a situation when for some reason an official from
the finance section needs all the data about sales in a particular month.
In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales
section and then request him to give the particular data.
This is what Encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single name
“sales section”.
Two Important property of Encapsulation
1. Data Protection: Encapsulation protects the internal state of an
object by keeping its data members private. Access to and
modification of these data members is restricted to the class’s
public methods, ensuring controlled and secure data
manipulation.
2. Information Hiding: Encapsulation hides the internal
implementation details of a class from external code. Only the
public interface of the class is accessible, providing abstraction
and simplifying the usage of the class while allowing the
internal implementation to be modified without impacting
external code.
For example if we give input , and output should be half of input
#include <iostream>
class temp{
int a;
int b;
public:
a=input;
b=a/2;
return b;
};
int main() {
int n;
cin>>n;
temp half;
int ans=half.solve(n);
cout<<ans<<endl;
Features of Encapsulation
Below are the features of encapsulation:
1. We can not access any function from the class directly. We need
an object to access that function that is using the member
variables of that class.
2. The function which we are making inside the class must use
only member variables, only then it is called encapsulation.
3. If we don’t make a function inside the class which is using the
member variable of the class then we don’t call it encapsulation.
4. Encapsulation improves readability, maintainability, and security
by grouping data and methods together.
5. It helps to control the modification of our data members.
Encapsulation also leads to data abstraction. Using encapsulation also
hides the data, as in the above example, the data of the sections like
sales, finance, or accounts are hidden from any other section.
Role of Access Specifiers in Encapsulation
Access specifiers facilitate Data Hiding in C++ programs by restricting
access to the class member functions and data members. There are three
types of access specifiers in C++:
• Private: Private access specifier means that the member
function or data member can only be accessed by other member
functions of the same class.
• Protected: A protected access specifier means that the member
function or data member can be accessed by other member
functions of the same class or by derived classes.
• Public: Public access specifier means that the member function
or data member can be accessed by any code.
By default, all data members and member functions of a class are
made private by the compiler.
Points to Consider
As we have seen in the above example, access specifiers play an
important role in implementing encapsulation in C++. The process of
implementing encapsulation can be sub-divided into two steps:
1. Creating a class to encapsulate all the data and methods into a
single unit.
2. Hiding relevant data using access specifiers.
4.Polymorphism in c++
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
Types of Polymorphism
#include <bits/stdc++.h>
// Driver code
int main()
{
Geeks obj1;
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64
B. 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. For example, we
can make use of the addition operator (+) for string class to concatenate
two strings. We know that the task of this operator is to add two
operands. So a single operator ‘+’, when placed between integer
operands, adds them and when placed between string operands,
concatenates them.
Below is the C++ program to demonstrate operator overloading:
#include <iostream>
#include <string>
class Integer {
private:
int value;
public:
Integer(int v) : value(v) {}
};
class MyString {
private:
string value;
public:
}
// Method to display the string value
};
int main() {
Integer num1(10);
Integer num2(20);
MyString str1("Hello");
return 0;
Explanation
1. Class Integer:
o This class represents an integer and has a constructor to initialize its value.
o The + operator is overloaded to add two Integer objects. It returns a new
Integer object with the sum of the two integer values.
2. Class MyString:
o This class represents a string and has a constructor to initialize its value.
o The + operator is overloaded to concatenate two MyString objects. It returns a
new MyString object with the concatenated string.
3. Overloaded + Operator:
o For the Integer class, the + operator adds the values of two Integer objects.
oFor the MyString class, the + operator concatenates the values of two
MyString objects.
4. Main Function:
o Integer Addition: Two Integer objects (num1 and num2) are added using the
overloaded + operator.
o String Concatenation: Two MyString objects (str1 and str2) are
concatenated using the overloaded + operator.
Key Takeaways
This example is designed to show the basics of operator overloading in a clear and easy-to-
understand way.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late
binding and dynamic polymorphism are other names for runtime
polymorphism. The function call is resolved at runtime in runtime
polymorphism. In contrast, with compile time polymorphism, the
compiler determines which function call to bind to the object after
deducing it at runtime.
A. Function Overriding
Function Overriding occurs 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.
Function overriding Explanation
public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function"
<< "\n\n";
}
void print()
{
cout << "Called GFG_Base print function"
<< "\n\n";
}
};
public:
void display()
{
cout << "Called GFG_Child Display Function"
<< "\n\n";
}
void print()
{
cout << "Called GFG_Child print Function"
<< "\n\n";
}
};
int main()
{
// Create a reference of class GFG_Base
GFG_Base* base;
GFG_Child child;
base = &child;
Output
Called GFG_Child Display Function
Example 2:
C++
// C++ program for virtual function overriding
#include <bits/stdc++.h>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}
// Driver code
int main()
{
base* bptr;
derived d;
bptr = &d;
return 0;
}
Output
print derived class
show base class