C++ Programming Interview Questions

X




Resources > C++ Interview Questions > {{currentSubTopic}}

Introduction


What are the differences between C and C++?

The major difference between C and C++ is that C is a procedural programming language and does not support classes and objects, while C++ is a combination of both procedural and object oriented programming language.


What are the advantages of C++?

Some of the important advantages of C++ are:
1) Being an object oriented language, it provides support for features like polymorphism and inheritance making codes more concise and reusable.
2) Object oriented programming also provides for a modular structure for writing clear and organized code.
3) Due to encapsulation, programmers can change one chunk of the system without breaking the other chunks.


Can a program be compiled without main() function?

No.


Is it possible to get the source code back from binary file?

No.


Can we nest multi line comments in a C++ code?

No. Nesting of multiline comments generates compilation error.


Is 068 a valid octal number?

An octal number can only have digits ranging from 0-7.


Pointers, Arrays, Multidimensional Arrays and Strings


What are the differences between references and pointers?

On the surface, both references and pointers are very similar, both are used to have one variable provide access to another. But there are some major differences between the two:
A pointer can be re-assigned

int x = 5;
int y = 6;
int *p;
p =  &x;
p = &y;

On the other hand, a reference cannot be re-assigned, and must be assigned at initialization.

int x = 5;
int y = 6;
int &r = x;

A pointer has its own memory address and size on the stack whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack.

Pointer can be assigned NULL directly, whereas reference cannot. This ensures that the underlying operations do not run into exception situation.

C++ permits having pointers to pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection.


What is this pointer?

In C++, this pointer is used to represent the address of the calling object inside a member function. For example, consider an object obj calling one of its member function say doStuff() as obj.doStuff(). Then, this pointer will hold the address of object obj inside the member function doStuff().


Functions and Structures, Dynamic memory allocation and Preprocessors


What is the difference between new() and malloc()?

new operator constructs new objects. malloc function allocates a block of memory and returns a pointer to the beginning of the block. The differences between new and malloc are as follows:

The major difference between the two is that when new is used to create objects, it calls the constructor of the class while malloc() does not invoke the constructor.

When new is used to create objects, the amount of memory required will be calculated by the compiler. Whereas in the case of malloc(), the memory requirement needs to be calculated manually.


Define friend function.

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class.


What is an inline function?

Whenever a function is called, the memory address of the function call instruction is stored , parameters are copied on the stack and then the control is passed to the called function. When the function code is done executing, the return value of the function is stored in a register and the control transfers back to the calling function. This process becomes an overhead if the time taken to execute the function is lesser than the time spent in switching of control. C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. 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 C++ compiler at compile time thereby bringing down the execution time of the code.


What is the role of mutable storage class specifier?

The mutable storage class specifier is used to make a class data member modifiable even though the member is part of an object declared as const.

class Sample
{
  public:
    Sample() : x(10), y(20) { };
    mutable int x;
    int y;
};

int main()
{
  const Sample obj;
  obj.x = 345;
  // obj.y = 2345;
}

The compiler would not allow the assignment obj.y = 2345 because obj has been declared as const. The compiler will allow the assignment obj.x = 345 because Sample::x has been declared as mutable.


What is the difference between delete and delete[]?

The delete[] operator is used to delete arrays. The delete operator is used to delete non-array objects. It calls operator delete[] and operator delete function respectively to delete the memory that the array or non-array object occupied after (eventually) calling the destructors for the array's elements or the non-array object.


Which operator can be used in C++ to allocate dynamic memory?

new operator is used for dynamic memory allocation in C.


Classes and Objects, Constructors and Destructors


What is constructor?

Constructor is a special type of member function that is called when an object is created. It automatically initializes the newly created object


Can we do “delete this”?

Delete operator can only be used with objects created using the new operator otherwise its behaviour is undefined. However, it is not preferable to do so.


What is Object Oriented Programming (OOP)?

OOP is a model of programming organized around objects rather than "actions" and data rather than logic. It is based on the concept of representing real world entities as objects, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. So while programming using OOP, programmers not only define the type of data structures but also the operations that could be applied on them.


Distinguish between shallow copy and deep copy.

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

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

So, 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.


What is a destructor? Can it be overloaded?

Destructors are inverse of constructors. Just as a constructor is called automatically when an object is created, destructors are called automatically when an object is deleted or goes out of scope, to free the memory consumed by the object.

No, the destructor cannot be overloaded because then the code will have no way to know which destructor to call when an object is deleted.


What is role of static keyword on class member variable?

When a data member is declared as static, only one copy of the data is maintained for all objects of the class.They belong to the class and not to a particular object.


Can we initialize a class/structure member variable as soon as the same is defined?

No.


Explain the static member function.

A static member is a member function of a class that can be called even if no objects of the class exist. Static functions can be accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class.


What is a reference variable in C++?

Reference variables are those that hold the memory address of an object present in memory. They are said to refer to the objects whose memory address they contain.


Inheritance and Operator Overloading


What are the C++ access specifiers?

An access control defines a boundary to a member of the class. They are also known as visibility labels and access specifiers.
A class can have three kinds access control:
1. Private: member of a class is accessible only by members and friends of the class. By default all the members of the class are private.
2. Protected: member of a class are accessible only by members and friends of the class and members and friends of the derived classes, provided they access the base member via a pointer or a reference to their own derived class.
3. Public: member of a class is accessible by everyone.


What is overloading?

Overloading means providing multiple definitions to an entity. Overloaded declarations are declarations having the same name but differ in certain aspects. C++ allows both function and operator overloading. Overloaded functions are functions with same name but different parameters. Overloaded operators are same operators but working on different number of operands.


What is function overriding?

Function overriding is used when you want to change the implementation of some super class method in your subclass. Function is said to be overridden when you define function with the same signature as in the super class but different implementation. If you create an object of the derived class and call the member function which exists in both base and derived classes , the member function of the derived class is invoked and the function of the base class is ignored. This is function overriding.


What is virtual inheritance?

Virtual inheritance is a feature that ensures only one copy of a base class's member variables are inherited by its non-immediate derived classes. Without virtual inheritance, if classes A and B both inherit from class X, and class C inherits from classes A and B, then class C will contain two copies of X's member variables: one via A, and one via B. These will be accessible independently, using scope resolution.

Instead, if classes A and B inherit virtually from class X, then objects of class C will contain only one set of the member variables from class X.


What is an abstract class in C++?

Sometimes it may not be possible to provide an implementation of all the member functions of a base class as the exact implementation of a function may be specific to the derived class and may vary from class to class. For example, consider a class Shape. Every shape has an area so we can put a method called getArea() in the Shape class. But the logic for calculating the area will be different for different shapes inheriting from the Shape class. So getArea() needs to be defined as a pure virtual function meaning a function with no definition. A class having at least pure virtual function is called an abstract class.


When should we use multiple inheritance?

Multiple inheritance is used when you want to make a class inherit from two base classes.


Is it legal to assign a base class object to a derived class pointer?

No, vice-versa is true. A Base Class pointer can point to a derived class object.If I tell you I have a dog, you can safely assume that I have a pet. If I tell you I have a pet, you don't know if that animal is a dog, it could be a cat or maybe even a giraffe. Without knowing some extra information you can't safely assume I have a dog. Similarly a derived object is a base class object, so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.


Virtual Functions


What is a pure virtual function?

Sometimes it may not be possible to provide an implementation of all the member functions of a base class as the exact implementation of a function may be specific to the derived class and may vary from class to class. For example, consider a class Shape. Every shape has an area so we can put a method called getArea() in the Shape class. But the logic for calculating the area will be different for different shapes inheriting from the Shape class. So getArea() needs to be defined as a pure virtual function meaning a function with no definition. A class having at least pure virtual function is called an abstract class.


Does an abstract class in C++ need to hold all pure virtual functions?

No. A class having at least pure virtual function is called an abstract class. It can have normal methods as well.


Miscellaneous


What does Scope Resolution operator?

Scope resolution operator(::) in C++ programming language is used to define a function outside a class or when we want to use a global variable but also has a local variable with the same name.
For example:

#include <iostream>
using namespace std;
char a = 'g';     // global variable
int main() {
  char a = 'l';   //local variable
  cout << "Local  variable: " << a << "\n";      
  cout << "Global variable: " << ::a << "\n";  //using scope resolution operator
  return 0;
}
Output:
#include <iostream>
using namespace std;
class programming {
public:
  void output();  //function declaration
};
// function definition outside the class 
void programming::output() {
  cout << "Function defined outside the class.\n";
}
int main() {
  programming x;
  x.output(); 
  return 0;
}

What is the purpose of #undef preprocessor?

In the C Programming Language, the #undef directive tells the preprocessor to remove all definitions for the specified macro. A macro can be redefined after it has been removed by the #undef directive. Once a macro is undefined, an #ifdef directive on that macro will evaluate to false.


What you mean by early binding and late binding?

Binding means matching the function call with the correct function definition by the compiler. It takes place either at compile time or at runtime. In early binding, the compiler matches the function call with the correct function definition at compile time. It is also known as Static Binding or Compile-time Binding. In the case of late binding, the compiler matches the function call with the correct function definition at runtime. It is also known as Dynamic Binding or Runtime Binding.In late binding, the compiler identifies the type of object at runtime and then matches the function call with the correct function definition. By default, early binding takes place. Late binding is achieved by declaring virtual functions.


What do you mean by persistent and non persistent objects?

A persistent object can live after the program which created it has stopped. Persistent objects can even outlive different versions of the creating program, can outlive the disk system, the operating system, or even the hardware on which the OS was running when they were created. A non-persistent object is the one which is destroyed after the program ends.


name