OOP Complete

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

OBJECT ORIENTED PROGRAMMING

● Object-Oriented Programming is a methodology or paradigm to design a


program using classes and objects. It simplifies the software development
and maintenance by providing some concepts defined below :

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

C++ Syntax (for class) :


class student{
public:
int id; // data member
int mobile;
string name;

int add(int x, int y){ // member functions


return x + y;
}
};

● Object is a run-time entity. It is an instance of the class. An object can


represent a person, place or any other item. An object can operate on
both data members and member functions.

C++ Syntax (for object):


student s = new student();

Note : When an object is created using a new keyword, then space is


allocated for the variable in a heap, and the starting address is stored in
the stack memory. When an object is created without a new keyword,
then space is not allocated in the heap memory, and the object contains
the null value in the stack.

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 :

class derived_class :: visibility-mode base_class;


visibility-modes = {private, protected, public}

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

Encapsulation is the process of combining data and functions into a single


unit called class. In Encapsulation, the data is not accessed directly; it is
accessed through the functions present inside the class. In simpler words,
attributes of the class are kept private and public getter and setter methods
are provided to manipulate these attributes. Thus, encapsulation makes the
concept of data hiding possible. (Data hiding: a language feature to restrict
access to members of an object, reducing the negative effect due to
dependencies. e.g. "protected", "private" feature in C++).

APNI KAKSHA
● Abstraction

We try to obtain an abstract view, model or structure of a real life problem,


and reduce its unnecessary details. With definition of properties of
problems, including the data which are affected and the operations which
are identified, the model abstracted from problems can be a standard
solution to this type of problems. It is an efficient way since there are
nebulous real-life problems that have similar properties.

Data binding : Data binding is a process of binding the application UI and


business logic. Any change made in the business logic will reflect directly to the
application UI.

● Polymorphism

Polymorphism is the ability to present the same interface for differing


underlying forms (data types). With polymorphism, each of these classes
will have different underlying data. A point shape needs only two
coordinates (assuming it's in a two-dimensional space of course). A circle
needs a center and radius. A square or rectangle needs two coordinates for
the top left and bottom right corners and (possibly) a rotation. An irregular
polygon needs a series of lines. Precisely, Poly means ‘many’ and morphism
means ‘forms’.

Types of Polymorphism IMP

1. Compile Time Polymorphism (Static)


2. Runtime Polymorphism (Dynamic)

Let’s understand them one by one :

● Compile Time Polymorphism : The polymorphism which is implemented at


the compile time is known as compile-time polymorphism. Example -
Method Overloading

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:

1. The return type of the overloaded function.

2. The type of the parameters passed to the function.

3. The number of parameters passed to the function.

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.

C++ Sample Code :

#include <bits/stdc++.h>
using namespace std;

class Base_class{
public:
virtual void show(){
cout << "Apni Kaksha base" << endl;
}
};

class Derived_class : public Base_class{


public:
void show(){
cout << "Apni Kaksha derived" << 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
}

// Output : Apni Kaksha derived

● Constructor : Constructor is a special method which is invoked automatically


at the time of object creation. It is used to initialize the data members of
new objects generally. The constructor in C++ has the same name as class or
structure.

There can be two types of constructors in C++.

1. Default constructor : A constructor which has no argument is known


as default constructor. It is invoked at the time of creating an
object.

2. Parameterized constructor : Constructor which has parameters is


called a parameterized constructor. It is used to provide
different values to distinct objects.

3. Copy Constructor : A Copy constructor is an overloaded


constructor used to declare and initialize an object from another
object. It is of two types - default copy constructor and user
defined copy constructor.

C++ Sample Code :

#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

● Destructor : A destructor works opposite to constructor; it destructs the


objects of classes. It can be defined only once in a class. Like constructors, it
is invoked automatically. A destructor is defined like a constructor. It must
have the same name as class, prefixed with a tilde sign (~).

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

2. It can be used to refer to the current class instance variable.

3. It can be used to declare indexers.

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

● Aggregation : It is a process in which one class defines another class as

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.

● Virtual Function IMP: A virtual function is used to replace the


implementation provided by the base class. The replacement is always
called whenever the object in question is actually of the derived class, even
if the object is accessed by a base pointer rather than a derived pointer.
1. A virtual function is a member function which is present in the
base class and redefined by the derived class.

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.

3. When the function is made virtual, then C++ determines at run-time


which function is to be called based on the type of the object pointed
by the base class
pointer. Thus, by making the base class pointer to point to
different objects, we can execute different versions of the virtual
functions.

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

class derived : public base {


public:
void print(){
cout << "print derived class" << endl;
}

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

int main(){
base* bptr;
derived d;
bptr = &d;

// virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();
}

/*
output :

APNI KAKSHA
print derived class // (impact of virtual function)
show base class
*/

● Pure Virtual Function :


1. A pure virtual function is not used for performing any task. It only
serves as a placeholder.
2. A pure virtual function is a function declared in the base class
that has no definition relative to the base class.
3. A class containing the pure virtual function cannot be used to declare
the objects of its own, such classes are known as abstract base
classes.
4. The main objective of the base class is to provide the traits to the
derived classes and to create the base pointer used for achieving the
runtime polymorphism.

C++ Syntax :

virtual void display() = 0;

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

// output : You can see me !

● Abstract Classes : In C++ class is made abstract by declaring at least one of


its functions as a pure virtual function. A pure virtual function is specified
by placing "= 0" in its declaration. Its implementation must be provided
by derived classes.

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:

1. Private: Functions and variables declared as private can be accessed only


within the same class, and they cannot be accessed outside the class they
are declared.
2. Public: Functions and variables declared under public can be accessed from
anywhere.
3. Protected: Functions and variables declared as protected cannot be
accessed outside the class except a child class. This specifier is generally
used in inheritance.

Key Notes

● Delete is used to release a unit of memory, delete[] is used to release an array.

● Virtual inheritance facilitates you to create only one copy of each object
even if the object appears more than one in the hierarchy.

● Function overloading: Function overloading is defined as we can have more


than one version of the same function. The versions of a function will have
different signatures meaning that they have a different set of parameters.

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.

● Overloading is static Binding, whereas Overriding is dynamic Binding.


Overloading is nothing but the same method with different arguments,
and it may or may not return the same value in the same class itself.
Overriding is the same method name with the same arguments and
return types associated with the class and its child class.

APNI KAKSHA
OOPs Interview Questions

To view the live version of the


page, click here.

©Copyright by Interviewbit
Contents

Basic OOPs Interview Questions


1. What is meant by the term OOPs?
2. What is the need for OOPs?
3. What are some major Object Oriented Programming languages?
4. What are some other programming paradigms other than OOPs?
5. What is meant by Structured Programming?
6. What are the main features of OOPs?
7. What are some advantages of using OOPs?
8. Why is OOPs so popular?

Advanced OOPs Interview Questions


9. What is a class?
10. What is an object?
11. What is encapsulation?
12. What is Polymorphism?
13. What is Compile time Polymorphism and how is it different from Runtime
Polymorphism?
14. How does C++support Polymorphism?
15. What is meant by Inheritance?
16. What is Abstraction?
17. How much memory does a class occupy?
18. Is it always necessary to create objects from class?

Page 1 ©Copyright by Interviewbit


OOPs Interview Questions

Advanced OOPs Interview Questions (.....Continued)


19. What is a constructor?
20. What are the various types of constructors in C++?
21. What is a copy constructor?
22. What is a destructor?
23. Are class and structure the same? If not, what's the difference between a class
and a structure?
24. Explain Inheritance with an example?
25. Are there any limitations of Inheritance?
26. What are the various types of inheritance?
27. What is a subclass?
28. Define a superclass?
29. What is an interface?
30. What is meant by static polymorphism?
31. What is meant by dynamic polymorphism?
32. What is the difference between overloading and overriding?
33. How is data abstraction accomplished?
34. What is an abstract class?
35. How is an abstract class different from an interface?
36. What are access specifiers and what is their significance?
37. What is an exception?
38. What is meant by exception handling?

Page 2 ©Copyright by Interviewbit


OOPs Interview Questions

Advanced OOPs Interview Questions (.....Continued)


39. What is meant by Garbage Collection in OOPs world?
40. Can we run a Java application without implementing the OOPs concept?

OOPs Coding Problems


41. What is the output of the below code?
42. What will be the output of the below code?
43. Predict the output?
44. What will be the output in below code?
45. Predict the output?
46. What is the output of the below program?

Page 3 ©Copyright by Interviewbit


Let's get Started
OOPs, or Object-Oriented Programming is a programming model or paradigm which
revolves around the concept of “OBJECTS”. Objects can be considered as real-world
instances of entities like class, that contain some characteristics and behaviors
specified in the class template.
In simple language, a class can be considered as the blueprint or template, based on
which objects can be created. So the Objects are considered the instance of a class,
and are therefore sometimes called “instances”. The term “characteristics” refers to
the “what” about the Object, and the term “behavior” refers to the “how” about the
Object.
For example, if we consider a car, then based on the OOPs model:
Class =A specific car model, such as Audi A4, BMW I8, Maruti Suzuki Vitara
Brezza, etc.
Object =A specific car of any model, like the car you own
Characteristics =What is the color of your car? What is the Chassis number of
your car? etc
Behavior =How to start the car? How to change the gear of the car? etc.
Characteristics are also known as data, attributes, or properties, and Behaviours are
also known as the functions, procedures or methods, in the programming language.
The concept of “objects” allows the OOPs model to easily access, use and modify the
instance data and methods, interact with other objects, and define methods in
runtime (during the execution of the program). This gives the OOPs model
significance and makes it diverse in its implementation.
In fact, the OOPs model is so popular, that many of the most widely used
programming languages support and use this Object Oriented Programming or OOPs
model, such as Java, C++,Python, C#,etc.

Page 4 ©Copyright by Interviewbit


OOPs Interview Questions

Basic OOPs Interview Questions


1. What is meant by the term OOPs?
OOPs refers to Object-Oriented Programming. It is the programming paradigm that is
defined using objects. Objects can be considered as real-world instances of entities
like class, that have some characteristics and behaviors.

2. What is the need for OOPs?


There are many reasons why OOPs is mostly preferred, but the most important
among them are:
OOPs helps users to understand the software easily, although they don’t know
the actual implementation.
With OOPs, the readability, understandability, and maintainability of the code
increase multifold.
Even very big software can be easily written and managed easily using OOPs.

3. What are some major Object Oriented Programming


languages?

Page 5 ©Copyright by Interviewbit


OOPs Interview Questions

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.

4. What are some other programming paradigms other than


OOPs?
Programming paradigms refers to the method of classification of programming
languages based on their features. There are mainly two types of Programming
Paradigms:
Imperative Programming Paradigm
Declarative Programming Paradigm

Page 6 ©Copyright by Interviewbit


OOPs Interview Questions

Now, these paradigms can be further classified based:

1. ImperativeProgramming Paradigm: Imperative programming focuses on HOW


to execute program logic and defines control flow as statements that change a
program state. This can be further classified as:
a) Procedural Programming Paradigm: Procedural programming specifies the steps a
program must take to reach the desired state, usually read in order from top to
bottom.
b) Object-Oriented Programming or OOP: Object-oriented programming (OOP)
organizes programs as objects, that contain some data and have some behavior.
c) Parallel Programming: Parallel programming paradigm breaks a task into subtasks
and focuses on executing them simultaneously at the same time.

2. Declarative Programming Paradigm: Declarative programming focuses on WHAT


to execute and defines program logic, but not a detailed control flow. Declarative
paradigm can be further classified into:
a)Logical Programming Paradigm: Logical programming paradigm is based on
formal logic, which refers to a set of sentences expressing facts and rules about how
to solve a problem
b) Functional Programming Paradigm: Functional programming is a programming
paradigm where programs are constructed by applying and composing functions.
c) Database Programming Paradigm: Database programming model is used to
manage data and information structured as fields, records, and files.

Page 7 ©Copyright by Interviewbit


OOPs Interview Questions

5. What is meant by Structured Programming?


Structured Programming refers to the method of programming which consists of a
completely structured control flow. Here structure refers to a block, which contains a
set of rules, and has a definitive control flow, such as (if/then/else), (while and for),
block structures, and subroutines.
Nearly all programming paradigms include Structured programming, including the
OOPs model.

6. What are the main features of OOPs?


OOPs or Object Oriented Programming mainly comprises of the below four features,
and make sure you don't miss any of these:
Inheritance
Encapsulation
Polymorphism
Data Abstraction

Page 8 ©Copyright by Interviewbit


OOPs Interview Questions

7. What are some advantages of using OOPs?


OOPs is very helpful in solving very complex level of problems.
Highly complex programs can be created, handled, and maintained easily using
object-oriented programming.
OOPs, promote code reuse, thereby reducing redundancy.
OOPs also helps to hide the unnecessary details with the help of Data
Abstraction.
OOPs, are based on a bottom-up approach, unlike the Structural programming
paradigm, which uses a top-down approach.
Polymorphism offers a lot of flexibility in OOPs.

8. Whyis OOPs so popular?


OOPs programming paradigm is considered as a better style of programming. Not
only it helps in writing a complex piece of code easily, but it also allows users to
handle and maintain them easily as well. Not only that, the main pillar of OOPs - Data
Abstraction, Encapsulation, Inheritance, and Polymorphism, makes it easy for
programmers to solve complex scenarios. As a result of these, OOPs is so popular.

Advanced OOPs Interview Questions

Page 9 ©Copyright by Interviewbit


OOPs Interview Questions

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.

10. What is an object?


An object refers to the instance of the class, which contains the instance of the
members and behaviors defined in the class template. In the real world, an object is
an actual entity to which a user interacts, whereas class is just the blueprint for that
object. So the objects consume space and have some characteristic behavior.
For example, a specific car.

11. What is encapsulation?

Page 10 ©Copyright by Interviewbit


OOPs Interview Questions

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.

Encapsulation can also be defined in two different ways:

1)Data hiding: Encapsulation is the process of hiding unwanted information, such as


restricting access to any member of an object.

2)Data binding: Encapsulation is the process of binding the data members and the
methods together as a whole, as a class.

12. What is Polymorphism?


Polymorphism is composed of two words - “poly” which means “many”, and “morph”
which means “shapes”. Therefore Polymorphism refers to something that has many
shapes.

Page 11 ©Copyright by Interviewbit


OOPs Interview Questions

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.

13. What is Compile time Polymorphism and how is it different


from Runtime Polymorphism?

Compile Time Polymorphism: Compile time polymorphism, also known as Static


Polymorphism, refers to the type of Polymorphism that happens at compile time.
What it means is that the compiler decides what shape or value has to be taken by
the entity in the picture.
Example:

Page 12 ©Copyright by Interviewbit


OOPs Interview Questions

// 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));
}
}

Page 13 ©Copyright by Interviewbit


OOPs Interview Questions

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.

Runtime Polymorphism: Runtime polymorphism, also known as Dynamic


Polymorphism, refers to the type of Polymorphism that happens at the run time.
What it means is it can't be decided by the compiler. Therefore what shape or value
has to be taken depends upon the execution. Hence the name Runtime
Polymorphism.
Example:

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.

14. Howdoes C++support Polymorphism?


C++is an Object-oriented programming language and it supports Polymorphism as
well:

Page 14 ©Copyright by Interviewbit


OOPs Interview Questions

Compile Time Polymorphism: C++supports compile-time polymorphism with


the help of features like templates, function overloading, and default
arguments.
Runtime Polymorphism: C++ supports Runtime polymorphism with the help of
features like virtual functions. Virtual functions take the shape of the functions
based on the type of object in reference and are resolved at runtime.

15. What is meant by Inheritance?


The term “inheritance” means “receiving some quality or behavior from a parent to
an offspring.” In object-oriented programming, inheritance is the mechanism by
which an object or class (referred to as a child) is created using the definition of
another object or class (referred to as a parent). Inheritance not only helps to keep
the implementation simpler but also helps to facilitate code reuse.

16. What is Abstraction?


If you are a user, and you have a problem statement, you don't want to know how the
components of the software work, or how it's made. You only want to know how the
software solves your problem. Abstraction is the method of hiding unnecessary
details from the necessary ones. It is one of the main features of OOPs.
For example, consider a car. You only need to know how to run a car, and not how the
wires are connected inside it. This is obtained using Abstraction.

17. Howmuch memory does a class occupy?


Classes do not consume any memory. They are just a blueprint based on which
objects are created. Now when objects are created, they actually initialize the class
members and methods and therefore consume memory.

18. Isit always necessary to create objects from class?


No. An object is necessary to be created if the base class has non-static methods. But
if the class has static methods, then objects don’t need to be created. You can call the
class method directly in this case, using the class name.

19. What is a constructor?

Page 15 ©Copyright by Interviewbit


OOPs Interview Questions

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.

20. What are the various types of constructors in C++?


The most common classification of constructors includes:
Default constructor: The default constructor is the constructor which doesn’t take
any argument. It has no parameters.

Page 16 ©Copyright by Interviewbit


OOPs Interview Questions

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

Copy constructor: A copy constructor is a member function that initializes an object


using another object of the same class.

class ABC
{
int x;

ABC(int y)
{
x = y;
}
// Copy constructor
ABC(ABC abc)
{
x = abc.x;
}
}

21. What is a copy constructor?

Page 17 ©Copyright by Interviewbit


OOPs Interview Questions

Copy Constructor is a type of constructor, whose purpose is to copy an object to


another. What it means is that a copy constructor will clone an object and its values,
into another object, is provided that both the objects are of the same class.

22. What is a destructor?


Contrary to constructors, which initialize objects and specify space for them,
Destructors are also special methods. But destructors free up the resources and
memory occupied by an object. Destructors are automatically called when an object
is being destroyed.

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.

24. Explain Inheritance with an example?


Inheritance is one of the major features of object-oriented programming, by which an
entity inherits some characteristics and behaviors of some other entity and makes
them their own. Inheritance helps to improve and facilitate code reuse.
Let me explain to you with a common example. Let's take three different vehicles - a
car, truck, or bus. These three are entirely different from one another with their own
specific characteristics and behavior. But. in all three, you will find some common
elements, like steering wheel, accelerator, clutch, brakes, etc. Though these
elements are used in different vehicles, still they have their own features which are
common among all vehicles. This is achieved with inheritance. The car, the truck, and
the bus have all inherited the features like steering wheel, accelerator, clutch, brakes,
etc, and used them as their own. Due to this, they did not have to create these
components from scratch, thereby facilitating code reuse.

Page 18 ©Copyright by Interviewbit


OOPs Interview Questions

25. Are there any limitations of Inheritance?


Yes, with more powers comes more complications. Inheritance is a very powerful
feature in OOPs, but it has some limitations too. Inheritance needs more time to
process, as it needs to navigate through multiple classes for its implementation. Also,
the classes involved in Inheritance - the base class and the child class, are very tightly
coupled together. So if one needs to make some changes, they might need to do
nested changes in both classes. Inheritance might be complex for implementation, as
well. So if not correctly implemented, this might lead to unexpected errors or
incorrect outputs.

26. What are the various types of inheritance?


Inflexible Hierarchy: Inheritance establishes a hierarchical relationship between

The various types of inheritance include:


classes, where derived classes inherit properties and behavior from a base class.
However, this hierarchy can become inflexible when changes are required. Modifying
the base class can impact all derived classes, potentially introducing unintended
consequences or requiring extensive modifications throughout the codebase.

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.

Difficulty in Understanding: Inheritance can make the codebase more complex,


especially when there are deep inheritance hierarchies. Understanding the
relationships and behavior of classes becomes more challenging, increasing the
cognitive load for developers and making maintenance and debugging more difficult.

Increased Dependencies: Inheritance introduces dependencies between classes.


Changes in the base class can propagate through the derived classes, requiring careful
consideration and potential modifications in multiple places. This can lead to a higher
degree of interdependence between classes, making it harder to isolate and test
individual components.
Page 19 ©Copyright by Interviewbit
OOPs Interview Questions

27. What is a subclass?


The subclass is a part of Inheritance. The subclass is an entity, which inherits from
another class. It is also known as the child class.

28. Define a superclass?


Superclass is also a part of Inheritance. The superclass is an entity, which allows
subclasses or child classes to inherit from itself.

Page 20 ©Copyright by Interviewbit


OOPs Interview Questions

29. What is an interface?


An interface refers to a special type of class, which contains methods, but not their
definition. Only the declaration of methods is allowed inside an interface. To use an
interface, you cannot create objects. Instead, you need to implement that interface
and define the methods for their implementation.

30. What is meant by static polymorphism?


Static Polymorphism is commonly known as the Compile time polymorphism. Static
polymorphism is the feature by which an object is linked with the respective function
or operator based on the values during the compile time. Static or Compile time
Polymorphism can be achieved through Method overloading or operator
overloading.

31. What is meant by dynamic polymorphism?


Dynamic Polymorphism or Runtime polymorphism refers to the type of
Polymorphism in OOPs, by which the actual implementation of the function is
decided during the runtime or execution. The dynamic or runtime polymorphism can
be achieved with the help of method overriding.

32. What is the difference between overloading and overriding?

Page 21 ©Copyright by Interviewbit


OOPs Interview Questions

Overloading is a compile-time polymorphism feature in which an entity has multiple


implementations with the same name. For example, Method overloading and
Operator overloading.
Whereas Overriding is a runtime polymorphism feature in which an entity has the
same name, but its implementation changes during execution. For example, Method
overriding.
Image

33. Howis data abstraction accomplished?


Data abstraction is accomplished with the help of abstract methods or abstract
classes.

34. What is an abstract class?


An abstract class is a special class containing abstract methods. The significance of
abstract class is that the abstract methods inside it are not implemented and only
declared. So as a result, when a subclass inherits the abstract class and needs to use
its abstract methods, they need to define and implement them.

35. Howis an abstract class different from an interface?


Interface and abstract class both are special types of classes that contain only the
methods declaration and not their implementation. But the interface is entirely
different from an abstract class. The main difference between the two is that, when
an interface is implemented, the subclass must define all its methods and provide its
implementation. Whereas when an abstract class is inherited, the subclass does not
need to provide the definition of its abstract method, until and unless the subclass is
using it.
Also, an abstract class can contain abstract methods as well as non-abstract
methods.

36. What are access specifiers and what is their significance?

Page 22 ©Copyright by Interviewbit


OOPs Interview Questions

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.

37. What is an exception?


An exception can be considered as a special event, which is raised during the
execution of a program at runtime, that brings the execution to a halt. The reason for
the exception is mainly due to a position in the program, where the user wants to do
something for which the program is not specified, like undesirable input.

38. What is meant by exception handling?


No one wants its software to fail or crash. Exceptions are the major reason for
software failure. The exceptions can be handled in the program beforehand and
prevent the execution from stopping. This is known as exception handling.
So exception handling is the mechanism for identifying the undesirable states that
the program can reach and specifying the desirable outcomes of such states.
Try-catch is the most common method used for handling exceptions in the program.

39. What is meant by Garbage Collection in OOPs world?


Object-oriented programming revolves around entities like objects. Each object
consumes memory and there can be multiple objects of a class. So if these objects
and their memories are not handled properly, then it might lead to certain memory-
related errors and the system might fail.
Garbage collection refers to this mechanism of handling the memory in the program.
Through garbage collection, the unwanted memory is freed up by removing the
objects that are no longer needed.

40. Can we run a Java application without implementing the


OOPs concept?
No. Java applications are based on Object-oriented programming models or OOPs
concept, and hence they cannot be implemented without it.

Page 23 ©Copyright by Interviewbit


OOPs Interview Questions

However, on the other hand, C++can be implemented without OOPs, as it also


supports the C-like structural programming model.

OOPs Coding Problems


41. What is the output of the below code?

#include<iostream>

using namespace std;


class BaseClass1 {
public:
BaseClass1()
{ cout << " BaseClass1 constructor called" << endl; }
};

class BaseClass2 {
public:
BaseClass2()
{ cout << "BaseClass2 constructor called" << endl; }
};

class DerivedClass: public BaseClass1, public BaseClass2 {


public:
DerivedClass()
{ cout << "DerivedClass constructor called" << endl; }
};

int main()
{
DerivedClass derived_class;
return 0;
}

Output:

BaseClass1 constructor called


BaseClass2 constructor called
DerivedClass constructor called

Page 24 ©Copyright by Interviewbit


OOPs Interview Questions

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.

42. What will be the output of the below code?

class Scaler
{
static int i;

static
{
System.out.println(“a”);

i = 100;
}
}

public class StaticBlock


{
static
{
System.out.println(“b”);
}

public static void main(String[] args)


{
System.out.println(“c”);

System.out.println(Scaler.i);
}
}

Output:

b
c
a
100

Page 25 ©Copyright by Interviewbit


OOPs Interview Questions

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.

43. Predict the output?

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

int main() { This is a conversion operator


ClassB b(10);
g(b);
g(20);
getchar();
return 0;
}

Output:

i = 10
i = 20

Page 26 ©Copyright by Interviewbit


OOPs Interview Questions

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.

44. What will be the output in belowcode?

public class Demo{


public static void main(String[] arr){
System.out.println(“Main1”);
}
public static void main(String arr){
System.out.println(“Main2”);
}
}

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.

45. Predict the output?

Page 27 ©Copyright by Interviewbit


OOPs Interview Questions

#include<iostream>
using namespace std;

class BaseClass{
int arr[10];
};

class DerivedBaseClass1: public BaseClass { };

class DerivedBaseClass2: public BaseClass { };

class DerivedClass: public DerivedBaseClass1, public DerivedBaseClass2{};

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.

46. What is the output of the below program?

Page 28 ©Copyright by Interviewbit


OOPs Interview Questions

#include<iostream>

using namespace std;


class A {
public:
void print()
{ cout <<" Inside A::"; }
};

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

Page 29 ©Copyright by Interviewbit

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy