Preparing for a C/C++ interview can be a daunting task, especially for freshers. To help you out, we’ve compiled a list of common C/C++ interview questions that you might encounter. By familiarizing yourself with these questions, you’ll be well-equipped to tackle any interview with confidence. For those interested in C#, check out these C# interview questions for freshers.
Basic C/C++ Interview Questions
1. What are the differences between C and C++?
C is a procedural programming language, while C++ is a combination of both procedural and object-oriented programming languages. C++ supports features like classes, inheritance, polymorphism, and encapsulation, which are not present in C.
2. Explain the concept of a pointer in C.
A pointer is a variable that stores the memory address of another variable. Pointers are used for dynamic memory allocation, array manipulation, and accessing memory locations directly.
int a = 10;
int *ptr = &a;
printf(“Value of a: %d”, *ptr); // Output: 10
3. What is a NULL pointer?
A NULL pointer is a pointer that does not point to any valid memory location. It is often used to indicate that a pointer is not assigned any value.
int *ptr = NULL;
4. How do you declare a function in C?
A function is declared using the following syntax:
return_type function_name(parameters) {
// function body
}
For example:
int add(int a, int b) {
return a + b;
}
5. What is the use of the const keyword in C++?
The const keyword is used to define constant variables that cannot be modified after their initialization. It is also used to protect function parameters from being altered inside the function.
const int x = 10;
6. Explain the concept of inheritance in C++.
Inheritance is a feature in C++ that allows a class (derived class) to inherit properties and behaviors (methods) from another class (base class). It promotes code reusability and establishes a relationship between classes.
class Base {
public:
void display() {
cout << “Base class display” << endl;
}
};
class Derived : public Base {
public:
void show() {
cout << “Derived class show” << endl;
}
};
Advanced C/C++ Interview Questions
1. What is polymorphism in C++?
Polymorphism allows functions or methods to process objects differently based on their data type or class. It is achieved through function overloading and operator overloading (compile-time polymorphism) and virtual functions (runtime polymorphism).
2. Explain the difference between malloc and new.
malloc is a standard library function in C that allocates memory at runtime and returns a void pointer to the allocated space. new is an operator in C++ that allocates memory and calls the constructor for object initialization.
3. What are virtual functions in C++?
Virtual functions are member functions in a base class that can be overridden in derived classes. They are used to achieve runtime polymorphism.
class Base {
public:
virtual void display() {
cout << “Base class display” << endl;
}
};
class Derived : public Base {
public:
void display() override {
cout << “Derived class display” << endl;
}
};
4. What is the significance of the this pointer in C++?
The this pointer is an implicit pointer available to all member functions of a class. It points to the object for which the member function is called.
5. How does exception handling work in C++?
Exception handling in C++ is performed using three keywords: try, catch, and throw. It is used to handle runtime errors and ensures the program continues execution without interruption.
try {
// code that may throw an exception
throw “An error occurred”;
} catch (const char* msg) {
cout << msg << endl;
}
Data Structures and Algorithms in C/C++
1. How do you implement a linked list in C++?
A linked list is a data structure consisting of nodes where each node contains data and a pointer to the next node.
struct Node {
int data;
Node* next;
};
void insert(Node** head, int newData) {
Node* newNode = new Node();
newNode->data = newData;
newNode->next = *head;
*head = newNode;
}
2. Explain the concept of a binary tree.
A binary tree is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child.
struct Node {
int data;
Node* left;
Node* right;
};
3. How do you perform a depth-first search (DFS) in a graph using C++?
DFS is an algorithm for traversing or searching tree or graph data structures. It starts at the root (or an arbitrary node) and explores as far as possible along each branch before backtracking.
void DFS(int v, vector<bool>& visited, vector<vector<int>>& adjList) {
visited[v] = true;
cout << v << ” “;
for (int i : adjList[v]) {
if (!visited[i]) {
DFS(i, visited, adjList);
}
}
}
Memory Management in C/C++
1. What is dynamic memory allocation?
Dynamic memory allocation refers to the process of allocating memory at runtime using functions like malloc, calloc, realloc, and free in C and the new and delete operators in C++.
2. Explain the concept of memory leak.
A memory leak occurs when a program allocates memory but fails to release it. This can lead to increased memory usage and, eventually, the exhaustion of available memory.
int* ptr = new int[10];
// forgot to delete the allocated memory
3. How do you prevent memory leaks in C++?
To prevent memory leaks, ensure that every new is paired with a corresponding delete. Using smart pointers (e.g., std::unique_ptr, std::shared_ptr) can also help manage memory automatically.
Common Mistakes to Avoid in C/C++ Interviews
1. Not understanding the basics thoroughly
Many candidates overlook basic concepts like pointers, arrays, and simple data structures. Ensure you have a strong grasp of these fundamentals.
2. Ignoring time and space complexity
Always analyze the time and space complexity of your code. Interviewers often ask about the efficiency of your solutions.
3. Not practicing enough
Regular practice is key to acing technical interviews. Solve problems on platforms like LeetCode, HackerRank, and Codeforces to build your skills.
Conclusion
Preparing for C/C++ interviews requires a solid understanding of both basic and advanced concepts. By familiarizing yourself with the common questions outlined in this article, you’ll be well-prepared to tackle your interview with confidence. For those interested in design patterns, check out this article on dependency injection in C#.
FAQs
1. What is the difference between struct and class in C++?
In C++, struct defaults to public access, whereas class defaults to private access. Otherwise, they are essentially the same.
2. How do you handle exceptions in C++?
Exceptions in C++ are handled using try, catch, and throw keywords. This allows for structured error handling and recovery.
3. What are some common C++ interview questions for freshers?
Common questions include differences between C and C++, understanding pointers, memory management, and implementation of data structures. For a comprehensive list, check out these C# interview questions for freshers.
4. What is a segmentation fault in C/C++?
A segmentation fault occurs when a program tries to access an invalid memory location. It is often caused by dereferencing a null or uninitialized pointer.
5. How do you implement a stack using an array in C++?
A stack can be implemented using an array by maintaining a top pointer that tracks the index of the last element added.
class Stack {
int top;
int arr[100];
public:
Stack() { top = -1; }
void push(int x) { arr[++top] = x; }
int pop() { return arr[top–]; }
};