OOP Complete
OOP Complete
OOP Complete
● Class is a user-defined data type which defines its properties and its
functions. Class is the only logical representation of the data. For
example, Human being is a class. The body parts of a human being are its
properties, and the actions performed by the body parts are known as
functions. The class does not occupy any memory space till the time an
object is instantiated.
APNI KAKSHA
● Inheritance
Inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such a way, you can reuse,
extend or modify the attributes and behaviors which are defined in other
classes.
In C++, the class which inherits the members of another class is called
derived class and the class whose members are inherited is called base class.
The derived class is the specialized class for the base class.
C++ Syntax :
Types of Inheritance :
1. Single inheritance : When one class inherits another class, it is known
as single level inheritance
2. Multiple inheritance : Multiple inheritance is the process of deriving
a new class that inherits the attributes from two or more classes.
3. Hierarchical inheritance : Hierarchical inheritance is defined as the
process of deriving more than one class from a base class.
4. Multilevel inheritance : Multilevel inheritance is a process of deriving a
class from another derived class.
5. Hybrid inheritance : Hybrid inheritance is a combination of
simple, multiple inheritance and hierarchical inheritance.
● Encapsulation
APNI KAKSHA
● Abstraction
● Polymorphism
APNI KAKSHA
Method Overloading : Method overloading is a technique which allows you
to have more than one function with the same function name but with
different functionality. Method overloading can be possible on the
following basis:
Example :
#include<bits/stdc++.h>
using namespace std;
class Add {
public:
int add(int a,int b){
return (a + b);
}
int add(int a,int b,int c){
return (a + b + c);
}
};
int main(){
Add obj;
int res1,res2;
res1 = obj.add(2,3);
res2 = obj.add(2,3,4);
cout << res1 << " " << res2 << endl;
return 0;
}
/*
Output : 5 9
add() is an overloaded function with a different number of parameters. */
APNI KAKSHA
● Runtime Polymorphism : Runtime polymorphism is also known as dynamic
polymorphism. Function overriding is an example of runtime
polymorphism. Function overriding means when the child class contains
the method which is already present in the parent class. Hence, the child
class overrides the method of the parent class. In case of function
overriding, parent and child classes both contain the same function with a
different definition. The call to the function is determined at runtime is
known as runtime polymorphism.
#include <bits/stdc++.h>
using namespace std;
class Base_class{
public:
virtual void show(){
cout << "Apni Kaksha base" << endl;
}
};
int main(){
Base_class* b;
Derived_class d;
b = &d;
b->show(); // prints the content of show() declared in derived
class return 0;
APNI KAKSHA
}
#include <bits/stdc++.h>
using namespace std;
class go {
public:
int x;
go(int a){ // parameterized constructor.
APNI KAKSHA
x=a;
}
go(go &i){ // copy constructor
x = i.x;
}
};
int main(){
go a1(20); // Calling the parameterized constructor.
go a2(a1); // Calling the copy constructor.
cout << a2.x << endl;
return 0;
}
// Output : 20
Example :
#include<bits/stdc++.h>
using namespace std;
class A{
public:
// constructor and destructor are called automatically,
once the object is instantiated
A(){
cout << "Constructor in use" << endl;
}
~A(){
cout << "Destructor in use" << endl;
}
};
int main(){
APNI KAKSHA
A a;
A b;
return 0;
}
/*
Output: Constructor in use
Constructor in use
Destructor in use
Destructor in use
*/
● ‘this’ Pointer : this is a keyword that refers to the current instance of the
class. There can be 3 main uses of ‘this’ keyword:
1. It can be used to pass the current object as a parameter to
another method
C++ Syntax :
struct node{
int data;
node *next;
node(int x){
this->data = x;
this->next = NULL;
}
}
● Friend Function : Friend function acts as a friend of the class. It can access
the private and protected members of the class. The friend function is not
APNI KAKSHA
a member of the class, but it must be listed in the class definition. The
non-member function cannot access the private data of the class.
Sometimes, it is necessary for the non-member function to access the data.
The friend function is a non-member function and has the ability to
access the private data of the class.
Note :
1. A friend function cannot access the private members directly, it has
to use an object name and dot operator with each member name.
2. Friend function uses objects as arguments.
Example IMP :
#include <bits/stdc++.h>
using namespace std;
class A{
int a = 2;
int b = 4;
public:
// friend function
friend int mul(A k){
return (k.a * k.b);
}
};
int main(){
A obj;
int res = mul(obj);
cout << res << endl;
return 0;
}
// Output : 8
APNI KAKSHA
any entity reference. It is another way to reuse the class. It is a form of
association that represents the HAS-A relationship.
2. When we use the same function name in both base and derived
class, the function in base class is declared with a keyword
virtual.
Key Points :
1. Virtual functions cannot be static.
2. A class may have a virtual destructor but it cannot have a virtual
constructor.
C++ Example :
#include <bits/stdc++.h>
APNI KAKSHA
using namespace std;
class base {
public:
// virtual function (re-defined in the derived class)
virtual void print(){
cout << "print base class" << endl;
}
void show(){
cout << "show base class" << endl;
}
};
void show(){
cout << "show derived class" << endl;
}
};
int main(){
base* bptr;
derived d;
bptr = &d;
/*
output :
APNI KAKSHA
print derived class // (impact of virtual function)
show base class
*/
C++ Syntax :
C++ Example :
#include<bits/stdc++.h>
using namespace std;
class Base{
public:
virtual void show() = 0;
};
class Derived : public Base {
public:
void show() {
cout << "You can see me !" << endl;
}
};
int main(){
Base *bptr;
APNI KAKSHA
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Example :
#include<bits/stdc++.h>
using namespace std;
// abstract class
class Shape{
public:
virtual void draw()=0;
};
class Rectangle : Shape{
public:
void draw(){
cout << "Rectangle" << endl;
}
};
class Square : Shape{
public:
void draw(){
cout << "Square" << endl;
}
};
int main(){
Rectangle rec;
Square sq;
APNI KAKSHA
rec.draw();
sq.draw();
return 0;
}
/*
Output :
Rectangle
Square
*/
● Namespaces in C++ :
1. The namespace is a logical division of the code which is designed to
stop the naming conflict.
2. The namespace defines the scope where the identifiers such as
variables, class, functions are declared.
3. The main purpose of using namespace in C++ is to remove the
ambiguity. Ambiguity occurs when a different task occurs with the
same name.
4. For example: if there are two functions with the same name such as
add(). In order to prevent this ambiguity, the namespace is used.
Functions are declared in different namespaces.
5. C++ consists of a standard namespace, i.e., std which contains
inbuilt classes and functions. So, by using the statement "using
namespace std;" includes the namespace "std" in our program.
C++ Example :
#include <bits/stdc++.h>
using namespace std;
// user-defined namespace
namespace Add {
int a = 5, b = 5;
int add() {
return (a + b);
}
}
APNI KAKSHA
int main() {
int res = Add :: add(); // accessing the function inside namespace
cout << res;
}
// output : 10
● Access Specifiers IMP : The access specifiers are used to define how functions
and variables can be accessed outside the class. There are three types of
access specifiers:
Key Notes
● Virtual inheritance facilitates you to create only one copy of each object
even if the object appears more than one in the hierarchy.
APNI KAKSHA
Operator overloading: Operator overloading is defined as the standard
operator can be redefined so that it has a different meaning when applied to
the instances of a class.
APNI KAKSHA
OOPs Interview Questions
©Copyright by Interviewbit
Contents
The programming languages that use and follow the Object-Oriented Programming
paradigm or OOPs, are known as Object-Oriented Programming languages. Some of
the major Object-Oriented Programming languages include:
Java
C++
Javascript
Python
PHP
And many more.
9. What is a class?
A class can be understood as a template or a blueprint, which contains some values,
known as member data or member, and some set of rules, known as behaviors or
functions. So when an object is created, it automatically takes the data and functions
that are defined in the class.
Therefore the class is basically a template or blueprint for objects. Also one can
create as many objects as they want based on a class.
For example, first, a car’s template is created. Then multiple units of car are created
based on that template.
One can visualize Encapsulation as the method of putting everything that is required
to do the job, inside a capsule and presenting that capsule to the user. What it means
is that by Encapsulation, all the necessary data and methods are bind together and
all the unnecessary details are hidden to the normal user. So Encapsulation is the
process of binding data members and methods of a program together to do a specific
job, without revealing unnecessary details.
2)Data binding: Encapsulation is the process of binding the data members and the
methods together as a whole, as a class.
In OOPs, Polymorphism refers to the process by which some code, data, method, or
object behaves differently under different circumstances or contexts. Compile-time
polymorphism and Run time polymorphism are the two types of polymorphisms in
OOPs languages.
// In this program, we will see how multiple functions are created with the same name,
// but the compiler decides which function to call easily at the compile time itself.
class CompileTimePolymorphism{
// 1st method with name add
public int add(int x, int y){
return x+y;
}
// 2nd method with name add
public int add(int x, int y, int z){
return x+y+z;
}
// 3rd method with name add
public int add(double x, int y){
return (int)x+y;
}
// 4th method with name add
public int add(int x, double y){
return x+(int)y;
}
}
class Test{
public static void main(String[] args){
CompileTimePolymorphism demo=new CompileTimePolymorphism();
// In the below statement, the Compiler looks at the argument types and decides to c
System.out.println(demo.add(2,3));
// Similarly, in the below statement, the compiler calls method 2
System.out.println(demo.add(2,3,4));
// Similarly, in the below statement, the compiler calls method 4
System.out.println(demo.add(2,3.4));
// Similarly, in the below statement, the compiler calls method 3
System.out.println(demo.add(2.5,3));
}
}
In the above example, there are four versions of add methods. The first method takes
two parameters while the second one takes three. For the third and fourth methods,
there is a change of order of parameters. The compiler looks at the method signature
and decides which method to invoke for a particular method call at compile time.
class AnyVehicle{
public void move(){
System.out.println(“Any vehicle should move!!”);
}
}
class Bike extends AnyVehicle{
public void move(){
System.out.println(“Bike can move too!!”);
}
}
class Test{
public static void main(String[] args){
AnyVehicle vehicle = new Bike();
// In the above statement, as you can see, the object vehicle is of type AnyVehicle
// But the output of the below statement will be “Bike can move too!!”,
// because the actual implementation of object ‘vehicle’ is decided during runtime v
vehicle = new AnyVehicle();
// Now, the output of the below statement will be “Any vehicle should move!!”,
vehicle.move();
}
}
As the method to call is determined at runtime, as shown in the above code, this is
called runtime polymorphism.
Constructors are special methods whose name is the same as the class name. The
constructors serve the special purpose of initializing the objects.
For example, suppose there is a class with the name “MyClass”, then when you
instantiate this class, you pass the syntax:
MyClass myClassObject = new MyClass();
Now here, the method called after “new” keyword - MyClass(), is the constructor of
this class. This will help to instantiate the member data and methods and assign
them to the object myClassObject.
class ABC
{
int x;
ABC()
{
x = 0;
}
}
Parameterized constructor: The constructors that take some arguments are known
as parameterized constructors.
class ABC
{
int x;
ABC(int y)
{
x = y;
}
}
class ABC
{
int x;
ABC(int y)
{
x = y;
}
// Copy constructor
ABC(ABC abc)
{
x = abc.x;
}
}
23. Are class and structure the same? If not, what's the
difference between a class and a structure?
No, class and structure are not the same. Though they appear to be similar, they have
differences that make them apart. For example, the structure is saved in the stack
memory, whereas the class is saved in the heap memory. Also, Data Abstraction
cannot be achieved with the help of structure, but with class, Abstraction is majorly
used.
Single inheritance Multiple Inheritance Issues: Some programming languages support multiple
inheritance, where a class can inherit from multiple base classes. However, multiple
Multiple inheritances inheritance can lead to complexities and challenges, such as the "diamond problem"
where ambiguity arises if two base classes have a common method name. Resolving
such conflicts can be challenging and may require explicit disambiguation.
Multi-level inheritance Tight Coupling: Inheritance can create a strong coupling between classes, where
changes in the base class can affect the behavior of derived classes. This tight
Hierarchical inheritance coupling can make the code more fragile and harder to maintain, as changes in one
class can inadvertently impact other classes in the inheritance hierarchy.
Hybrid inheritance Limited Code Reusability: Inheritance promotes code reuse by inheriting properties and
behavior from a base class. However, this reuse is limited to the hierarchical
relationship, as derived classes are tightly bound to the implementation details of the
base class. Inheritance may not provide the same level of code reuse flexibility as other
mechanisms like composition.
Access specifiers, as the name suggests, are a special type of keywords, which are
used to control or specify the accessibility of entities like classes, methods, etc. Some
of the access specifiers or access modifiers include “private”, “public”, etc. These
access specifiers also play a very vital role in achieving Encapsulation - one of the
major features of OOPs.
#include<iostream>
class BaseClass2 {
public:
BaseClass2()
{ cout << "BaseClass2 constructor called" << endl; }
};
int main()
{
DerivedClass derived_class;
return 0;
}
Output:
Reason:
The above program demonstrates Multiple inheritances. So when the Derived class’s
constructor is called, it automatically calls the Base class's constructors from left to
right order of inheritance.
class Scaler
{
static int i;
static
{
System.out.println(“a”);
i = 100;
}
}
System.out.println(Scaler.i);
}
}
Output:
b
c
a
100
Reason:
Firstly the static block inside the main-method calling class will be implemented.
Hence ‘b’ will be printed first. Then the main method is called, and now the sequence
is kept as expected.
#include<iostream>
using namespace std;
class ClassA {
public:
ClassA(int ii = 0) : i(ii) {}
void show() { cout << "i = " << i << endl;}
private:
int i;
};
class ClassB {
public:
ClassB(int xx) : x(xx) {}
operator ClassA() const { return ClassA(x); }
private:
int x;
};
void g(ClassA a)
{ a.show(); } operator ClassA() const { return ClassA(x); }
Output:
i = 10
i = 20
Reason:
ClassA contains a conversion constructor. Due to this, the objects of ClassA can have
integer values. So the statement g(20) works. Also, ClassB has a conversion operator
overloaded. So the statement g(b) also works.
Output:
Main1
Reason:
Here the main() method is overloaded. But JVM only understands the main method
which has a String[] argument in its definition. Hence Main1 is printed and the
overloaded main method is ignored.
#include<iostream>
using namespace std;
class BaseClass{
int arr[10];
};
int main(void)
{
cout<<sizeof(DerivedClass);
return 0;
}
Output:
If the size of the integer is 4 bytes, then the output will be 80.
Reason:
Since DerivedBaseClass1 and DerivedBaseClass1 both inherit from class BaseClass,
DerivedClass contains two copies of BaseClass. Hence it results in wastage of space
and a large size output. It can be reduced with the help of a virtual base class.
#include<iostream>
class B : public A {
public:
void print()
{ cout <<" Inside B"; }
};
class C: public B {
};
int main(void)
{
C c;
c.print();
return 0;
}
Output:
Inside B
Reason:
The above program implements a Multi-level hierarchy. So the program is linearly
searched up until a matching function is found. Here, it is present in both classes A
and B. So class B’s print() method is called.
Useful Resource
Features of OOPS