Menu
CoddyTech

C++ Basics Interview Questions

Basics from campus placements: C vs C++, compilation, operators, sizeof and tricky keywords.

15 questions
  1. What is C++ and how is it different from C?

    A compiled, statically typed language that keeps almost all of C and adds classes, references, templates, exceptions, overloading, RAII and a library of containers and algorithms.

    Not every C program is valid C++: int *p = malloc(4); needs a cast, and class and new are reserved words. The syntax fits in the C++ cheat sheet.

  2. What happens when you compile a C++ program?

    Preprocessing expands #include and macros, compilation turns each .cpp into assembly, assembly produces object files, and linking joins them with libraries into an executable.

    "not declared in this scope" is a compiler error; "undefined reference to foo()" is a linker error, usually a missing .cpp or library.

  3. What do 7 / 2, 7 % 2 and 7 / 2.0 give in C++?

    C++
    #include <iostream>
    using namespace std;
    
    int main() {
        int a = 7, b = 2;
        cout << a / b << " " << a % b << " " << a / 2.0 << endl;
        return 0;
    }

    It prints 3 1 3.5. 7 / 2 with two ints truncates to 3, and 7 % 2 is 1. In a / 2.0 one operand is a double, so the result is 3.5.

    Division truncates toward zero (guaranteed since C++11), so -7 / 2 is -3 and -7 % 2 is -1.

  4. How do a++ and ++a differ when assigned to another variable?

    C++
    #include <iostream>
    using namespace std;
    
    int main() {
        int a = 5;
        int b = a++;
        int c = ++a;
        cout << a << " " << b << " " << c << endl;
        return 0;
    }

    It prints 7 5 7. a++ returns the old value (5) and then makes a 6; ++a increments to 7 first and returns 7.

    The trap is i++ + ++i, which modifies i twice without sequencing: undefined behavior, so no answer is right.

  5. What is the difference between a struct and a class in C++?

    Only the default access. Members and base classes of a struct are public by default; in a class they are private.

    C++
    #include <iostream>
    
    struct Point {
        int x = 1;            // public by default
    };
    
    class Account {
        int balance = 100;    // private by default
    public:
        int get() const { return balance; }
    };
    
    int main() {
        Point p;
        Account acc;
        std::cout << p.x << " " << acc.get() << "\n";
        // acc.balance would not compile: it is private
    }

    This prints 1 100. By convention, struct is for plain data with no invariants and class for a type that protects its state.

  6. Do sizeof and strlen agree on char s[] = "hello"?

    C++
    #include <iostream>
    #include <cstring>
    
    int main() {
        char s[] = "hello";
        std::cout << sizeof(s) << " " << strlen(s) << "\n";
    }

    It prints 6 5. sizeof(s) is the size of the array, five letters plus the '\0'; strlen(s) counts up to the '\0'.

    For a const char*, or an array passed to a function, sizeof gives the pointer's size (8 on 64-bit).

  7. What is the sizeof of an empty class in C++?

    C++
    #include <iostream>
    
    class Empty {};
    class WithInt { int x; };
    
    int main() {
        std::cout << sizeof(Empty) << " " << sizeof(WithInt) << "\n";
    }

    It prints 1 4. An empty class still has a nonzero size, 1 on every mainstream compiler, because every object must have its own address.

    Used as a base class it may take zero bytes (the empty base optimization), and C++20's [[no_unique_address]] gives the same saving for an empty member (MSVC ignores it and needs [[msvc::no_unique_address]]; see the no_unique_address reference).

  8. What is a namespace, and why is using namespace std; considered bad practice?

    A namespace is a named scope that keeps names apart, so std::sort and mylib::sort can coexist. using namespace std; pulls every std name into scope; in a header it leaks into every includer, and names like count clash with yours. It is fine in a small .cpp file.

  9. What is the difference between #include <file> and #include "file", and what are include guards?

    #include <file> searches the system include paths; #include "file" usually searches the current file's directory first, then the system paths. An include guard stops a header from being pasted twice into one translation unit.

    #ifndef SHAPE_H
    #define SHAPE_H
    class Shape { /* ... */ };
    #endif
    

    #pragma once does the same in one line; it is not standard, but GCC, Clang and MSVC support it.

  10. What is the difference between std::endl and '\n'?

    std::endl writes a newline and flushes the stream; '\n' only writes the newline. In a loop printing a million lines, the flushes can make endl several times slower.

    Use '\n' by default and flush only when output must appear at once, such as a progress line. std::cerr flushes after every write anyway.

  11. What is function overloading in C++?

    Several functions share a name but differ in the number or types of parameters; the compiler picks one at compile time from the arguments.

    C++
    #include <iostream>
    using namespace std;
    
    int area(int side) { return side * side; }
    int area(int w, int h) { return w * h; }
    double area(double r) { return 3.14159 * r * r; }
    
    int main() {
        cout << area(4) << " " << area(3, 5) << " " << area(1.0) << "\n";
    }

    This prints 16 15 3.14159. The return type alone cannot tell overloads apart. Each name is mangled with its parameter types, and extern "C" turns that off. More in the function overloading docs.

  12. What is an inline function in C++?

    inline lets a function (and, since C++17, a variable) be defined in a header included by many .cpp files without breaking the one definition rule. Whether a call is inlined is the compiler's choice, keyword or not.

    Unlike a macro it checks types and evaluates arguments once: #define SQ(x) x*x makes SQ(1+2) equal 5.

  13. What are the uses of the static keyword in C++?

    Four meanings: a local keeps its value between calls and is initialized once; a data member is shared by all objects; a member function has no this; and at namespace scope it gives internal linkage, visible only in that .cpp file.

    C++
    #include <iostream>
    
    int nextId() {
        static int id = 0;    // initialized once
        return ++id;
    }
    
    struct Counter {
        static int created;
        Counter() { ++created; }
    };
    int Counter::created = 0;
    
    int main() {
        nextId();
        nextId();
        std::cout << nextId() << "\n";
        Counter a, b, c;
        std::cout << Counter::created << "\n";
    }

    This prints 3 and then 3.

  14. How does exception handling work in C++?

    throw raises an exception object and the first catch whose type matches handles it. On the way, the stack unwinds and every local object in between is destroyed.

    C++
    #include <iostream>
    #include <stdexcept>
    #include <vector>
    using namespace std;
    
    int main() {
        vector<int> v = {1, 2, 3};
        try {
            cout << v.at(5) << "\n";
        } catch (const out_of_range&) {
            cout << "out_of_range caught\n";
        } catch (const exception& e) {
            cout << "other: " << e.what() << "\n";
        }
    }

    This prints out_of_range caught. Catch by const& to avoid slicing and put the most derived handler first. An uncaught exception calls std::terminate. More in the try and catch docs.

  15. Does member order affect a struct's sizeof on a 64-bit system?

    C++
    #include <iostream>
    
    struct A { char c; int i; char d; };
    struct B { int i; char c; char d; };
    
    int main() {
        std::cout << sizeof(A) << " " << sizeof(B) << "\n";
    }

    It prints 12 8 on x86-64 and ARM64 with GCC, Clang or MSVC. An int must start at an address divisible by 4, so A gets 3 bytes of padding after c and 3 after d to keep its size a multiple of 4. In B the two chars share one padded block. Order members from largest to smallest alignment to save space.

Coddy programming languages illustration

Learn to code with Coddy

Get started