20 Oops with C++ Interview Questions and Answers for Fresher and Experienced Professionals

1. Why do we need Object Oriented Programming?
2. What is Object Oriented Programming?
3. What are the characteristics of Object-Oriented Programming?
4. What are Classes and Objects?
5. What is inheritance? etc.

1. Why do we need Object Oriented Programming?

Object Oriented Programming was developed because of the limitations discovered in the earlier approaches to programming. Before OOP, there were Procedural languages which include C, Pascal, FORTRAN etc.

In a procedural program, program code is written in a top down approach and the program is divided into functions or procedures. There are also two kinds of data which are local data and global data. A local data is defined in a function and is accessible only by that function and global data is accessible by any function in a program. This is a very simple style of programming and is very efficient for small programs. However, there are two major limitations with procedural languages.

First is unrestricted access, as a program grows larger, there are many functions and global data items which leads to a larger number of connections between them, which is not a good practice in programming. For example, it could make a program difficult to be modified. Suppose, when a global data item’s type is changed from integer to float, all the functions that access that particular global data item must be modified to work with a float data item and it’s not an easy job when there are many functions in the program.

2. What is Object Oriented Programming?

Object Oriented Programming is a style of programming where data items and functions that operate on those data items are group into a unit, known as an object. In C++, the data items  are called as data members and the functions are called as member functions.

In OOP, a program typically consists of a number of objects, which communicate with each other by calling each other member functions.

Programming languages that support Object Oriented Paradigm are C++, Java, C#, Python, PHP and many more.

3. What are the characteristics of Object-Oriented Programming?

The Characteristics of Object-Oriented Programming are as follows

- Class
- Objects
- Inheritance
- Polymorphism
- Abstraction
- Encapsulation

4. What are Classes and Objects?

In OOP, a Class is considered as a plan or the blueprint of an object. A Class specifies what data and functions will be included in that object. A Class must always be defined before the creation of an object and by defining the class does not automatically create the object.

An object is an instance of a class, in the same way a rose is an instance of a flower. An object embodies the exact characteristics of the class and when an object is created, a space is reserved for it in the memory.

Since an object contains data (state) and functions(behaviors), there is a close match between Objects in OOP and Objects in real life and this close similarity revolutionize the designs of programs. For example, let’s take a Car, it has properties such as model, color, brand, year etc. and it also has different functions such as to start a car, drive the car, stop the car. This can be represented in a program with the help of objects as follows,

Example:


class Car {             // create a class
                public:    // Access specifier
                        string brand;    // data members declaration
                        string model;
                        string colour;
                        int year;
                        void startaCar();  // member functions declaration
                        void driveaCar();
                        void stopaCar();

                        void startaCar() { // member functions defined in a class
                                   cout<< ”start the car”;
                        }
                        void driveaCar() {
                                 cout<< “driveaCar”;
                        }
                        void stopaCar() {
                                 cout<< “stopaCar”;
                        }
                   };

void main() {

                Car car1;     // create an object named as car1 of Car
                car1.brand = ”Mercedes”;  // assign values to data members
                car1.model = “XLS”;
                car1.colour = “white”;
                car1.year = “2008”;
                car1.startaCar();   // call a member function

                car car2 // create an object named as car2 of Car
                car2.brand = ”Audi”;
                car2.model = “RR”;
                car2.colour = “Orange”;
                car2.year = “2013”
                car2.driveaCar();
}



5. What is inheritance?

Inheritance is one of the core concepts of OOP. Inheritance is a mechanism where one class acquires the attributes and member functions of another class. The class which is inherited from is known as a base class whereas the class that inherits from the base class is known as derived class. Derive classes can inherit the characteristics of the base class and also add new ones of their own.

To inherit from another class, use “ : “ symbol.

Example:


class Vehicle{
                public:
                        string brand = "BMW";
                        void message() {
                                  cout<< "Welcome \n" ;
                        }
};

// Derived class
class Car: public Vehicle {
                public:
                string model = "i8";
};

int main() {
                Car myCar;
                myCar.message();
                cout<                 return 0;
}



Output:
Welcome
BMW i8

6. What is Polymorphism?

In simple terms Polymorphism means more than one form which means that an entity (function or operator) behaves differently in different situations. For example, a man possesses different behavior in different situations. He can act at the same time like a father, a husband or an employee.

In C++ we can implement polymorphism in the following ways.

- Function overloading
- Operator overloading
- Function overriding

i) Function overloading: In C++, you can have two or more functions with the same name but each function with different parameters. And depending on the number of arguments or type of arguments that is supplied when calling a function, the function with matching parameters is called. Function overloading is a type of compile time polymorphism.

ii) Operator Overloading: In C++, we can change the behaviour of an operator in a program. We can overload an operator only when we are operating on user-defined types such as objects and structures, we cannot use operator overloading on basic types such as int, double.

Basically, operator overloading is same as function overloading, where different operator function has the same symbol but different operands and depending on the operands different operator functions are executed. Operator overloading is also an example of compile time polymorphism.

iii) Function overriding: Function overriding is like creating a new version of an old function in the child class. In C++ inheritance, you can have a function with the same name in both the base class and the derived class. However, when we call that function using the object of the derived class, the function in the derived class is executed instead of the one in the base class. This is known as function overriding. Function overriding is a run time polymorphism.

7. What is the difference between Compile time polymorphism and Run time polymorphism?



8. What is abstraction in OOP?

In OOP, Data abstraction or abstraction means displaying only essential information and hiding away the background details.

Data abstraction provides an interface to the user while hiding away the implementation details of the program.

One example of data abstraction in C++ is the use of header files. For example log() function that returns the natural logarithm of a number is present in the header file <cmath>. In the program, we don’t have to know the algorithm of calculating the logarithm of a number, we simply call the log() function with an argument and the logarithm of that argument is returned. Thus, the details of the implementation are hidden.

9. What is Encapsulation?

Encapsulation is one of the key features of object-oriented programming. It is a process of grouping similar code in one place i.e related data members and member functions are grouped together in a single class. Encapsulation makes our code cleaner and easy to read and provide better control for the modification of our data items.

For example, to calculate area of a rectangle we need three things, length of a rectangle, breadth of a rectangle and a function to calculate the area of a rectangle. All these related members are then group together into a single class where you can conceptualize better and read easily, as follows

Example:


Class Rectangle {
                public:
                int length;
                int breadth;
                int getArea() {
                        Return length * breadth;
                }
};


10. What is Data hiding in C++?

Data hiding means that data are concealed within a class so that it prevents accidental accessing by functions outside the class.  The primary mechanism for hiding data is to put the data in the class and declare them as private. Private data and functions can only be accessed from within the same class. Data hiding is designed to protect programmers from honest mistakes.

11. What is the difference between C and C++?

Few differences of C and C++ are as follows


12. What are the access specifiers in C++?

Access specifiers decide how the members (data members and member functions) of a class can be accessed by different members outside the class. In C++ there are three types of access specifiers.

public: The members which are declared as public can be accessed from outside the class.

private: Here, the members declared as private can only be accessed by member functions in the same class.

protected: Here, the members declared as protected cannot be accessed from outside the class, however they can be accessed in inherited classes.

13. What are Structures in C++?

A Structure is collection of variables of different datatypes. A Structure is a specification for a new data type which is user defined. A Structure is defined using the struct keyword as follows,

Example:


             struct Citizen //  define a structure name citizen
             {
                    char name[30]; // variables
                    int age;
                    char job;
             }



The above structure definition serves only as the blueprint for the creation of the variables of type citizen and does not actually create the variables i.e. it does not reserve space for them in the memory.

To actually create the variables i.e. for the variables to exist in the memory, you have to defined in the main() as follows,

Citizen citizen1;

The above statement will create a variable citizen1 of type Citizen.

14. What is the difference between structures and classes?

Structures are very similar to classes since a structure can also contain functions inside it, therefore a structure group together both data and functions just like a class but the only difference between them is that the data items inside a structure are public by default whereas the data items inside a class are private by default.

However, in most situations, programmers use structures to group only data and classes to group both data and functions.

15. What are constructors in C++?

A constructor is a specialized member function that is called automatically whenever an object is created. A constructor is primarily used to initialized data members of an object.

Rules for defining a constructor:

First, a constructor must have the same name as the class of which they are members. This is one way to let the compiler knows that it is a constructor.

Second, a constructor must not have any return type.

Example:


         class  Shoes {
                double size;
                public:
                Shoes() {       // a constructor
                        size = 7;
                        cout<<“ Shoe size: “<< size;
                }
          };

         int main() {
                Shoes shoe1;
                return 0;
         }


Output:
Shoe size: 7

16. What are the types of constructors in C++?

There are three types of constructors

Default constructor: A constructor with no parameters is known as a default constructor.

Example:


class  Shoes {
                double size;
                public:
                Shoes() {       // a constructor
                        size = 7;
                        cout<<“ Shoe size: “<< size;
                }
};

int main() {
            Shoes shoe1;
            return 0;
}


Parameterized constructor: A constructor that has parameters are known as parameterized constructor.

Example:


class Shoes {
            double size;
            public:
            Shoes(double sizes) {      // parameterized constructor
                     size = sizes;
            }
};

int main() {
             Shoes shoe1(7);    // initialized shoe1 with value 7
             return 0
}


Copy constructor: It is a special constructor that creates a new object as a copy of an existing object.

Example:


class Shoes {
        double size;
        public:
        Shoes(double sizes) {      // parameterized constructor
                    size = sizes;
        }
        Shoes(Shoes &obj) { // copy constructor with Shoes object as parameter
                   size = obj.size;
        }
};

int main() {
              Shoes shoe1(7);
              Shoes shoe2=shoe1;      // copy data of shoe1 to shoe2
              return 0;
}


17. What are destructors?

Destructors is a special member function that is invoked automatically when an object is destroyed.

Destructors must have the same name as its class, does not have any arguments and return type and is preceded by a ‘ ~ ‘ tilde.

The most common use of destructors is to deallocate memory that was allocated for the object.

Example:


Class Print {
        Public:
             Int data;
        Public
             Print() {
                   // constructor
             }
             ~Print() { // destructor
             }
};


18. What is a namespace in C++?

Namespace is a declarative region that provide scope to identifiers inside it. It is a method to prevent name conflicts of variables, functions in a program. In big projects, there is a big chance that there may be two or more variables or functions with the same name and this will result in an error when compiled. To resolve this issue, namespace is introduced in C++.

In the program below through the use of namespace, we can use the same variable name x and function name printX() in the same program.

Example:


namespace A
{
        int x=4;
        void printX() {
             cout<<x<<endl;
        }
}

namespace B
{
        int x=13;
        void printX() {
                  cout<<x<<endl;
        }
}


19. What is the meaning of “using namespace std” at the beginning of a C++ program?

std is a special namespace and is short form for standard. Using the namespace std means that you are going to use classes or functions from the std namespace, and you don’t have to explicitly call the std namespace every time you want to access its members.

In the header file <iostream> the function such as cin, cout are defined in the std namespace, hence we must mention the std namespace in the beginning of the program, otherwise we have to invoked explicitly every time we need to use cin and cout.

Example:


Using namespace std

#include <iostream>
using namespace std
{
cout<<“ hello “ <<endl;
cin>> var;
}

Without namespace std

#include <iostream>

std::cout<<” hello “<<endl; // prefix std has to be added every time
std::cin>>var;


20. What are Inline functions?

In C++, while compiling a program, if a function is declared as inline, the actual code of the function is inserted in the location of the inline function, instead of jumping to the function which is done in normal member functions. Inline function speeds up the execution process of the function.

To define an inline function, you need to specify the keyword inline as before the function definition as follows

Example:


#include <iostream>
Using namespace std;

inline void displaynumber(int num) {         // inline function
              cout<<num<<endl;
}  

int main() {
            displayNum(5);
            return 0;
}