- 1 What is c++?
- 2 How to code during an online interview?
- 3 Where can you use C++ for practicing the language online?
- 4 What techniques are effective in ensuring that the C++ code performs well?
- 5 Most common C++ interview question for experienced and beginner developers
-
6
Question and Answers
- 6.1 Most common questions asked by interviewers:
-
6.2
Here are some of the C++ common questions asked during interview
- 6.2.1 Q1. What does OOPS stand for?
- 6.2.2 Q2. Difference between C and C++ programming language.
- 6.2.3 Q3. In C++ language, explain Classes & Objects.
- 6.2.4 Q4. How do you implement inheritance in C++?
- 6.2.5 Q5. What do you understand about Dynamic Memory Allocation in C++?
- 6.2.6 Q6. What is the STL?
- 6.2.7 Q7. How does the ‘std::sort’ function work in C++?
- 6.2.8 Q8. Explain what the Map and Set containers are in C++.
- 6.2.9 Q9. Write how Mutex should be used in C++.
- 6.3 Technical Questions:
- 7 Conclusion
If you are someone who wants to work as a c++ developer, then going through a c++ coding interview is necessary. With the rise of technology, interviews have also become more advanced. Online interviews are now being used widely by companies around the world. It has become important that an interviewee should also be adapted to online interview atmospheres. C++ online interviews are becoming famous day by day. In these types of interviews the questions will be made in accordance to test the candidates skills, capabilities, critical thinking, coding speed etc. You might be an experienced or beginner c++ developer, but before going for an online ide C++ interview there are some things that you should know. In this article we will cover topics related to C++ interviews and C++ common interview questions asked during interviews.
What is c++?
C++ is a coding language that was developed by Bjarne Stroustrup. It is an extension to the C programming language. It is highly suitable for most of the applications that are available. C++ is an object-oriented programming (OOP), which means it supports concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction, allowing for better organization and modularity of code. Using online C++ ide like online dev C++ makes it easier to code C++ programming language.
How to code during an online interview?
Join the Interview
- Log in a few minutes early to avoid technical issues.
- Follow the provided link or meeting details to join the interview.
Understand the Problem
- Listen carefully to the interviewer’s problem statement.
- Ask clarifying questions to ensure you understand the requirements.
Code Incrementally
- Write clean, readable code with meaningful variable names.
- Use comments to explain your logic where necessary.
- Implement your solution in small increments and test as you go.
Run Test Cases
- Use the platform’s features to run sample inputs and validate your solution.
- Discuss edge cases and how your code handles them.
Debug if Needed
- If your code doesn’t work as expected, calmly debug the issue while explaining your process to the interviewer.
Discuss Your Solution
- Once finished, walk the interviewer through your code, explaining your reasoning and choices.
- Be open to feedback and suggestions for improvements.
Where can you use C++ for practicing the language online?
Dev C++ Online: A readily available lightweight editor for code development in C++ which may be used for solving problems.
Online C++ IDE: Such webpages as Repl. The websites it, Ideone, and Compiler Explorer give online IDEs for building and executing C++ programs.
C++ Programming Coding Questions and Answers PDF: Most of the social sites offer links that have PDF documents that contain frequently asked C++ coding questions and answers which can be of immense help while preparing for the interviews.
What techniques are effective in ensuring that the C++ code performs well?
Avoid Unnecessary Copying: It is urged to use the references or pointers instead of copying larger objects in data.
Use Efficient Algorithms: Always select algorithms which are less time complex.
Manage Memory Efficiently: Prevent memory leaks and always free up all resources in due time.
Use Inline Functions: Restricts small, often invoked functions to cut on the overall expenses.
Most common C++ interview question for experienced and beginner developers
To demonstrate your skills and excel in a C++ interview, thorough preparation is key. This collection of C++ interview questions will assist candidates in showcasing their expertise and improving their chances of success. For recruiters, selecting the right candidate from a large pool can be daunting. However, these questions can help streamline the evaluation process, making it easier to identify the best fit for your team. With the right c++ programming coding question and answers pdf and assessment tools, both candidates and recruiters can achieve their goals!
Question and Answers
Most common questions asked by interviewers:
Q1. What is SDLC?
The SDLC is known as the Software Development Lifecycle. It helps the developer in the software development life cycle from the first planning stage to the final product delivery. It involved various stages: planning, requirements analysis, design, development, testing, deployment, and maintenance.
Q2. What is the framework?
A framework is a ready-made foundation that comes with various tools and rules. It simplifies the creation process by offering a starting point and useful guidelines. This framework can be used to speed up development and avoid starting from scratch.
Q3. Explain the Big O notation.
Big O Notation measures the running time or space needed by an algorithm that changes as the size of the input grows. It is a tool that helps to understand the efficiency of an algorithm.
Common Big O notation:
- O(1) represents constant time.
- O(log n) represents logarithmic time.
- O(n) represents Linear time.
Q4. What is ASCII code and Unicode?
ASCII and Unicode are used to write special text representations on computers, but they work differently. ASCII is an old system with only 128 characters. These include letters, numbers, and symbols, all mainly for English. It’s quite basic and can be limiting.
On the other hand, Unicode is much more advanced. It covers 149,878 characters from many languages and writing systems. This makes Unicode crucial for handling text from around the world. Whether Chinese, Arabic, or even special symbols, Unicode displays everything correctly.
Q5. Why do companies still use C++?
C++ is a low-level programming language, mostly used where performance, control, and support for older codebases are crucial. Preferred by developers to write codes for system fundamentals, games, and embedded system development.
Here are some of the C++ common questions asked during interview
Q1. What does OOPS stand for?
OOPS stands for Object-Oriented Programming System or Object-Oriented Programming Structure.
Q2. Difference between C and C++ programming language.
FEATURE | C | C++ |
Programming Paradigm | Procedural programming, focusing on functions and procedures | Object-oriented programming emphasizing on data and the operations that can be taken with it. |
Data Abstraction | Limited; uses structures for data | Supports classes and objects, enabling encapsulation and inheritance |
Standard Library | Minimal standard library | Rich Standard Template Library (STL) provides pre-defined data structures and algorithms |
Memory management | Manual memory management (malloc/free) | Supports both manual and automatic memory management (new/delete) and smart pointers |
Q3. In C++ language, explain Classes & Objects.
Class:
A class is a special function that is defined by a user, which includes member variables and data functions that can be accessed and used to create an instance of the class. This approach promotes code reusability and modularity, enabling the creation of complex and scalable software applications.
A C++ class is a prototype or blueprint that plays a crucial role in creation of object.
For Example, We are already aware of different types of chairs, from office chairs to dining chairs. Here, the class would be a general description of what a chair is. It would include the essential components that make up any chair: legs, a seat, and a backrest.
Key points about classes:
- They define the properties and behaviors of objects.
- They provide a way to organize data and functions logically.
- They promote code reusability and modularity.
Syntax:
class <class_name>
{
}
OBJECT:
Object is instance of class, can be consider as a real-world entity. It consists of attributes and methods. Basically, attributes are variables, and methods are functions.
For example, an office chair, a dining chair, and a rocking chair are all specific instances or “objects” of the chair class. Each chair will have its own unique properties (like color, material, or style) while sharing the fundamental structure defined by the chair class.
Key points about objects:
- They are created from classes.
- They have their own memory space.
- They can access and modify the data members of their class.
Syntax:
<class_Name> <obj_name>; // Creating an object
Note: Memory is allocated only when the object is created. There is no memory allocation in the class declaration.
Program:
#include <iostream>
using namespace std;
// Define a class to represent an Employee in a company
class Employee {
public:
// Data members (attributes) of the Employee class
string name; // Employee's name
int id; // Employee's ID
string department; // Employee's department
// Member function to display employee details
void displayDetails() {
cout << "Employee ID: " << id << endl;
cout << "Employee Name: " << name << endl;
cout << "Department: " << department << endl;
}
};
int main() {
// Creating an object of the Employee class
Employee emp1;
// Assigning values to the object's attributes
emp1.id = 101; // Setting ID
emp1.name = "John Doe"; // Setting Name
emp1.department = "Finance"; // Setting Department
// Call the function to display the details of the employee
emp1.displayDetails();
return 0;
}
Q4. How do you implement inheritance in C++?
Inheritance in C++:
Inheritance permits the use of the properties and functions of the parent class by creating a child class building upon the blueprint of the current one. This approach promotes code reusability, establishes clear hierarchical relationships, and enables flexible program expansion.
How to Implement Inheritance in C++
In C++ language, inheritance is implemented using the colon (:) symbol. The derived class is placed on the left, followed by the base class on the right. You can optionally specify access levels (public, protected, or private) to control how inherited members are used in the derived class.
Syntax:
class <DerivedClass> : access_specifier <BaseClass> {
// Derived class members
};
Derived class: The class that will take properties from an existing class.
Base class: From this class, properties and behavior are inherited.
Program:
#include <iostream>
using namespace std;
// Base class
class Project {
public:
// Base class constructor
Project() {
cout << "Project initiated." << endl;
}
// Base class function
void plan() {
cout << "Planning the project." << endl;
}
};
// Derived class inheriting from base class 'Project'
class ITProject : public Project {
public:
// Derived class constructor
ITProject() {
cout << "IT Project started." << endl;
}
// Derived class function
void code() {
cout << "Coding for the IT project." << endl;
}
};
int main() {
// Create an object of the derived class 'ITProject'
ITProject myITProject;
// Call the inherited function from the base class
myITProject.plan(); // Accessing function from Project class
// Call the function from the derived class
myITProject.code(); // Accessing function from ITProject class
return 0;
}
Q5. What do you understand about Dynamic Memory Allocation in C++?
Dynamic memory allocation in C++ happens while a program is running, not when it’s being compiled. This method lets you manage memory based on what the program needs at that moment. It offers flexibility, allowing the program to request and release memory as required during execution.
Why Use Dynamic Memory Allocation?
- Handling Uncertain Data Sizes: Sometimes, you don’t know how big your data will be. In such cases, dynamic memory allocation becomes essential.
- Adaptable Data Structures: With dynamic memory, your data structures aren’t fixed in size. They can grow or shrink depending on what your program demands.
- Efficient Memory Usage: Instead of holding unnecessary memory blocks, it’s allocated based on the program requirement. This approach reduces wastage of memory space and makes better use of available memory.
How It Works
C++ gives you two main ways for memory allocation:
1) new operator: assigns memory space to the variables at the runtime
int *p = new int; // memory allocation for integer
int *a = new int[5]; // memory allocation for array of 5 integer
2) delete operator: frees up the memory space.
delete ptr; // Deallocates memory pointed to by ptr
delete[] arr; // Deallocates memory for the array pointed to by arr
Program:
#include <iostream>
using namespace std;
int main() {
// Dynamic memory allocation for an integer using 'new'
int* ptr = new int; // Allocates memory on the heap for one integer
// Assign a value to the dynamically allocated memory
*ptr = 42;
// Output the value stored in the dynamically allocated memory
cout << "Value stored in dynamically allocated memory: " << *ptr << endl;
// Deallocate the memory using 'delete'
delete ptr; // Frees the memory allocated on the heap
// Setting pointer to nullptr after deletion
ptr = nullptr;
return 0;
}
Q6. What is the STL?
STL, or Standard Template Library, which comes with pre-written code, and has multiple classes and functions that can help you in common programming tasks. Such as searching and sorting of data, performing mathematical operations, and managing lists or arrays. This library plays a crucial role in the development of modern C++.
Key Components of STL
- Containers: These are like data structures that allow you to store various types of elements. These containers can manage memory dynamically, resize automatically, and efficiently add, remove, and find elements.
- Algorithms: These are the step-by-step instructions that do things like sorting and searching. They work on the data in your containers to get the job done efficiently.
- Iterators: These act like markers, helping you move through the data in your containers. They let you get to and change the data inside.
- Functors: These are objects that act like functions. You can pass them around and use them in different parts of your code.
Q7. How does the ‘std::sort’ function work in C++?
The std::sort function in C++’s Standard Template Library (STL) is a powerful tool for sorting. It uses Introsort, a smart mix of three sorting methods: Quicksort, Heapsort, and Insertion Sort. This function is declared in the program header file.
It sorts the elements of a given range from ‘first’ to ‘last’ by default in ascending order of the values. It can accept a comparison function by which it can be sorted in various orders per the client’s needs.
std::sort characteristics
- Speed and Efficiency: std::sort is quick, averaging a time complexity of O(n log n). What makes it unique is its ability to switch gears; when Quicksort encounters its worst-case scenario, it seamlessly transitions to Heapsort. And when dealing with small chunks of data, it uses Insertion Sort to keep things running smoothly.
- Versatile Sorting: Whether you’re working with arrays, vectors, or other data types, std::sort can handle them all. It doesn’t stop there—you can also sort custom data types, making it a flexible choice for different needs.
- Custom Sorting Rules: Want to sort in a way that’s not just ascending or descending? std::sort lets you define your own sorting rules through a custom comparator function, giving you full control over how the sorting happens.
- Working with Iterators: The function works directly with iterators, meaning you can decide exactly which part of your data to sort. This control over sorting ranges can be incredibly useful.
- Stability Considerations: By default, std::sort isn’t stable (meaning equal elements might not keep their original order). However, if stability is important to you, you can opt for a stable sorting algorithm as the base case.
Program:
#include <algorithm>
#include <vector>
std::vector<int> <var> = {8, 3, 1, 5, 2, 0};
std::sort(<var>.begin(), <var>.end()); // It will arrange the number in ascending order.
Program:
#include <iostream>
#include <algorithm> // Include for std::sort
using namespace std;
int main() {
// Initialize an array of integers
int arr[] = {3, 1, 4, 1, 5, 9, 2};
// Calculate the number of elements in the array
int n = sizeof(arr) / sizeof(arr[0]);
// Use std::sort to sort the array in ascending order
// std::sort takes two iterators: the beginning and the end of the range
sort(arr, arr + n);
// Output the sorted array
cout << "Sorted array: ";
for (int i = 0; i < n; ++i) {
cout << arr[i] << " "; // Print each element in the sorted array
}
cout << endl;
return 0;
}
- Describe vectors in C++.
A vector is a kind of dynamic array supplied by STL, which can adjust its capacity according to the amount of added or deleted elements. It allows one to access any element of the list randomly, and it is more flexible than the array. making them ideal for scenarios where the exact size of a collection is unknown at compile time.
Key characteristics
- Dynamic size: In Vectors, there is no need to worry about space because it grows or shrinks as you add or remove items.
- Random access: You can grab any item in a vector by its position, just like picking a book from a specific spot on a shelf.
- Efficient operations: Adding or removing items? Moving through the list? Vectors make these tasks quick and easy.
- Iterators: Vectors come with tools called iterators. These help you move through your list, item by item.
- STL compatibility: Vectors are part of C++’s Standard Template Library (STL), meaning they play nicely with lots of built-in functions and algorithms.
Vector’s operations:
- Adding to the End: Use push_back() when you want to pop a new item onto the end of your list.
- Removing from the End: Got an item at the end you don’t need anymore? pop_back() takes it off for you.
- Inserting in the Middle: insert() lets you drop an item right where you want it, even if it’s not at the end.
- Deleting Items: Need to get rid of one or more items? erase() can handle that, whether it’s just one or a whole range.
- Clearing the List: Want to start fresh? clear() wipes the vector clean.
- Checking Size: size() tells you how many items are in your list right now.
- Is It Empty?: Wondering if there’s anything in your list? empty() gives you a quick yes or no.
- Start and Finish: begin() and end() help you know where your list starts and where it wraps up, which is useful for looping through.
Syntax:
#include <vector>
vector<data_type> vector_name;
Program:
#include <iostream>
#include <vector> // Include the vector library
using namespace std;
int main() {
// Initialize a vector of integers
vector<int> vec = {1, 2, 3, 4, 5};
// Adding to the end of the vector using push_back()
vec.push_back(6);
// Removing the last element using pop_back()
vec.pop_back();
// Inserting an element in the middle using insert()
vec.insert(vec.begin() + 2, 10); // Insert 10 at the 3rd position (index 2)
// Deleting a specific element using erase()
vec.erase(vec.begin() + 2); // Erase the element at the 3rd position
// Clearing the vector using clear()
vec.clear();
// Checking if the vector is empty using empty()
if (vec.empty()) {
cout << "The vector is empty." << endl;
}
// Adding some elements again for size and iteration demonstration
vec.push_back(7);
vec.push_back(8);
vec.push_back(9);
// Checking the size of the vector using size()
cout << "The size of the vector is: " << vec.size() << endl;
// Iterating through the vector using begin() and end()
cout << "Vector elements: ";
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
Q8. Explain what the Map and Set containers are in C++.
Maps are associative containers in C++ that store elements as key-value pairs. Each key is unique, and the associated value can be any data type. Maps use a balanced binary search tree to organize the data or values. This makes the map efficient for quickly finding, adding, or removing data.
Key characteristics of maps:
- Associative: Elements are stored based on their keys.
- Ordered: Elements are stored in sorted order based on their keys.
- Unique keys: Each key must be unique.
- Efficient search: Search operations are typically logarithmic in time.
- Iterators: Maps provide iterators to traverse elements.
Common operations:
- insert(): Inserts a new key-value pair.
- find(): Searches for an element by its key.
- erase(): Removes an element by its key or iterator.
- count(): Checks if a key exists.
- begin() and end(): Returns iterators to the beginning and end of the map.
Syntax:
std::map<key_type, value_type> map_name;
map_name = {{key1, value1},{key2, value2}, ...};
Sets in C++ are collections that consist only of unique entities(values), preventing potential duplication of any values. These entities are usually organized in a specific order, often sorted from smallest to largest. Sets use a structure called a binary search tree to keep everything in order. This setup helps sets work efficiently, making it quick to search for an item, add a new one, or remove an existing one. The uniqueness of each item in a set is crucial, ensuring that every element is distinct, making sets an ideal choice for storing items where duplicates are not needed.
Key characteristics of sets:
- Associative: Elements are stored based on their values.
- Ordered: Elements are stored in sorted order.
- Unique elements: Each element must be unique.
- Efficient search: Search operations are typically logarithmic in time.
- Iterators: Sets provide iterators to traverse elements.
Common operations:
- insert(): Inserts a new element.
- find(): Searches for an element by its value.
- erase(): Removes an element by its value or iterator.
- count(): Checks if an element exists.
- begin() and end(): Returns iterators to the beginning and end of the set, respectively.
Syntax:
std::set <DataType> <set_name>;
Program:
#include <iostream>
#include <map> // Include for map
#include <set> // Include for set
using namespace std;
int main() {
// 1. MAP OPERATIONS
// Initialize a map (associative container with key-value pairs)
map<int, string> myMap;
// Insert elements into the map
myMap.insert({1, "One"});
myMap.insert({2, "Two"});
myMap.insert({3, "Three"});
// Find an element by key
auto it = myMap.find(2); // Find the element with key 2
if (it != myMap.end()) {
cout << "Found key 2 with value: " << it->second << endl;
}
// Erase an element by key
myMap.erase(2); // Erase the element with key 2
// Count the number of occurrences of a key
cout << "Count of key 2: " << myMap.count(2) << endl; // Should be 0 after deletion
// Iterate over the map using begin() and end()
cout << "Map elements: ";
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << "{" << it->first << ": " << it->second << "} ";
}
cout << endl;
// 2. SET OPERATIONS
// Initialize a set (container with unique elements)
set<int> mySet;
// Insert elements into the set
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
// Find an element in the set
auto sit = mySet.find(20); // Find the element 20
if (sit != mySet.end()) {
cout << "Found element: " << *sit << endl;
}
// Erase an element from the set
mySet.erase(20); // Erase the element 20
// Count the number of occurrences of an element
cout << "Count of element 20: " << mySet.count(20) << endl; // Should be 0 after deletion
// Iterate over the set using begin() and end()
cout << "Set elements: ";
for (auto sit = mySet.begin(); sit != mySet.end(); ++sit) {
cout << *sit << " ";
}
cout << endl;
return 0;
}
Q9. Write how Mutex should be used in C++.
Mutexes, is stands for “mutual exclusion objects,” are a mechanism that helps the operating system in the management of concurrency when only one thread has the privilege to access a given resource. It helps minimize or eradicate data races, thus making the process thread-safe.
Using a mutex to safeguard data involves a few straightforward steps:
- Include the <mutex> header: This provides access to the mutex functionality.
- Declare a std::mutex: This creates a mutex object to manage access to shared data.
- Lock the mutex: The lock() used before the read-and-write operations ensures exclusive access.
- Unlock the mutex: unlock() used after the read or write operations to release the mutex.
These steps help manage concurrent access to shared resources, preventing data corruption and ensuring safe operation.
Program:
#include <iostream>
#include <thread> // Include for threading
#include <mutex> // Include for mutex
using namespace std;
mutex mtx; // Create a global mutex object
// Function to print numbers (shared resource)
void printNumbers(int n) {
// Lock the mutex to ensure exclusive access to the shared resource
mtx.lock();
// Critical section: only one thread can access this at a time
for (int i = 1; i <= n; ++i) {
cout << i << " ";
}
cout << endl;
// Unlock the mutex to allow other threads to access the resource
mtx.unlock();
}
int main() {
// Create two threads that both call the printNumbers function
thread t1(printNumbers, 5);
thread t2(printNumbers, 5);
// Wait for both threads to finish execution
t1.join();
t2.join();
return 0;
}
Also Read: Top 10 Data Engineer Interview Questions in 2024
Technical Questions:
Q1. What do you mean by call by value and call by reference?
Call by Value
In call by value, a copy of the argument is passed to the function. Any modifications made to the argument within the function do not affect the original value outside the function. This way, the original value stays the same.
Call by Reference
In call by reference, instead of a copy, the function gets a direct link to the original argument. Any changes made inside the function will change the original value outside. This allows the function to directly modify the variables it receives.
Call by value makes a copy, keeping the original safe from changes. Call by reference gives access to the original, letting the function make changes directly.
Q2. What do you mean by abstraction in C++?
The abstraction is achieved through classes and objects. Which holds objects’ properties (Data members) and behaviors (member functions).
The implementation of these data members and member functions is completely hidden inside the class, providing a clear separation between the object’s interface and its implementation. This approach allows the use of objects without seeing the implementation of code, supporting code reusability, modularity, and ease of maintenance.
Like Java and c#, there is no abstract keyword in C++. To achieve the abstraction in C++, it’s important to have at least one pure virtual function to consider the class as an abstract class.
Syntax:
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
Q3. Explain constructor in C++.
Constructor is a member function of a class that is automatically executed when an object is created. The constructor has the same name as the class and does not return any value, not even void. Whether the class is public or private, constructors help maintain the structure and integrity of the object, making sure it’s ready for whatever tasks it will perform. In essence, constructors are the starting point for any object in a class, setting the foundation for its operations.
Syntax:
class MyName {
public:
MyName(parameter_list) { // Constructor body
}
};
Types of Constructors:
- Default Constructor: Automatically called by the compiler when no arguments are provided.
- Parameterized Constructor: When arguments are passed, it initializes the data members of an object.
- Copy Constructor: This takes another constructor of the same class as an argument.
- Move Constructor: This constructor takes an rvalue reference to another object of the same class and transfers its resources to the new object.
Q4. What is operator overloading?
In C++, operator overloading is used to change the primary behavior of built-in operators like +, -, *, etc. Instead of using standard operations, it can specify how these operators work with objects of the class, making the operations more intuitive for specific data types.
Key points about operator overloading:
- Overloading operators: Most built-in operators can be overloaded except for a few like ‘.‘, ‘?’, and ’:’.
- Custom behavior: Allow to define the specific actions that should occur when an operator is applied to objects of your class.
Q5. What is polymorphism in C++?
Polymorphism plays a crucial role in effectively dealing with different types of objects. It allows a single piece of code to be utilized for various subclasses, regardless of whether the types are known in advance or not.
Polymorphism is beneficial for managing diverse object types, as it simplifies the process of maintaining and extending code by enabling the treatment of different derived classes through a common interface.
There are two main types of polymorphism in C++: Compile-time polymorphism and Runtime polymorphism.
Also Read: Best Interview Questions for Data Analysts in 2024
Conclusion
While it is necessary to be acquainted with the general overview of C++ and its peculiarities, one must also possess certain skills related to online interviews. With the right approaches and employing techniques during an interview, you can convince the interviewer that you have well-engraved concepts and are prepared to work with online tools and facilities. This guide provides the novice and even the advanced developer with the correct tools and approaches to tackle a C++ interview and ensure employment in their preferred company.