0% found this document useful (0 votes)
41 views22 pages

Oops

Oops last moment revision for interveiw purpose

Uploaded by

gauravsrivsin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views22 pages

Oops

Oops last moment revision for interveiw purpose

Uploaded by

gauravsrivsin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

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;

// Define a class named 'Person'


class Person {
private:
string name; // Data member for name
int age; // Data member for age

public:
// Constructor to initialize the data members
Person(string n, int a) {
name = n;
age = a;
}

// Member function to display the person's details


void displayInfo() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
// Create an object of the Person class
Person person1("Alice", 30);

// Call the member function to display the details of the object


person1.displayInfo();

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.

Example of Single Inheritance in C++

Here's a simple example demonstrating single 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;
}

// Method to display the base class details


void displayInfo() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

// Derived class inheriting from the base class 'Person'


class Student : public Person {
private:
int studentID;

public:
// Constructor to initialize derived class and base class attributes
Student(string n, int a, int id) : Person(n, a) {
studentID = id;
}

// Method to display the derived class details


void displayStudentInfo() {
// Call the base class method
displayInfo();
cout << "Student ID: " << studentID << endl;
}
};

int main() {
// Create an object of the derived class
Student student1("Alice", 20, 101);

// Display details of the student


student1.displayStudentInfo();

return 0;
}

Explanation

1. Base Class (Person):


o The Person class has two protected data members (name and age), which can
be accessed in the derived class.
o It includes a constructor to initialize these data members and a method
displayInfo() to show the person's details.
2. Derived Class (Student):
o The Student class inherits from the Person class using the public keyword,
which means all public members of Person become public members of
Student.
o The Student class adds an additional private member, studentID.
o The constructor of Student initializes both the base class (Person) and the
derived class (Student) members.
o The displayStudentInfo() method calls the displayInfo() method from
the base class and also prints the studentID.
3. Main Function (main):
o An object of the derived class Student is created, and the constructor
initializes the object's attributes.
o The displayStudentInfo() method displays the details of the student.

Key Concepts of Inheritance

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

Key Uses of the this Keyword

1. Distinguishing Between Data Members and Parameters: When a parameter name


matches a data member name, this can be used to differentiate them.
2. Returning the Current Object: It can be used to return the current object from a
method, often for method chaining.

Example Code

Here is a simple example to demonstrate the use of the this keyword:

#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;
}

// Method to set the length, returning 'this' to allow for method


chaining
Rectangle* setLength(int length) {
this->length = length;
return this; // Return the current object
}

// Method to set the width, returning 'this' to allow for method


chaining
Rectangle* setWidth(int width) {
this->width = width;
return this; // Return the current object
}

// Method to calculate and return the area of the rectangle


int calculateArea() const {
return length * width;
}

// Method to display the dimensions of the rectangle


void display() const {
cout << "Length: " << length << ", Width: " << width << endl;
}
};

int main() {
// Create a Rectangle object
Rectangle rect(10, 5);

// Display initial dimensions


rect.display();

// Modify dimensions using method chaining with 'this' keyword


rect.setLength(15)->setWidth(10);

// Display modified dimensions


rect.display();

// Calculate and display the area


cout << "Area: " << rect.calculateArea() << endl;

return 0;
}

Explanation

1. Class Definition (Rectangle):


o The Rectangle class has two private data members: length and width.
o The constructor initializes these members using the this keyword to
distinguish between the parameter names and the data members.
2. Constructor (Rectangle(int length, int width)):
o In the constructor, this->length = length assigns the value of the
parameter length to the data member length.
o Similarly, this->width = width assigns the parameter width to the data
member width.
o Without this, the parameter would shadow the data member, making it
unclear which is being referenced.
3. Methods for Setting Attributes (setLength and setWidth):
o These methods use this to refer to the current object and set the
corresponding data members.
o They return this to allow for method chaining, which means that multiple
method calls can be combined in a single statement (e.g.,
rect.setLength(15)->setWidth(10)).
4. Displaying Dimensions and Calculating Area:
o The display() method shows the current dimensions of the rectangle.
o The calculateArea() method calculates the area using the current values of
length and width.
5. Main Function (main):
o An instance of the Rectangle class is created with initial dimensions of 10
and 5.
o The dimensions are modified using method chaining, facilitated by the this
keyword.
o The final dimensions and area are displayed.

Key Concepts Illustrated

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

Consider a real-life example of a man driving a car. The man only


knows that pressing the accelerator will increase the speed of the car or
applying brakes will stop the car but he does not know how on pressing
the accelerator the speed is actually increasing, he does not know about
the inner mechanism of the car or the implementation of the accelerator,
brakes, etc in the car. This is what abstraction is.
Types of Abstraction:
1. Data abstraction – This type only shows the required
information about the data and ignores unnecessary details.
2. Control Abstraction – This type only shows the required
information about the implementation and ignores unnecessary
details.
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.
Abstraction using Access Specifiers
Access specifiers are the main pillar of implementing abstraction in C++.
We can use access specifiers to enforce restrictions on class members.
For example:
• Members declared as public in a class can be accessed from
anywhere in the program.
• Members declared as private in a class, can be accessed only
from within the class. They are not allowed to be accessed from
any part of the code outside the class.
We can easily implement abstraction using the above two features
provided by access specifiers. Say, the members that define the internal
implementation can be marked as private in a class. And the important
information needed to be given to the outside world can be marked as
public. And these public members can access the private members as
they are inside the class. Our C++ covers how to implement abstraction
in your C++ programs, making your code cleaner and more manageable.

#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();

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.

Advantages of Data Abstraction


• Helps the user to avoid writing the low-level code
• Avoids code duplication and increases reusability.
• Can change the internal implementation of the class
independently without affecting the user.
• Helps to increase the security of an application or program as
only important details are provided to the user.
• It reduces the complexity as well as the redundancy of the code,
therefore increasing the readability.
• New features or changes can be added to the system with
minimal impact on existing code.

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>

using namespace std;

class temp{

int a;

int b;

public:

int solve(int input){

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

To master polymorphism and other OOP principles, our Complete C++


Course offers in-depth tutorials on advanced object-oriented concepts.
1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or
operator overloading.
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. In simple terms, it is a feature of object-oriented
programming providing many functions that have the same name but
distinct parameters when numerous tasks are listed under one function
name. There are certain Rules of Function Overloading that should be
followed while overloading a function.
Below is the C++ program to show function overloading or compile-time
polymorphism:

#include <bits/stdc++.h>

using namespace std;


class Geeks {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}

// Function with same name but


// 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};

// Driver code
int main()
{
Geeks obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}

Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64

Explanation: In the above example, a single function named


function func() acts differently in three different situations, which is a
property of polymorphism.

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>

using namespace std;

// Class to handle integer addition

class Integer {
private:

int value;

public:

// Constructor to initialize the integer value

Integer(int v) : value(v) {}

// Overload the + operator for adding two Integer objects

Integer operator+(const Integer& other) {

return Integer(value + other.value);

// Method to display the integer value

void display() const {

cout << "Integer Result: " << value << endl;

};

// Class to handle string concatenation

class MyString {

private:

string value;

public:

// Constructor to initialize the string value

MyString(const string& v) : value(v) {}

// Overload the + operator for concatenating two MyString objects

MyString operator+(const MyString& other) {

return MyString(value + other.value);

}
// Method to display the string value

void display() const {

cout << "String Result: " << value << endl;

};

int main() {

// Example for integer addition

Integer num1(10);

Integer num2(20);

Integer intResult = num1 + num2; // Add two Integer objects

intResult.display(); // Output: Integer Result: 30

// Example for string concatenation

MyString str1("Hello");

MyString str2(" World");

MyString strResult = str1 + str2; // Concatenate two MyString objects

strResult.display(); // Output: String Result: Hello World

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

• Operator Overloading Simplified: We defined custom behavior for the + operator to


work with two different classes.
• Basic Use Case: This example keeps the implementation straightforward and easy to
understand, focusing only on simple integer addition and string concatenation.

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

Runtime Polymorphism with Data Members


B. Virtual Function
A virtual function is a member function that is declared in the base class
using the keyword virtual and is re-defined (Overridden) in the derived
class.
Some Key Points About Virtual Functions:
• Virtual functions are Dynamic in nature.
They are defined by inserting the keyword “virtual” inside a

base class and are always declared with a base class and
overridden in a child class
• A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:
C++
// C++ Program to demonstrate
// the Virtual Function
#include <iostream>
using namespace std;

// Declaring a Base class


class GFG_Base {

public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function"
<< "\n\n";
}

void print()
{
cout << "Called GFG_Base print function"
<< "\n\n";
}
};

// Declaring a Child Class


class GFG_Child : public GFG_Base {

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;

// This will call the virtual function


base->display();

// This will call the non-virtual function


base->print();
}

Output
Called GFG_Child Display Function

Called GFG_Base print 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;
}

void show() { cout << "show base class" << endl; }


};

class derived : public base {


public:
// print () is already virtual function in
// derived class, we could also declared as
// virtual void print () explicitly
void print() { cout << "print derived class" << endl; }

void show() { cout << "show derived class" << endl; }


};

// Driver code
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;
}

Output
print derived class
show base class

You might also like