Share this:

Top 82 C++ Questions and Answers for Job Interview :

 

1) What are the differences between C and C++?

Answer: C is a procedural oriented programming language whereas C++ supports both procedural and Object-Oriented programming. C++ is a kind of superset of C. Since C++ supports object-oriented programming, it supports features like function overloading, templates, inheritance, virtual functions, friend functions however C is unable to perform these functions.

 

2) What is OOP?

Answer: Object-oriented programming (OOP) refers to a type of computer programming  in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure.

In this way, the data structure becomes an object that includes both data and functions. In addition, programmers can create relationships between one object and another. For example, objects can inherit characteristics from other objects.

 

3) What are the Comments in C++?

Answer: Comments are portions of the code ignored by the compiler which allow the user to make simple notes in the relevant areas of the source code. Comments come either in block form or as single lines.

 

4) What are Vectors?

Answer: Vectors are sequence containers representing arrays that can change in size.
Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

 

5) Difference between Declaration and Definition of a variable.

Answer: Declaration of variable mean to tell compiler there is a var\funct\struct of particular data type.
Definition of variable mean asking compiler to allocate memory to variable or define storage for that variable. You can define a variable only one time but you can declare it as many times you want.

 

6) What is Local and Global scope of a variable.

Answer: Global variables are declared outside any function, and they can be accessed (used) on any function in the program. Local variables are declared inside a function, and can be used only inside that function.  The scope of a variable refers to where is a variable visible or accessible.

 

7) What is a Constant?

Answer: A constant, like a variable, is a memory location where a value can be stored. Unlike variables, constants never change in value.

Examples of Constants:

75 //integer (decimal)
0113 //octal
0x4b //hexadecimal
3.142 //floating point
‘c’ //character constant
“Hello, World” //string constant

 

8) What is the difference between equal to (==) and Assignment Operator (=)?

Answer: The ‘=’ is the so-called assignment operator and is used to assign the result of the expression on the right side of the operator to the variable on the left side. The ‘==’ is the so-called equality comparison operator and is used to check whether the two expressions on both sides are equal or not.

 

9) What are the various Arithmetic Operators in C++?

Answer: C++ supports the following arithmetic operators:

  • + addition
  • – subtraction
  • * multiplication
  • / division
  • % module

 

10) State the difference between Pre and Post Increment/Decrement Operations.

Answer:Pre increment operator is used to increment variable value by 1 before assigning the value to the variable. Post increment operator is used to increment variable value by 1 after assigning the value to the variable.

 

11) What is this pointer?

Answer: The member functions of every object have access to a pointer named this, which points to the object itself. When we call a member function, it comes into existence with the values of this set to the address of the object for which it was called. This pointer is the default hidden and implicit argument of any non-static member function.

 

12) What are C++ access specifiers?

Answer: C++ access specifiers are used for determining or setting the boundary for the availability of class members (data members and member functions) beyond that class.

For example, the class members are grouped into sections, private protected and public. These keywords are called access specifiers which define the accessibility or visibility level of class members.

By default, the class members are private. So, if the visibility labels are missing then by default all the class members are private.

  • Private: Members declared as private are accessible only within the same class and they cannot be accessed outside the class they are declared. Child classes are also not allowed to access private members of parent.
  • Public: Members declared as public are accessible from anywhere.
  • Protected: Only the class and its child classes can access protected members.

 

13) What is Function overloading?

Answer: Function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

 

14) What is Operator Overloading?

Answer:In programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.

In this case, the addition operator is overloaded to allow addition on a user-defined type “Time” (in C++):

Time operator+(const Time& lhs, const Time& rhs)

{

Time temp = lhs;

temp.seconds += rhs.seconds;

temp.minutes += temp.seconds / 60;

temp.seconds %= 60;

temp.minutes += rhs.minutes;

temp.hours += temp.minutes / 60;

temp.minutes %= 60;

temp.hours += rhs.hours;

return temp;

}

Addition is a binary operation, which means it has two operands. In C++, the arguments being passed are the operands, and the temp object is the returned value.

15) What is Copy Constructor?

Answer: Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type. It is usually of the form X (X&), where X is the class name. The compiler provides a default Copy Constructor to all the classes.

16) What Is Inheritance?

Answer: In object-oriented programming, inheritance is the concept that when a class of objects is defined, any subclass that is defined can inherit the definitions of one or more general classes. This means for the programmer that an object in a subclass need not carry its own definition of data and methods that are generic to the class (or classes) of which it is a part. This not only speeds up program development; it also ensures an inherent validity to the defined subclass object (what works and is consistent about the class will also work for the subclass).

17) What is Static Member?

Answer:When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. Astatic member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.

18) What is the difference between #import and #include?

Answer:#include  directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result, the program size increases, thus wasting memory and processor’stime.
#import statement makes the JVM go to the Java standard library, execute the code there, and substitute the result into the program. Here, no code is copied and hence no waste of memory or processor’s time. Hence import is an efficient mechanism than #include.

19) What is a static element?

Answer:It is a variable which is declared with the static keyword, it is also known as class member, thus only single copy of the variable creates for all objects.

Any changes in the static data member through one-member function will reflect in all other object’s member functions.

Declaration

static datatype member name;

20) What is a point in c++?

Answer:  point is most often a reference to a method or property of an object in OOP. The relationship between an object, attributes, and methods is indicated by a dot (“. “) Established between them.

 

21) WHAT IS USE OF NEW FUNCTION?

Answer: New is used to allocate memory for a C++ class object, the object’s constructor is called after the memory is allocated.

 

22) WHAT IS USE OF MALLOC FUNCTION?

Answer: The malloc () function in C++ allocates a block of uninitialized memory and returns a void pointer to the first byte of the allocated memory block if the allocation succeeds.

 

23) What is A DELEGATE?

Answer:delegate is a class that wraps a pointer or reference to an object instance, a member method of that object’s class to be called on that object instance, and provides a method to trigger that call.

 

24) What is mutator method?

Answer:mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter (also known as an accessor), which returns the value of the private member variable.

The mutator method is most often used in object-oriented programming, in keeping with the principle of encapsulation. According to this principle, member variables of a class are made private to hide and protect them from other code, and can only be modified by a public member function (the mutator method), which takes the desired new value as a parameter, optionally validates it, and modifies the private member variable.

 

25) What is encapsulation?

Answer: Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Other way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.

 

26) What is polymorphism?

Answer: The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

 

27) What is abstraction? How does it differ from encapsulation?

Answer: Data abstraction refers to providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. Encapsulation can be understood as hiding properties and methods from the outside world. The class is the best example of C ++ encapsulation.

28) What are built-in functions?

Answer: Built in or inbuilt function are that type of functions which are already defined or created in a program or in programming framework . User don’t need to create these types of functions. User or developer can directly use built in function by only call it.

 

29) What is a pointer?

Answer: Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.

 

30) What is a linked list?

Answer: linked list is a sequence of data structures, which are connected together via linksLinked List is a sequence of links which contains items. Each link contains a connection to another link.

 

31) What is a virtual function?

Answer: virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.

32) What is the use of default constructor?

Answer: A constructor without parameters is known as default constructor. Constructors are mostly used to initialize the instance variables. Specifically, using default constructors the instance variables will be initialized with fixed values for all objects.

33) Explain container class.

-Class to hold objects in memory or external storage. It acts as a generic holder.
– It has a predefined behavior and a known interface.
– It is used to hide the topology used for maintaining the list of objects in memory.
– The container class can be of two types:
1. Heterogeneous container: Here the container class contains a group of mixed objects
2. Homogeneous container: Here the container contains all the same objects.

 

34) What is namespace?

Answer: Namespace is a feature added in C++ and not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc.) inside it.

35) Explain public, protected, private in C++?

Answer: Public Specifier
Public class members and functions can be used from outside of a class by any function or other classes. You can access public data members or function directly by using dot operator (.) or (arrow operator-> with pointers).
Protected Specifier
Protected class members and functions can be used inside its class. Protected members and functions cannot be accessed from other classes directly. Additionally, protected access specifier allows friend functions and classes to access these data members and functions. Protected data members and functions can be used by the class derived from this class.

Private Specifier
Private class members and functions can be used only inside of class and by friend functions and classes

 

36) When do you call copy constructors?

Answer:Following situations in c++ where the copy constructor would be invoked:

  1. when an existing object is assigned an object of its own class

MyClass A,B;A = new MyClass();B=A; //copy constructor called

  1. if a functions receives as argument, passed by value, an object of a class

void foo(MyClass a);foo(a); //copy constructor invoked

  1. when a function returns (by value) an object of the class

MyClass foo ()   {      MyClass temp;      ….      return temp; //copy constructor called   }

37) Explain storage qualifiers in C++.

Answer: 1. CONST KEYWORD:

  • Constants are also like normal variables. But, only difference is, their values can’t be modified by the program once they are defined.
  • They refer to fixed values. They are also called as literals.
  • They may be belonging to any of the data type.
  • Syntax:
    const data_type variable_name; (or) const data_type *variable_name;
  • Please refer C – Constantstopic in this tutorial for more details on const keyword.

2. VOLATILE KEYWORD:

  • When a variable is defined as volatile, the program may not change the value of the variable explicitly.
  • But these variable values might keep on changing without any explicit assignment by the program. These types of qualifiers are called volatile.
  • For example, if global variable’s address is passed to clock routine of the operating system to store the system time, the value in this address keep on changing without any assignment by the program. These variables are named as volatile variable.
  • Syntax:
    volatile data_type variable_name; (or) volatile data_type *variable_name;

 

38) Explain dangling pointer.

Answer: Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.

39) What is a pdb file?

Answer:  A program database (PDB) file contains debugging and project state information that allows incremental linking of a Debug configuration of the program. This file is created when you compile a C/C++ program with /ZI or /Zi or a Visual Basic/C#/JScript .NET program with /debug.

40) What are Stacks?

Answer:A stack is a conceptual structure consisting of a set of homogeneous elements and is based on the principle of last in first out (LIFO). It is a commonly used abstract data type with two major operations, namely push and pop. Push and pop are carried out on the topmost element, which is the item most recently added to the stack. The push operation adds an element to the stack while the pop operation removes an element from the top position. The stack concept is used in programming and memory organization in computers.

41) Explain STL.

Answer: The Standard Template Library (STL) is a software library for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called algorithmscontainersfunctions, and iterators.[1]

The STL provides a set of common classes for C++, such as containers and associative arrays, that can be used with any built-in type and with any user-defined type that supports some elementary operations (such as copying and assignment). STL algorithms are independent of containers, which significantly reduces the complexity of the library.

42) What are the different types of STL containers?

Answer: Following are the 3 types of STL containers:
1. Adaptive containers: For e.g. queue, stack
2. Associative containers: For e.g. set, map
3. Sequence containers: For e.g. vector, deque

43) WHAT IS REALLOC FUNCTION?

Answer: Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with a call to free or realloc. Otherwise, the results are undefined.

The reallocation is done by either:

  1. a) expanding or contracting the existing area pointed to by ptr, if possible. The contents of the area remain unchanged up to the lesser of the new and old sizes. If the area is expanded, the contents of the new part of the array are undefined.
  2. b) allocating a new memory block of size new size bytes, copying memory area with size equal the lesser of the new and the old sizes, and freeing the old block.

 

44) WHAT IS FREE FUNCTION?

Answer: The free() function in C++ deallocates a block of memory previously allocated using calloc, malloc or realloc functions, making it available for further allocations. The free() function does not change the value of the pointer, that is it still points to the same memory location.

 

45) EXPLAIN SHALLOW COPY.

Answer: shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied — the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.

 

46) Explain deep copy.

Answer: deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disastrous consequences.

If an object has pointers to dynamically allocated memory, and the dynamically allocated memory needs to be copied when the original object is copied, then a deep copy is required.

A class that requires deep copies generally needs:

  • A constructor to either make an initial allocation or set the pointer to NULL.
  • A destructor to delete the dynamically allocated memory.
  • A copy constructor to make a copy of the dynamically allocated memory.
  • An overloaded assignment operator to make a copy of the dynamically allocated memory.

47) Explain the scope of resolution operator.

Answer: The scope resolution operator helps to identify and specify the context to which an identifier refers, particularly by specifying a namespace. The specific uses vary across different programming languages with the notions of scoping. In many languages the scope resolution operator is written “::“.

48) List the advantages of inheritance.

Answer: One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses, where equivalent code exists in two related classes. This also tends to result in a better organization of code and smaller, simpler compilation units.

Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably.

Reusability-> facility to use public methods of base class without rewriting the same

Extensibility-> extending the base class logic as per business logic of the derived class

Data hiding-> base class can decide to keep some data private so that it cannot be altered by the derived class

Overriding-> With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.

49) What do you mean by a template?

Answer: template is a C++ programming feature that permits function and class operations with generic types, which allows functionality with different data types without rewriting entire code blocks for each type.

50) Explain RTTI.

Answer: In computer programming, run-time type information or run-time type identification (RTTI)[1] is a feature of the C++ programming language that exposes information about an object’s data type at runtime. Run-time type information can apply to simple data types, such as integers and characters, or to generic types. This is a C++ specialization of a more general concept called type introspection.

51) How can STACKS be implemented?

Answer: It can be implemented by using a linear array say S [] containing s size locations along with an integer variable TOP storing the index of the top most element in the stack.

52) What are the various operations performed on stack?

Answer: There are basically three operations that can be performed on stacks. They are 1) inserting an item into a stack (push). 2) deleting an item from the stack (pop). 3) displaying the contents of the stack(pip).

53) How a new element can be added or pushed in a stack?

Answer: Pushing an element into stack:
Whenever an element is to be pushed into stack, TOP is increased by 1 and then the element is inserted in the linear array denoted by S [] at the location with index TOP i.e. at S[TOP]. During push () operation, a stage may come when TOP points to the last location in array S [] i.e. it becomes equal to stksize-1, then no more element can be pushed into stack and we say that Stack Overflow.

Algo Push(S,Top, Item)
Step 1 : If (Top == stksize-1)
then (i) Write “Stack Overflow ”
(ii) Exit
step 2 : top = top + 1
step 3 : S[top] = Item
step 4 : Exit

54) DIFFERENTIATE BETWEEN A CLASS AND AN OBJECT.

Answer: 1)Class is blueprint means you can create different object based on one class which varies in there property. e.g. if
Car is a class than Mercedes, BMW or Audi can be considered as object because they are essentially a car but have different size, shape, color and feature.

2) A Class can be analogous to structure in C programming language with only difference that structure doesn’t contain any methods or functions, while class in Java contains both state and behavior, state is represented by field in class e.g.numberOfGears, whether car is automatic or manual, car is running or stopped etc. On the other hand behavior is controlled by functions, also known as methods in Java e.g. start() will change state of car from stopped to started or running and stop()will do opposite.

3) Object is also called instance in Java and every instance has different values of instance variables. e.g. in
following code

class Person {
private String name;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

Person p1 = new Person(“Rakesh”);
Person p2 = new Person(“Jimmy”);
Person p3 = new Person(“Peter”);

Here Person is a class as it defines design of Person objects i.e. How will a person object look like, what properties it will have etc. By the way Class is declared by keyword “class” in Java and p1, p2, p3 are different object of Person class. In natural language you can say different person which has different names where name is a property of Person Class. Another difference between Class and Object in Java is that we have a class keyword to declare class in Java but there is no object keyword. Objects are most notably created using new() operator, which calls constructor of class to create and initialize object in Java.

55) Explain Queue. How it can be implemented?

Answer:– A queue is a linear data structure which is a collection of homogeneous elements where insertion and deletion occurs at different ends.
– The end where insertion takes place is called REAR and the end where deletion takes place is called FRONT.
– Queue is also known as FIFO (FIRST IN FIRST OUT) because the element which is inserted first last will be the first element to come out from the queue.
– Queue can be implemented by:
1. Array Implementation of Stack
2. Linked List Implementation of Stack

56) Explain static memory allocation 

Answer: Memory is allocated for the declared variable by the compiler. The address can be obtained by using ‘address of’ operator and can be assigned to a pointer. The memory is allocated during compile time. Since most of the declared variables have static memory, this kind of assigning the address of a variable to a pointer is known as static memory allocation.

57) Explain dynamic memory allocation 

Answer: Allocation of memory at the time of execution (run time) is known as dynamic memory allocation. The functions calloc() and malloc() support allocating of dynamic memory. Dynamic allocation of memory space is done by using these functions when value is returned by functions and assigned to pointer variables.

58) WHAT IS A FUNCTION PROTOTYPE?
Answer:  function prototype or function interface is a declaration of a function that specifies the function’s name and type signature (arity, data types of parameters, and return type), but omits the function body. While a function definition specifies how the function does what it does (the “implementation”), a function prototype merely specifies its interface, i.e. what data types go in and come out of it.

59) What is searching? 

Answer: Searching is the process of finding a given value position in a list of values. It decides whether a search key is present in the data or not. It is the algorithmic process of finding a particular item in a collection of items. It can be done on internal data structure or on external data structure.

60) WHAT IS Linear Search?

Answer: linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched.

61) What is binary search?

Answer: Binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array. Even though the idea is simple, implementing binary search correctly requires attention to some subtleties about its exit conditions and midpoint calculation, particularly if the values in the array are not all of the whole numbers in the range

62) WHAT IS SORTING?

Answer:Sorting is any process of arranging items systematically, and has two common, yet distinct meanings:

1.     ordering: arranging items in a sequence ordered by some criterion;

2.     categorizing: grouping items with similar properties.

 

63) What is Bubble Sort?
Answer: Bubble Sort is probably one of the oldest, easiest, straight-forward, inefficient sorting algorithms. It works by comparing each element of the list with the element next to it and swapping them if required. With each pass, the largest of the list is “bubbled” to the end of the list whereas the smaller values sink to the bottom.

64) What is Selection Sort?
Answer: The idea of selection sort is rather simple: we repeatedly find the next largest (or smallest) element in the array and move it to its final position in the sorted array. Assume that we wish to sort the array in increasing order, i.e. the smallest element at the beginning of the array and the largest element at the end. We begin by selecting the largest element and moving it to the highest index position. We can do this by swapping the element at the highest index and the largest element. We then reduce the effective size of the array by one element and repeat the process on the smaller (sub)array. The process stops when the effective size of the array becomes 1 (an array of 1 element is already sorted).

65) What is Insertion Sort?
Answer: The Insertion Sort algorithm is a commonly used algorithm. Even if you haven’t been a programmer or a student of computer science, you may have used this algorithm. Try recalling how you sort a deck of cards. You start from the beginning, traverse through the cards and as you find cards misplaced by precedence you remove them and insert them back into the right position. Eventually what you have is a sorted deck of cards. The same idea is applied in the Insertion Sort algorithm.

66) What is Shell Sort?
Answer: Shell Sort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shell Sort is to allow exchange of far items. In shells ort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sub lists of every h’th element is sorted.

 

67) What is Heap Sort?
Answer: Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.

 

68) What is Merge Sort?
Answer: Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves.

 

69) What is Quick Sort?
Answer: Like Merge Sort, Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quick Sort that pick pivot in different ways.
1) Always pick first element as pivot.
2) Always pick last element as pivot (implemented below)
3) Pick a random element as pivot.
4) Pick median as pivot.

The key process in quick Sort is partition ().

 

70) What is the need of a destructor? Explain with the help of an example.

Answer: – During construction of an object, resources may be allocated for use.
– For example, a constructor may have opened a file and memory area may be allocated to it. These allocated resources must be deallocated before the object is destroyed.
– A destructor performs all clean-up tasks like closing a file, deallocating and releasing memory area etc. automatically.
– Example:

class X
{
int i, j;
public :
X( int m = 5, int n = 10)
{
i = m;
j = n;
}
~X() // destructor
{}
void print()
{
cout << i << ” ” <, j << endl;
}
};

 

71) How can a function be called?

Answer: 1. Implicit Calling:
By implicit calling, we mean that the constructor’s name is not specified in the calling statement.
General Form:

class name object_name( value1, value2, …. );

Example:

X o1(4,5);

2. Explicit Calling:
By explicit calling, we mean that the constructor’s name is specified in the calling statement.
General Form:

class_name object_name = constructor_name( value1, value2, …. );

Example :

X o1 = X(4,5);

 

72) What is the difference or relationship between a calling function and a called function?

Answer: The called function contains the definition of the function i.e. what and how to do.

The calling function contains the input (the actual parameters) which is given to the called function which then works on them because it contains the definition, performs the procedure specified and returns if anything is to be returned.

 

73) What are the rules for naming an identifier?

Answer:Variables are examples of identifiers. Identifiers are names given to identify something. There are some rules you have to follow for naming identifiers:

·         The first character of the identifier must be a letter of the alphabet (upper or lowercase) or an underscore (‘_’).

·         The rest of the identifier name can consist of letters (upper or lowercase), underscores (‘_’) or digits (0-9).

·         Identifier names are case-sensitive. For example, myname and myName are not the same. Note the lowercase n in the former and the uppercase N in the latter.

·         Examples of valid identifier names are i, __my_name, name_23 and a1b2_c3.

·         Examples of invalid identifier names are 2things, this is spaced out and my-name.

 

74) What are the Advantages of Linked Lists?

Answer:

·         They are a dynamic in nature which allocates the memory when required.

·         Insertion and deletion operations can be easily implemented.

·         Stacks and queues can be easily executed.

·         Linked List reduces the access time.

 

76) What are the Disadvantages of Linked Lists?

Answer:

·         The memory is wasted as pointers require extra memory for storage.

·         No element can be accessed randomly; it has to access each node sequentially.

·         Reverse Traversing is difficult in linked list.

 

78) List different Types of Linked Lists.

Answer:

·         Singly Linked List: – Singly linked lists contain nodes which have a data part as well as an address part i.e. next, which points to the next node in sequence of nodes. The operations we can perform on singly linked lists are insertion, deletion and traversal.

·         Doubly Linked List: – In a doubly linked list, each node contains two links the first link points to the previous node and the next link points to the next node in the sequence.

·         Circular Linked List: In the circular linked list the last node of the list contains the address of the first node and forms a circular chain.

 

79) What are the Applications of Linked Lists?

Answer:

·         Linked lists are used to implement stacks, queues, graphs, etc.

·         Linked lists let you insert elements at the beginning and end of the list.

·         In Linked Lists we don’t need to know the size in advance.

 

60) List the types of Inheritance.

We have 5 different types of Inheritance. Namely,

1.       Single Inheritance

2.       Multiple Inheritance

3.       Hierarchical Inheritance

4.       Multilevel Inheritance

5.       Hybrid Inheritance (also known as Virtual Inheritance)

 

 61) What is Single Inheritance?

Answer: In this type of inheritance one derived class inherits from only one base class. It is the simplest form of Inheritance.

 

62) What is multiple inheritance?

Answer: In this type of inheritance, a single derived class may inherit from two or more than two base classes.

 

63) What is Hierarchical Inheritance?

Answer: In this type of inheritance, multiple derived classes inherit from a single base class.

 

64) What is Multilevel Inheritance?

Answer: In this type of inheritance, the derived class inherits from a class, which in turn inherits from some other class. The Super class for one, is sub class for the other.

 

65) What is Hybrid (Virtual) Inheritance?

Answer: Hybrid Inheritance is combination of Hierarchical and Multilevel Inheritance.

 

66) What are the advantages of inheritance?

Answer:  One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of code and smaller, simpler compilation units.

·         Reusability — facility to use public methods of a base class without rewriting the same

·         Extensibility — extending the base class logic as per business logic of the derived class

·         Data hiding — base class can decide to keep some data private so that it cannot be altered by the derived class

·         Overriding–With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.

67) What are the Disadvantages of Inheritance?

Answer:  One of the main disadvantages of inheritance is the increased time/effort it takes the program to jump through all the levels of overloaded classes. If a given class has ten levels of abstraction above it, then it will essentially take ten jumps to run through a function defined in each of those classes

·         Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled.

·         This means one cannot be used independent of each other.

·         Also, with time, during maintenance adding new features both base as well as derived classes are required to be changed. If a method signature is changed then we will be affected in both cases (inheritance & composition)

·         If a method is deleted in the “super class” or aggregate, then we will have to re-factor in case of using that method. Here things can get a bit complicated in case of inheritance because our programs will still compile, but the methods of the subclass will no longer be overriding superclass methods. These methods will become independent methods in their own right.

68) What does virtual inheritance in C++ do?

Answer:  Virtual inheritance is a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritance.

To avoid the duplicated base class sub object that occurs with the “dreaded diamond”, you should use the ‘virtual’ keyword in the inheritance part of the classes that derive directly from the top of the diamond.

The “dreaded diamond” refers to a class structure in which a particular class appears more than once in a class’s inheritance hierarchy.

69) What are major differences between C++ and Java?

Answer:  Both Java and C++ are object-oriented languages. But certainly, this does not make them one and the same. So, here comes the major differences between Java and C++.

Differences between Java and C++:

·         Object Orientation: Java is a true and complete object-oriented language; whereas C++ is an extension of C with object-oriented behavior.

·         Template Class: Java does provide template classes, but C++ provides them.

·         Multiple Inheritance: Java supports multiple inheritance through interfaces; but C++ achieves it by permitting classes to inherit from other classes.

·         Global Variables: Global variables can be declared in C++, but not in Java.

·         Pointers: Java does not support pointers; but C++ supports pointers.

·         Object Destruction: Java destroys object in finalize method; but C++ destroys object through destructors.

·         Header Files: Java doesn’t support header files, but C++ supports them.

·         Structures and Union: Java does not support structures and union, but C++ supports them.

·         Operator Overloading: Operator Overloading is unsupported in Java, but supported in C++.

·         Garbage Collection: Java has an automatic garbage collector, whereas, C++ has no go in its standard library.

·         Conditional Compilation: Java does not support conditional compilation, but C++ do support it.

·         Threads: Java has built-in support for threads, but C++ has no such built-in support.

·         Default Arguments: Java does not support default arguments, but C++ do support them.

·         Scope Resolution Operator: Java has no scope resolution operator (: :), but C++ has it.

·         Got: Java has no got statement, but C++ has it.

·         Documentation Comment: Java has in-built support for documentation comment (/**…*/), but C++ does not support it.

·         Platform Independence: Java is platform independent; but C++ is not.

 

70) What are Advantages of Polymorphism?

Answer:

·         Method overloading allows methods that perform similar or closely related functions to be accessed through a common name. For example, a program performs operations on an array of numbers which can be int, float, or double type. Method overloading allows you to define three methods with the same name and different types of parameters to handle the array operations.

·         Method overloading can be implemented on constructors allowing different ways to initialize objects of a class. This enables you to define multiple constructors for handling different types of initializations.

·         Method overriding allows a sub class to use all the general definitions that a super class provides and add specialized definitions through overridden methods.

·         Method overriding works together with inheritance to enable code reuse of existing classes without the need for re-compilation.

 

71) What is the basic structure of a C++ program?

Answer: The basic structure of a C++ program is shown below:

1 #include<iostream.h>
2 int main()

3 {
4              cout<<”Hello,World!”;
5              return 0;

6 }

The first line that begins with “#” is a preprocessor directive. In this case, we are using includeas a directive which tells the compiler to include a header while “iostream.h” which will be used for basic input/output later in the program.

Next line is the “main” function that returns an Integer. The main function is the starting point of execution for any C++ program. Irrespective of its position in the source code file, the contents of the main function are always executed first by the C++ compiler.

In the next line, we can see open curly braces that indicate the start of a block of a code. After this, we see the programming instruction or the line of code that uses the count which is the standard output stream (its definition is present in iostream.h).

This output stream takes a string of characters and prints it to a standard output device. In this case it is, “Hello, World!”. Please note that each C++ instruction ends with a semicolon (;), which is very much necessary and omitting it will result in compilation errors.

Before closing the braces}, we see another line “return 0;”. This is the returning point to the main function.

Every C++ program will have a basic structure as shown above with a preprocessor directive, main function declaration followed by a block of code and then a returning point to the main function which indicates successful execution of the program.

 

72) What are the Extraction and Insertion operators in C++? Explain with examples.

Answer: In the iostream.h library of C++, cin, and cout are the two data streams that are used for input and output respectively. Cout is normally directed to the screen and cin is assigned to the keyboard.

“cin” (extraction operator): By using overloaded operator >> with cin stream, C++ handles the standard input.

1 int age;
2 cin>>age;

As shown in the above example, an integer variable ‘age’ is declared and then it waits for cin (keyboard) to enter the data. “cin” processes the input only when the RETURN key is pressed.

“cout” (insertion operator): This is used in conjunction with the overloaded << operator. It directs the data that followed it into the cout stream.

Example:

view source

print?

1 cout<<”Hello, World!”;
2  cout<<123;

 

73) What is Looping in C++?

Answer: Looping is to repeat your code as many times as you want without writing it many Times (as above Answer you don’t have to write a code 10 times just to print “hello world” on the screen, it can be easily done by looping in the programing language you are using.

Example: There Are

1:(For Loop) 2:(While Loop) 3: (Do While Loop)

For Loop Syntax:

1.        for (int; condition; increment)

2.        {

3.           // block of statement.

4.        }

 

init – Initializes the variable at the beginning of the loop to some value. This value is the starting point of the loop.

condition – Decides whether the loop will continue running or not. While this condition is true, the loop will continue running.

increment – The part of the loop that changes the value of the variable created in the variable declaration part of the loop. The increment statement is the part of the loop which will eventually stop the loop from running.

Example :

1.       #include <iostream>

2.       using namespace std;

3.       int main()

4.       {

5.           for(int i = 0; i < 10 ; i++)

6.           {

7.               cout<<i<<” “;

8.           }

9.           return 0;

10.   }

While Loop :

while loop in C++ programming language repeatedly executes a target statement as long as a given condition is true.

While Loop Syntax:

1.       while (condition)

2.       {

3.           statement(s);

4.       }

5.

Example:

1.       #include <iostream>

2.       using namespace std;

3.       int main ()

4.       {

5.           // local variable definition

6.           int x = 1;

7.

8.           // while loop execution

9.           while (x < 5)

10.       {

11.           //loops comes inside this body, until condition is true

12.           cout<<“Value of x: “<<x<<“\n”;

13.           x++;

14.       }

15.

16.       return 0;

17.   }

Do While Loop:

do-while loop is similar to a while loop, except that a do-while loop is guaranteed to execute at least one time. The conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.

Syntax:

1.       do

2.       {

3.           statement(s);

4.       } while (condition);

5.

6.

Example:

1.       #include <iostream>

2.       using namespace std;

3.       int main ()

4.       {

5.           // declared local operand (variable)

6.           int a = 1;

7.

8.           // do-while loop

9.           do

10.       {

11.           cout<<“value of a: “<<a<<“\n”;

12.           a = a + 1;

13.       } while (a < 5);

14.

15.       return 0;

16.   }

As you can see the advantages, you can perform bigger operation inside a loop without writing the code many times.

 

74) What is a nested loop in C++? What is the concept behind a nested loop?

Answer: A nested loop is a loop inside another loop. It consists of an outer loop, and an inner loop. In terms of the mechanics, an inner loop is no different than putting a loop inside a code block for an if statement, for example. Here’s an example of an outer loop and an inner loop:

1.       // Loop A

2.       for(int i = 1; i <= 10; i++)

3.       {

4.          printf(“All numbers from %d to 10:\n”, i);

5.          // Loop B

6.          for(int j = i; j <= 10 ; j++)

7.          {

8.             if(j < 10)

9.             {

10.            printf(“%d, “, j);

11.         }

12.         else

13.         {

14.            printf(“%d”, j);

15.         }

16.      }

17.      printf(“\n”);

18.   }

Note that both loops have the same form. There’s nothing special about Loop B. It’s just a loop, like Loop A, except that Loop B’s behavior is changed by what changes in Loop A (note I initialize j in Loop B to whatever i is set to in Loop A). Note that it is important to keep each loop’s variables straight! In my case, i is for Loop A, and j is for Loop B. Typically, this is what you’ll want to do with nested loops, have the inner loop be affected by what’s going on with the outer loop.

What you will see with my above example is a nested sequence of numbers, with each inner sequence starting with the current number in the outer sequence. The outer sequence goes from 1 to 10, and each inner sequence goes from each number in the outer sequence to 10.

 

75) What do you mean by ‘void’ return type?

 Answer: All functions should return a value as per the general syntax.

However, in case, if we don’t want a function to return any value, we use “void” to indicate that. This means that we use “void” to indicate that the function has no return value or it returns “void”.

 

76) What are Default Parameters? How are they evaluated in C++ function?

Answer: Default parameter is a value that is assigned to each parameter while declaring a function.

This value is used if that parameter is left blank while calling to the function. To specify a default value for a particular parameter, we simply assign a value to the parameter in the function declaration.

If the value is not passed for this parameter during the function call, then the compiler uses the default value provided. If a value is specified, then this default value is stepped on and the passed value is used.

 

 77) What is an Inline function in C++?

Answer: Inline function is a function that is expanded in line when it is called. Inline functions reduce the function call overhead. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the compiler at compile time. Inline function may increase efficiency if it is small.

 

78) WHAT IS AN ARRAY?

Answer: An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the “Hello World!” application. This section discusses arrays in greater detail.

An array of 10 element.

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

 

79) What are Advantages of an array?

Answer:

1.       It is used to represent multiple data items of same type by using only single name.

2.       It can be used to implement other data structures like linked lists, stacks, queues, trees, graphs etc.

3.       2D arrays are used to represent matrices.

80) What are Disadvantages of an array?

Answer:

1.       We must know in advance that how many elements are to be stored in array.

2.       Array is static structure. It means that array is of fixed size. The memory which is allocated to array cannot be increased or reduced.

3.       Since array is of fixed size, if we allocate more memory than requirement then the memory space will be wasted. And if we allocate less memory than requirement, then it will create problem.

4.       The elements of array are stored in consecutive memory locations. So, insertions and deletions are very difficult and time consuming.

 

81) What is the difference between an array and linked list?

Answer: Both store a sequence of elements, but using different techniques.

An array stores element in successive order in memory, i.e. it looks like follows:

————————————————————————————–

| item 1 | item 2 | item 3 | …  …  | item x | //here comes other stuff ————————————————————————————–

This means, elements are one after another consecutive in memory.

A ((doubly) linked) list, on the other hand, stores the items the following way: It creates an own “list item” for each element; this “list item” holds the actual element and a pointer/reference/hint/etc. to the next “list item”. If it is doubly linked, it also contains a pointer/reference/hint/etc. to the previous “list item”:

This means, the elements can be spread all over the memory and are not stored at specific memory locations.

Now that we know this, we can compare some usual operations on sequences of elements:

·         Accessing an element at a specific index: Using an array, we simply compute the offset for this index and have the element at the index.

This is very cheap. With a list on the other hand, we do not know a priori where the element at index is stored (since all elements can be anywhere in memory), so we have to walk the list item by item until we find the element at the index. This is an expensive operation.

·         Adding a new element at the end of the sequence: Using an array this can lead to the following problem: Arrays are usually of fixed size, so if we have the situation that our array is already completely filled (see //here comes other stuff), we probably can’t put the new element there because there might already be something else. So, maybe we have to copy the whole array. However, if the array is not filled, we can simply put the element there.

Using a list, we have to generate a new “list item”, put the element into it and set the next pointer of the currently last element to this new list item. Usually, we store a reference to the currently last element so that we don’t have to search through the whole list to find it. Thus, inserting a new element is no real problem with lists.

·         Adding a new element somewhere in the middle: Let’s first consider arrays: here, we might get into the following situation: We have an array with elements 1 to 1000:

1 | 2 | 3 | 4 | 5 | 6 | … | 999 | 1000 | free | free

Now, we want to insert 4.5 between 4 and 5: This means, we have to move all elements from 5 to 1000 one position right in order to make space for the 4.5:

1 | 2 | 3 | 4 | free | 5 | 6 | … | 999 | 1000 | free                   ||                  Vv  1 | 2 | 3 | 4 | 4.5 | 5 | 6 | … | 999 | 1000 | freeMoving all these elements, is a very expensive operation. So better don’t do this too often.

Now we consider, how a list can perform this task: Let’s say we have currently the following list:

1 -> 2 -> 3 -> 4 -> 5 -> … -> 999 -> 1000Again, we want to insert 4.5 between 4 and 5. This can be done very easily: We generate a new list item and update the pointers/references:

1 -> 2 -> 3 -> 4        5 -> … -> 999 -> 1000                |        ^                +-> 4.5 -+We have simply created a new list element and generated sort of “bypass” to insert it – very cheap (as long as we have a pointer/reference to the list item the new element will be inserted after).

So, let’s sum up: Linked lists are really nice when it comes to inserting at random positions (as long as you have a pointer to the adequate list item). If your operation involves adding lots of elements dynamically and traversing all elements anyway, a list might be a good choice.

An array is very good when it comes to index accesses. If your application needs to access elements at specific positions very often, you should rather use an array.

 

82) When to use “const” reference arguments in a function?

Answer: Using “const” reference arguments in a function is beneficial in several ways:

  • “const” protects from programming errors that could alter data.
  • As a result of using “const”, the function is able to process both const and non-const actual arguments, which is not possible when “const” is not used.
  • Using a const reference, allows the function to generate and use a temporary variable in an appropriate manner.

Conclusion: 

C++ is a technical skill that has been in demand for the past few decades and will remain for few more decades. Several core industries like electronics, mechanical, aerospace etc have chosen C and C++ as their core programming language to build their industry specific platforms. Because of this reason, the demand for C++ expected to continue. 82 Top C++ interview questions given above will help all job seekers to prepare better for the interviews.

Share this: