C++ Interview Questions in Java

List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

C++ Interview Questions in Java

Question 1.
What is C++?
Answer:
Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language while simplifying memory management and adding several features – including a new data type known as a class (you will learn more about these later) – to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.

Question 2.
What Is Object-Oriented Programming?
Answer:
Object-Oriented Programming (OOP) is a programming paradigm where the complete software operates as a bunch of objects talking to each other. An object is a collection of data and methods that operate on its data.

Question 3.
Why OOP?
Answer:
The main advantage of OOP is better manageable code that covers the following.

  1. The overall understanding of the software is increased as the distance between the language spoken by developers and that spoken by users.
  2. Object orientation eases maintenance by the use of encapsulation. One can easily change the underlying representation by keeping the methods the same. OOP paradigm is mainly useful for relatively big software. See this for a complete example that shows the advantages of OOP over procedural programming.

Question 4.
What are the main features of OOP?
Answer:

  • Encapsulation
  • Polymorphism
  • Inheritance

Question 5.
What is encapsulation?
Answer:
Encapsulation is referred to one of the following two notions.

  1. Data hiding: A language feature to restrict access to members of an object. For example, private and protected members in C++.
  2. Bundling of data and methods together: Data and methods that operate on that data are bundled together.

Question 6.
What is Polymorphism? How is it supported by C++?
Answer:
Polymorphism means that some code or operations or objects behave differently in different contexts. In C++, the following features support polymorphism.
• Compile Time Polymorphism: Compile time polymorphism means the compiler knows which function should be called when a polymorphic call is made. C++ supports compiler time polymorphism by supporting features like templates, function overloading, and default arguments.

• Run Time Polymorphism: Run time polymorphism is supported by virtual functions. The idea is virtual functions are called according to the type of the object pointed or referred to, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime.

Question 7.
What is Abstraction?
Answer:
The first thing with which one is confronted when writing programs is the problem. Typically we are confronted with “real-life” problems and we want to make life easier by providing a program for the problem. However, real-life problems are nebulous and the first thing we have to do is to try to understand the problem to separate necessary from unnecessary details: We try to obtain our own abstract view, or model, of the problem. This process of modeling is called abstraction

Question 8.
What is the difference between realloc( ) and free()?
Answer:
The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

Question 9.
What is function overloading and operator overloading?
Answer:
Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types, and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn’t add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

Question 10.
What is the difference between declaration and definition?
Answer:
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.

E.g.: void stars ( ) //function declaration 
The definition contains the actual implementation.
E.g.: void stars ( ) // declaratory
{
for(int j=10; j > =0; j - - ) //function body 
cout << *; 
cout << end1; }

Question 11.
What are the differences between references and pointers?
Answer:
Bothreferencesandpointerscanbeusedtochangelocalvariablesofonefunction inside another function. Bothofthemcanalsobeusedtosavecopyingofbig objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers.
References are less powerful than pointers

  1. Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
  2. References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
  3. A reference must be initialized when declared. There is no such restriction with pointers

Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java are the main reason Java doesn’t need pointers. References are safer and easier to use:

  1. Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location.
  2. Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. the operator is needed only at the time of declaration. Also, members of an object reference can be accessed with a dot operator, unlike pointers where an arrow operator (->) is needed to access members.

Question 12.
Explain Copy Constructor.
Answer:
It is a constructor which initializes its object member variable with another object of the same class. If you don’t implement a copy constructor in your class, the compiler automatically does it.

Question 13.
When do you call copy constructors?
Answer:
Copy constructors are called in these situations:

  • when the compiler generates a temporary object
  • when a function returns an object of that class by value
  • when the object of that class is passed by value as an argument to a function
  • when you construct an object based on another object of the same class

Question 14.
Differentiate between late binding and early binding. What are the advantages of early binding?
Answer:

  • Late binding refers to function calls that are not resolved until run time while early binding refers to the events that occur at compile time.
  • Late binding occurs through virtual functions while early binding takes place when all the information needed to call a function is known at the time of compiling. Early binding increases the efficiency. Some of the examples of early binding are normal function calls, overloaded function calls, and overloaded operators, etc.

Question 15.
What are the advantages of inheritance?
Answer:
It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional.

Question 16.
What do you mean by inline function?
Answer:
The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application’s performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.

Question 17.
What is public, protected, private?
Answer:
Public, protected, and private are three access specifiers in C++. Public data members and member functions are accessible outside the class. Protected data members and member functions are only available to derived classes. Private data members and member functions can’t be accessed outside the class. However, there is an exception that can be using friend classes.
Write a function that swaps the values of two integers, using int* as the argument type.

void swap(int* a, int*b) { 
int t; 
t = *a;
*a = *b;
*b = t;
}

Question 18.
What are virtual constructors/destructors?
Answer:
Answer 1 Virtual destructors:
If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.

There is a simple solution to this problem that declares a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.
Answer 2
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor.

This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

Question 19.
Explain storage qualifiers in C++.
Answer:

  1. Const – This variable means that if the memory is initialized once, it should not be altered by a program.
  2. Volatile – This variable means that the value in the memory location can be altered even though nothing in the program code modifies the contents.
  3. Mutable – This variable means that a particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

Question 20.
What is the type of “this” pointer? When does it get created?
Answer:
It is a constant pointer type. It gets created when a non-static member function of a class is called.

Question 21.
How would you differentiate between pre and post-increment operators while overloading?
Answer:
Mentioning the keyword int as the second parameter in the post-increment form of the operator++0 helps distinguish between the two forms.

Question 22.
What are the advantages of inheritance?
Answer:

  • It permits code reusability.
  • Reusability saves time in program development.
  • It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional.

Question 23.
What is a template?
Answer:
Templates allow the creation of generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until a certain point, they fulfill the functionality of a macro. Its prototype is any of the two following ones:

template <class indetifier> function_declaration; 
template type name indetifier> function_declaration;

The only difference between both prototypes is the use of keyword class or type name, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.

Question 24.
Define a constructor – What it is and how it might be called (2 methods).
Answer:
Answer 1
Constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized. Ways of calling constructor:

  1. Implicitly: automatically by complier when an object is created.
  2. Calling the constructors explicitly is possible, but it makes the code unverifiable.

Answer 2

class Point2D{ 
int x; int y;
public Point2DO : x(0) , y(0) {} //default (no argument) constructor
};
main( ){
Point2D MyPoint; // implicit Constructor call, in order to allocate 
memory on stack, the default constructor is implicitly called.
Point2D * pPoint = new Point2D(); // Explicit constructor call, 
In order to allocate memory on HEAP we call the default constructor.
we have two pairs: new( ) and delete( ) and another pair : alloc( ) and free( ).

Question 25.
Explain differences between eg. new() and malloc()
Answer:
Answer 1:

  1. “new and delete” are preprocessors while “malloc( ) and ffee( )” are functions, [we dont use brackets will calling new or delete],
  2. no need of allocate the memory while using “new” but in “malloc( )” we have to use “sizeof( )”.
  3. “new” will initlize. the new rnemoiy to 0 but “malloc( )” gives random value in the new alloted memory location [better to use calloc( )]

Answer 2:
new( ) allocates continous space for the object instace mallocO allocates distributed space.
new( ) is castless, meaning that allocates memory for this specific type, mallocO, callocO allocate space for void * that is cated to the specific class type pointer.

Question 26.
What is the difference between class and structure?
Answer:
Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private.

Question 27.
WhatisRTTI?
Answer:
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many Interview Questions – Homegrown versions with a solid, consistent approach.

Question 28.
W/hat is encapsulation?
Answer:
Packaging an object’s variables within its methods is called encapsulation.

Question 29.
W/hat is an object?
Answer:
Object is a software bundle of variables and related methods. Objects have state and behavior.

Question 30.
W/hat do you mean by inheritance?
Answer:
Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

Question 31.
Wffiat is namespace?
Answer:
Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:

namespace identifier { namespace-body }

Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example: namespace general {int a, b;} In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:

general::a general::b

The functionality of namespaces is especially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error.

Question 32.
What is virtual class and friend class?
Answer:
Friend classes are used when two or more classes are designed to work .together and need access to each other’s implementation in ways that the rest of the world shouldn’t be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than mainO has.

Question 33.
WTiat is the difference between an object and a class?
Answer:
Classes and objects are separate but related concepts. Every object belongs
to a class and every class contains one or more related objects.

  • A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don’t change.
  • The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
  • An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

Question 34.
What is a class?
Answer:
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.

Question 35.
WTiat is friend function?
Answer:
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

Question 36.
WTiich recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array?
Answer:
Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in 0(n log n) time.

Question 37.
What is abstraction?
Answer:
Abstraction is of the process of hiding unwanted details from the user.

Question 38.
What are virtual functions?
Answer:
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure 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. This allows algorithms in the base class to be replaced in the derived class, even if users don’t know about the derived class.

Question 39.
What is a scope resolution operator?
Answer:
A scope resolution operator (::), can be used to define the member functions of a class outside the class.

Question 40.
What do you mean by pure virtual functions?
Answer:
Pure virtual function in object oriented programming is called as virtual method that acts as a function allowing its behavior to be overridden by the class that is inheriting the pure virtual function with the same signature. This is used in case of polymorphism. It is used when a base class is being driven by the derived class and an object of the derived class referred as base or derived class type. When a derived class overrides the base class method then the output or the behavior will be called as ambiguous. To use the virtual function a virtual keyword is used. This allows the function to be defined in every derived class and use the functionality of it.

Question 40.
What is polymorphism? Explain with an example?
Answer:
“Poly” means“many” and“morph” means“form”. Polymorphismisthe ability of anobject(orreference)toassume(bereplacedby)orbecomemanydifferentformsofobject. Example: function overloading, function overriding, virtual functions. Another example can be a plus “+’ sign, used for adding two integers or for using it to concatenate two strings.

Question 41.
What is a conversion constructor?
Answer:
A constructor that accepts one argument of a different type.

Question 42.
What is the difference between a copy constructor and an overloaded assignment operator?
Answer:
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Question 43.
Explain the ISA and HASA class relationships. How would you implement each in a class design?
Answer:
A specialized class “is” a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee “has” a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

Question 44.
What is the Standard Template Library (STL)?
Answer:
A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.

Question 45.
In C++, what is the difference between method overloading and method overriding?
Answer:
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

Question 46.
What is a modifier?
Answer:
A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ‘mutators’.

Question 47.
What is an accessor?
Answer:
An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations

Question 48.
Differentiate between a template class and class template.
Answer:
Template class: A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates. Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.

Question 49.
Explain Stack & Heap Objects
Answer:
The memory a program uses is divided into four areas:

  • The code area – this is where the compiled program sits in memory.
  • The global area – the place where global variables are stored.
  • The heap – the place where dynamically allocated variables are allocated from.
  • The stack -the place where parameters and local variables are allocated from.

Question 50.
Explain deep copy and a shallow copy
Answer:

  • Deep copy – It involves using the contents of one object to create another instance of the same class. Here, the two objects may contain the same information but the target object will have its own buffers and resources. The destruction of either object will not affect the remaining object.
  • Shallow copy -It involves copying the contents of one object into another instance of the same class. This creates a mirror image. The two objects share the same externally contained contents of the other object to be unpredictable. This happens because of the straight copying of references and pointers.

Question 51.
Explain virtual class and friend class
Answer:
a. Virtual Base Class:
It is used in context of multiple inheritances in C++.
If you want to derive two classes from a class, and further derive one class from the two classes in the second level, you need to declare the uppermost base class as ‘virtual’ in the inherited classes. This prevents multiple copies of the uppermost base class data members when an object of the class at the third level of hierarchy is created.

b. Friend class:
When a class declares another class as its friend, it is giving complete access to all its data and methods including private and protected data and methods to the friend class member methods.
Friendship is not necessarily bi-directional. If A declares B as its friend it does not imply that A can access private data of B. It only means that B can access all data of A.
Explain the of scope resolution operator A scope resolution operator (::) is used to define the member functions of a class outside the class.
Mostly, a scope resolution operator is required when a data member is redefined by a derived class or an overridden method of the derived class wants to call the base class version of the same method.

Question 52.
What are virtual functions?
Answer:
Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual. Following things are necessary to write a C++ program with runtime polymorphism use of virtual functions)

  1. A base class and a derived class.
  2. A function with same name in base class and derived class.
  3. A pointer or reference of base class type pointing or referring to an object of derived class.

Question 53.
What are the features that are provided to make a program modular?
Answer:
To create a program requires self sufficient resources, the way to make a piece of code modular so that it can be handled properly. This shows the relationship between different objects or in between the same objects. Different functions have to be used to keep the code different from the data provided. Object oriented programming allows creating a modular approach to make it more abstract and create the interactions between them. The features that are being provided in object oriented programming are:

• Encapsulation: it deals with the grouping of data and functions together at one place or it can be said in an object that defines the interface of their interaction and the relationship between them.
• Inheritance: it deals with the relationship that exists between the parent and child classes. A child can inherit the properties of the parent and it remains helpful in creating a hierarchy in the system to keep things more modular.
• Polymorphism: is a feature that deals with different values that can be used by only one function. It doesn’t have to re-create the same function again and again for different values but, it uses the same function to call different data types.