PapersAdda

Cpp Programming Placement Questions

19 min read
Uncategorized
Advertisement Placement

C++ Programming Questions for Placement 2026 (with Solutions)

Last Updated: March 2026


Introduction

C++ remains one of the most sought-after programming languages in the placement circuit. Its combination of low-level memory manipulation and high-level object-oriented features makes it a favorite among companies like Google, Amazon, Microsoft, TCS, Infosys, and product-based organizations. C++ tests candidates on OOP concepts, STL proficiency, and algorithmic problem-solving.

Why C++ is Important for Placements

  1. Object-Oriented Foundation: OOP concepts learned in C++ apply to Java, C#, and other languages
  2. STL Library: Rich standard template library for efficient coding
  3. Performance: Tests understanding of time and space complexity
  4. Industry Usage: Widely used in game development, systems programming, and competitive programming
  5. Competitive Edge: Fast execution makes it ideal for coding competitions

Companies Testing C++ Programming

CompanyDifficultyCommon Topics
GoogleHardOOP, STL, Algorithms, Data Structures
AmazonHardOOP Design, Problem Solving
MicrosoftHardC++ concepts, System Design
TCSModerateBasics, OOP, Simple programs
InfosysModerateClasses, Inheritance, Polymorphism
DirectiHardAdvanced C++, Algorithms
AdobeHardOOP, Memory Management

Frequently Asked Coding Questions with Solutions

Question 1: Class and Object Basics

Problem: Create a Student class with name, roll number, and marks. Include methods to display details and calculate grade.

Solution:

#include <iostream>
#include <string>
using namespace std;

class Student {
private:
    string name;
    int rollNumber;
    float marks;

public:
    // Constructor
    Student(string n, int r, float m) {
        name = n;
        rollNumber = r;
        marks = m;
    }
    
    // Method to display details
    void displayDetails() {
        cout << "Name: " << name << endl;
        cout << "Roll Number: " << rollNumber << endl;
        cout << "Marks: " << marks << endl;
        cout << "Grade: " << calculateGrade() << endl;
    }
    
    // Method to calculate grade
    char calculateGrade() {
        if (marks >= 90) return 'A';
        else if (marks >= 80) return 'B';
        else if (marks >= 70) return 'C';
        else if (marks >= 60) return 'D';
        else return 'F';
    }
};

int main() {
    Student s1("John Doe", 101, 85.5);
    Student s2("Jane Smith", 102, 92.0);
    
    cout << "Student 1 Details:" << endl;
    s1.displayDetails();
    
    cout << "\nStudent 2 Details:" << endl;
    s2.displayDetails();
    
    return 0;
}

Output:

Student 1 Details:
Name: John Doe
Roll Number: 101
Marks: 85.5
Grade: B

Student 2 Details:
Name: Jane Smith
Roll Number: 102
Marks: 92
Grade: A

Question 2: Inheritance Example

Problem: Demonstrate inheritance with Employee as base class and Manager as derived class.

Solution:

#include <iostream>
#include <string>
using namespace std;

// Base class
class Employee {
protected:
    string name;
    int id;
    double salary;

public:
    Employee(string n, int i, double s) {
        name = n;
        id = i;
        salary = s;
    }
    
    virtual void displayInfo() {
        cout << "Employee ID: " << id << endl;
        cout << "Name: " << name << endl;
        cout << "Salary: $" << salary << endl;
    }
    
    virtual double calculateBonus() {
        return salary * 0.10;  // 10% bonus
    }
};

// Derived class
class Manager : public Employee {
private:
    int teamSize;
    string department;

public:
    Manager(string n, int i, double s, int ts, string dept) 
        : Employee(n, i, s) {
        teamSize = ts;
        department = dept;
    }
    
    void displayInfo() override {
        Employee::displayInfo();
        cout << "Department: " << department << endl;
        cout << "Team Size: " << teamSize << endl;
    }
    
    double calculateBonus() override {
        return salary * 0.20;  // 20% bonus for managers
    }
};

int main() {
    Employee emp("Alice", 1001, 50000);
    Manager mgr("Bob", 1002, 80000, 10, "Engineering");
    
    cout << "=== Employee Details ===" << endl;
    emp.displayInfo();
    cout << "Bonus: $" << emp.calculateBonus() << endl;
    
    cout << "\n=== Manager Details ===" << endl;
    mgr.displayInfo();
    cout << "Bonus: $" << mgr.calculateBonus() << endl;
    
    return 0;
}

Output:

=== Employee Details ===
Employee ID: 1001
Name: Alice
Salary: $50000
Bonus: $5000

=== Manager Details ===
Employee ID: 1002
Name: Bob
Salary: $80000
Department: Engineering
Team Size: 10
Bonus: $16000

Question 3: Operator Overloading

Problem: Overload the + operator to add two Complex numbers.

Solution:

#include <iostream>
using namespace std;

class Complex {
private:
    double real;
    double imag;

public:
    // Constructor
    Complex(double r = 0, double i = 0) {
        real = r;
        imag = i;
    }
    
    // Overload + operator
    Complex operator+(const Complex& other) {
        Complex temp;
        temp.real = real + other.real;
        temp.imag = imag + other.imag;
        return temp;
    }
    
    // Overload << operator for easy output
    friend ostream& operator<<(ostream& out, const Complex& c) {
        out << c.real;
        if (c.imag >= 0)
            out << " + " << c.imag << "i";
        else
            out << " - " << -c.imag << "i";
        return out;
    }
    
    // Overload >> operator for input
    friend istream& operator>>(istream& in, Complex& c) {
        cout << "Enter real part: ";
        in >> c.real;
        cout << "Enter imaginary part: ";
        in >> c.imag;
        return in;
    }
};

int main() {
    Complex c1(3, 4), c2(1, 2);
    Complex c3;
    
    cout << "First complex number: " << c1 << endl;
    cout << "Second complex number: " << c2 << endl;
    
    c3 = c1 + c2;  // Using overloaded + operator
    cout << "Sum: " << c3 << endl;
    
    return 0;
}

Output:

First complex number: 3 + 4i
Second complex number: 1 + 2i
Sum: 4 + 6i

Question 4: STL Vector Operations

Problem: Demonstrate various STL vector operations.

Solution:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    // Creating and initializing vector
    vector<int> vec = {5, 2, 8, 1, 9, 3};
    
    cout << "Original vector: ";
    for (int x : vec) cout << x << " ";
    cout << endl;
    
    // Adding elements
    vec.push_back(7);
    vec.emplace_back(4);
    
    cout << "After push_back: ";
    for (int x : vec) cout << x << " ";
    cout << endl;
    
    // Sorting
    sort(vec.begin(), vec.end());
    cout << "Sorted vector: ";
    for (int x : vec) cout << x << " ";
    cout << endl;
    
    // Binary search (on sorted vector)
    if (binary_search(vec.begin(), vec.end(), 5))
        cout << "5 is found in vector" << endl;
    
    // Finding min and max
    auto minMax = minmax_element(vec.begin(), vec.end());
    cout << "Min: " << *minMax.first << ", Max: " << *minMax.second << endl;
    
    // Size and capacity
    cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << endl;
    
    // Using iterator
    cout << "Using iterator: ";
    for (auto it = vec.begin(); it != vec.end(); ++it)
        cout << *it << " ";
    cout << endl;
    
    return 0;
}

Output:

Original vector: 5 2 8 1 9 3
After push_back: 5 2 8 1 9 3 7 4
Sorted vector: 1 2 3 4 5 7 8 9
5 is found in vector
Min: 1, Max: 9
Size: 8, Capacity: 12
Using iterator: 1 2 3 4 5 7 8 9

Question 5: Template Class

Problem: Create a generic Stack class using templates.

Solution:

#include <iostream>
#include <vector>
using namespace std;

template <typename T>
class Stack {
private:
    vector<T> elements;

public:
    // Push element
    void push(const T& element) {
        elements.push_back(element);
    }
    
    // Pop element
    void pop() {
        if (!isEmpty()) {
            elements.pop_back();
        } else {
            cout << "Stack is empty!" << endl;
        }
    }
    
    // Get top element
    T& top() {
        return elements.back();
    }
    
    // Check if empty
    bool isEmpty() const {
        return elements.empty();
    }
    
    // Get size
    size_t size() const {
        return elements.size();
    }
    
    // Display stack
    void display() const {
        cout << "Stack (top to bottom): ";
        for (auto it = elements.rbegin(); it != elements.rend(); ++it)
            cout << *it << " ";
        cout << endl;
    }
};

int main() {
    // Stack of integers
    Stack<int> intStack;
    intStack.push(10);
    intStack.push(20);
    intStack.push(30);
    intStack.display();
    
    cout << "Top element: " << intStack.top() << endl;
    intStack.pop();
    intStack.display();
    
    // Stack of strings
    Stack<string> stringStack;
    stringStack.push("Hello");
    stringStack.push("World");
    stringStack.display();
    
    return 0;
}

Output:

Stack (top to bottom): 30 20 10
Top element: 30
Stack (top to bottom): 20 10
Stack (top to bottom): World Hello

Question 6: Exception Handling

Problem: Demonstrate exception handling with custom exception for division by zero.

Solution:

#include <iostream>
#include <stdexcept>
using namespace std;

// Custom exception class
class DivisionByZeroException : public exception {
public:
    const char* what() const noexcept override {
        return "Error: Division by zero is not allowed!";
    }
};

// Function that may throw exception
double safeDivide(double numerator, double denominator) {
    if (denominator == 0) {
        throw DivisionByZeroException();
    }
    return numerator / denominator;
}

int main() {
    double a, b;
    
    cout << "Enter numerator: ";
    cin >> a;
    cout << "Enter denominator: ";
    cin >> b;
    
    try {
        double result = safeDivide(a, b);
        cout << "Result: " << result << endl;
    }
    catch (const DivisionByZeroException& e) {
        cout << e.what() << endl;
    }
    catch (const exception& e) {
        cout << "Standard exception: " << e.what() << endl;
    }
    catch (...) {
        cout << "Unknown exception occurred!" << endl;
    }
    
    cout << "Program continues after exception handling..." << endl;
    
    return 0;
}

Output:

Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed!
Program continues after exception handling...

Question 7: Virtual Functions and Polymorphism

Problem: Demonstrate runtime polymorphism using virtual functions.

Solution:

#include <iostream>
using namespace std;

// Abstract base class
class Shape {
public:
    virtual double calculateArea() = 0;  // Pure virtual function
    virtual void display() = 0;           // Pure virtual function
    virtual ~Shape() {}  // Virtual destructor
};

class Rectangle : public Shape {
private:
    double length, width;

public:
    Rectangle(double l, double w) : length(l), width(w) {}
    
    double calculateArea() override {
        return length * width;
    }
    
    void display() override {
        cout << "Rectangle: Length=" << length << ", Width=" << width;
        cout << ", Area=" << calculateArea() << endl;
    }
};

class Circle : public Shape {
private:
    double radius;
    const double PI = 3.14159;

public:
    Circle(double r) : radius(r) {}
    
    double calculateArea() override {
        return PI * radius * radius;
    }
    
    void display() override {
        cout << "Circle: Radius=" << radius;
        cout << ", Area=" << calculateArea() << endl;
    }
};

class Triangle : public Shape {
private:
    double base, height;

public:
    Triangle(double b, double h) : base(b), height(h) {}
    
    double calculateArea() override {
        return 0.5 * base * height;
    }
    
    void display() override {
        cout << "Triangle: Base=" << base << ", Height=" << height;
        cout << ", Area=" << calculateArea() << endl;
    }
};

int main() {
    // Array of base class pointers
    Shape* shapes[3];
    
    shapes[0] = new Rectangle(5, 3);
    shapes[1] = new Circle(4);
    shapes[2] = new Triangle(6, 4);
    
    cout << "=== Shape Information ===" << endl;
    for (int i = 0; i < 3; i++) {
        shapes[i]->display();
    }
    
    // Calculate total area
    double totalArea = 0;
    for (int i = 0; i < 3; i++) {
        totalArea += shapes[i]->calculateArea();
    }
    cout << "\nTotal Area: " << totalArea << endl;
    
    // Clean up
    for (int i = 0; i < 3; i++) {
        delete shapes[i];
    }
    
    return 0;
}

Output:

=== Shape Information ===
Rectangle: Length=5, Width=3, Area=15
Circle: Radius=4, Area=50.2654
Triangle: Base=6, Height=4, Area=12

Total Area: 77.2654

Question 8: Map and Set Usage

Problem: Count word frequencies using map and demonstrate set operations.

Solution:

#include <iostream>
#include <map>
#include <set>
#include <string>
#include <sstream>
using namespace std;

int main() {
    // Word frequency counter using map
    string text = "the quick brown fox jumps over the lazy dog the fox was quick";
    map<string, int> wordFreq;
    
    stringstream ss(text);
    string word;
    
    while (ss >> word) {
        wordFreq[word]++;
    }
    
    cout << "=== Word Frequencies ===" << endl;
    for (const auto& pair : wordFreq) {
        cout << pair.first << ": " << pair.second << endl;
    }
    
    // Set operations
    set<int> set1 = {1, 2, 3, 4, 5};
    set<int> set2 = {4, 5, 6, 7, 8};
    
    cout << "\n=== Set Operations ===" << endl;
    
    // Union
    set<int> unionSet;
    set_union(set1.begin(), set1.end(), 
              set2.begin(), set2.end(),
              inserter(unionSet, unionSet.begin()));
    
    cout << "Union: ";
    for (int x : unionSet) cout << x << " ";
    cout << endl;
    
    // Intersection
    set<int> interSet;
    set_intersection(set1.begin(), set1.end(),
                     set2.begin(), set2.end(),
                     inserter(interSet, interSet.begin()));
    
    cout << "Intersection: ";
    for (int x : interSet) cout << x << " ";
    cout << endl;
    
    // Check existence in set
    if (set1.find(3) != set1.end()) {
        cout << "3 is in set1" << endl;
    }
    
    return 0;
}

Output:

=== Word Frequencies ===
brown: 1
dog: 1
fox: 2
jumps: 1
lazy: 1
over: 1
quick: 2
the: 3
was: 1

=== Set Operations ===
Union: 1 2 3 4 5 6 7 8
Intersection: 4 5
3 is in set1

Question 9: Function Overloading and Default Arguments

Problem: Demonstrate function overloading and default parameters.

Solution:

#include <iostream>
#include <string>
using namespace std;

// Function overloading - same name, different parameters
class Calculator {
public:
    // Overload 1: Add two integers
    int add(int a, int b) {
        cout << "Adding two integers: ";
        return a + b;
    }
    
    // Overload 2: Add three integers
    int add(int a, int b, int c) {
        cout << "Adding three integers: ";
        return a + b + c;
    }
    
    // Overload 3: Add two doubles
    double add(double a, double b) {
        cout << "Adding two doubles: ";
        return a + b;
    }
    
    // Overload 4: Concatenate strings
    string add(string a, string b) {
        cout << "Concatenating strings: ";
        return a + b;
    }
};

// Default arguments
void printInfo(string name, int age = 25, string city = "Unknown") {
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "City: " << city << endl;
}

int main() {
    Calculator calc;
    
    cout << calc.add(5, 3) << endl;
    cout << calc.add(5, 3, 2) << endl;
    cout << calc.add(5.5, 3.3) << endl;
    cout << calc.add(string("Hello "), string("World")) << endl;
    
    cout << "\n=== Default Arguments ===" << endl;
    printInfo("Alice");
    cout << endl;
    printInfo("Bob", 30);
    cout << endl;
    printInfo("Charlie", 35, "New York");
    
    return 0;
}

Output:

Adding two integers: 8
Adding three integers: 10
Adding two doubles: 8.8
Concatenating strings: Hello World

=== Default Arguments ===
Name: Alice
Age: 25
City: Unknown

Name: Bob
Age: 30
City: Unknown

Name: Charlie
Age: 35
City: New York

Question 10: File I/O Operations

Problem: Read from and write to files using C++ streams.

Solution:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

struct Student {
    string name;
    int rollNo;
    float marks;
};

void writeToFile(const vector<Student>& students, const string& filename) {
    ofstream outFile(filename);
    
    if (!outFile) {
        cerr << "Error opening file for writing!" << endl;
        return;
    }
    
    for (const auto& student : students) {
        outFile << student.name << " " 
                << student.rollNo << " " 
                << student.marks << endl;
    }
    
    outFile.close();
    cout << "Data written successfully!" << endl;
}

vector<Student> readFromFile(const string& filename) {
    vector<Student> students;
    ifstream inFile(filename);
    
    if (!inFile) {
        cerr << "Error opening file for reading!" << endl;
        return students;
    }
    
    Student s;
    while (inFile >> s.name >> s.rollNo >> s.marks) {
        students.push_back(s);
    }
    
    inFile.close();
    return students;
}

int main() {
    vector<Student> students = {
        {"Alice", 101, 85.5},
        {"Bob", 102, 90.0},
        {"Charlie", 103, 78.5}
    };
    
    string filename = "students.txt";
    
    // Write to file
    writeToFile(students, filename);
    
    // Read from file
    cout << "\nReading from file:" << endl;
    vector<Student> readStudents = readFromFile(filename);
    
    cout << "\n=== Student Records ===" << endl;
    for (const auto& s : readStudents) {
        cout << "Name: " << s.name 
             << ", Roll No: " << s.rollNo 
             << ", Marks: " << s.marks << endl;
    }
    
    return 0;
}

Output Prediction Questions (10 Questions)

Question 1: What is the output?

#include <iostream>
using namespace std;
int main() {
    int x = 5;
    cout << x++ << " " << ++x;
    return 0;
}

Question 2: What is the output?

#include <iostream>
using namespace std;
class Test {
public:
    Test() { cout << "Constructor\n"; }
    ~Test() { cout << "Destructor\n"; }
};
int main() {
    Test t;
    return 0;
}

Question 3: What is the output?

#include <iostream>
using namespace std;
int main() {
    int arr[] = {1, 2, 3, 4, 5};
    cout << *(arr + 3);
    return 0;
}

Question 4: What is the output?

#include <iostream>
using namespace std;
void fun(int x = 10, int y = 20) {
    cout << x << " " << y;
}
int main() {
    fun();
    return 0;
}

Question 5: What is the output?

#include <iostream>
using namespace std;
int main() {
    string s = "Hello";
    cout << s.length() << " " << s.size();
    return 0;
}

Question 6: What is the output?

#include <iostream>
using namespace std;
int main() {
    int *p = new int(10);
    cout << *p;
    delete p;
    return 0;
}

Question 7: What is the output?

#include <iostream>
using namespace std;
class Base {
public:
    virtual void show() { cout << "Base\n"; }
};
class Derived : public Base {
public:
    void show() { cout << "Derived\n"; }
};
int main() {
    Base *b = new Derived();
    b->show();
    return 0;
}

Question 8: What is the output?

#include <iostream>
using namespace std;
template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}
int main() {
    cout << max(3, 5);
    return 0;
}

Question 9: What is the output?

#include <iostream>
using namespace std;
int main() {
    int a = 5, b = 10;
    swap(a, b);
    cout << a << " " << b;
    return 0;
}

Question 10: What is the output?

#include <iostream>
using namespace std;
int main() {
    const int x = 10;
    // x = 20;  // Error
    cout << x;
    return 0;
}

MCQs on C++ Fundamentals (10 Questions)

Question 1: What is the default access specifier for class members?

a) public b) private c) protected d) none


Question 2: Which of the following is not a type of inheritance?

a) Single b) Multiple c) Hierarchical d) Distributed


Question 3: What does virtual keyword do?

a) Makes a variable constant b) Enables runtime polymorphism c) Creates a static member d) Allocates memory dynamically


Question 4: What is a pure virtual function?

a) A function with no implementation b) A virtual function declared with = 0 c) A static virtual function d) A private virtual function


Question 5: Which container stores unique elements only?

a) vector b) list c) set d) map


Question 6: What is the purpose of this pointer?

a) To point to previous object b) To point to the current object c) To point to the next object d) To point to the base class


Question 7: What is constructor overloading?

a) Having multiple constructors with different parameters b) Calling a constructor multiple times c) Creating constructor in derived class d) None of the above


Question 8: What does new operator do?

a) Deletes memory b) Allocates memory on stack c) Allocates memory on heap d) Creates a reference


Question 9: Which is used to handle exceptions?

a) if-else b) try-catch c) switch-case d) for loop


Question 10: What is the difference between struct and class?

a) No difference b) struct has public default access, class has private c) struct cannot have functions d) class cannot have data members


Tips for C++ Coding Rounds

1. Master OOP Concepts

  • Understand inheritance types and when to use them
  • Know the difference between compile-time and runtime polymorphism
  • Practice operator overloading
  • Understand virtual functions and vtables

2. STL Proficiency

  • Know when to use vector, list, deque
  • Understand map vs unordered_map tradeoffs
  • Practice using algorithms library
  • Master iterators

3. Memory Management

  • Understand new/delete vs malloc/free
  • Know smart pointers (unique_ptr, shared_ptr)
  • Avoid memory leaks
  • Understand RAII principle

4. Template Programming

  • Basic template syntax
  • Template specialization
  • STL container usage with custom types

5. Best Practices

  • Use const correctness
  • Prefer references over pointers when possible
  • Use range-based for loops
  • Leverage auto keyword appropriately

Frequently Asked Questions (FAQ)

Q1: Is C++ better than Java for placements?

Both have their strengths. C++ is preferred for systems programming, game development, and competitive programming due to speed. Java is preferred for enterprise applications. Know one language deeply and be familiar with the other.

Q2: What are the most important C++ topics for placements?

Focus on: OOP concepts (inheritance, polymorphism, encapsulation), STL (vectors, maps, sets, algorithms), Pointers and references, Templates, Exception handling, Memory management, and Operator overloading.

Q3: Should I use C or C++ for placements?

C++ is generally preferred as it includes C and adds OOP and STL capabilities. However, some companies specifically ask for C. Be comfortable with both, but master C++ for object-oriented and STL advantages.

Q4: How important is STL for placements?

Very important! STL knowledge can significantly reduce coding time and improve efficiency. Know containers (vector, list, map, set), iterators, and algorithms (sort, binary_search, find, etc.).

Q5: What is the difference between struct and class in C++?

The only difference is default access: struct members are public by default, class members are private by default. Otherwise, they are identical in C++ (unlike C where struct cannot have methods).


Master C++ through consistent practice focusing on OOP concepts, STL proficiency, and problem-solving. Practice writing clean, efficient code using modern C++ features. Good luck with your placement preparation!

Advertisement Placement

Explore this topic cluster

More resources in Uncategorized

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

More in Uncategorized

More from PapersAdda

Share this article: