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, andclassandneware reserved words. The syntax fits in the C++ cheat sheet.What happens when you compile a C++ program?
Preprocessing expands
#includeand macros, compilation turns each.cppinto 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.cppor library.What do
7 / 2,7 % 2and7 / 2.0give 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 / 2with twoints truncates to 3, and7 % 2is 1. Ina / 2.0one operand is adouble, so the result is 3.5.Division truncates toward zero (guaranteed since C++11), so
-7 / 2is-3and-7 % 2is-1.How do
a++and++adiffer 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 makesa6;++aincrements to 7 first and returns 7.The trap is
i++ + ++i, which modifiesitwice without sequencing: undefined behavior, so no answer is right.What is the difference between a struct and a class in C++?
Only the default access. Members and base classes of a
structarepublicby default; in aclassthey areprivate.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,structis for plain data with no invariants andclassfor a type that protects its state.Do
sizeofandstrlenagree onchar 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,sizeofgives the pointer's size (8 on 64-bit).What is the
sizeofof 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).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::sortandmylib::sortcan coexist.using namespace std;pulls everystdname into scope; in a header it leaks into every includer, and names likecountclash with yours. It is fine in a small.cppfile.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 oncedoes the same in one line; it is not standard, but GCC, Clang and MSVC support it.What is the difference between
std::endland'\n'?std::endlwrites a newline and flushes the stream;'\n'only writes the newline. In a loop printing a million lines, the flushes can makeendlseveral times slower.Use
'\n'by default and flush only when output must appear at once, such as a progress line.std::cerrflushes after every write anyway.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, andextern "C"turns that off. More in the function overloading docs.What is an inline function in C++?
inlinelets a function (and, since C++17, a variable) be defined in a header included by many.cppfiles 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*xmakesSQ(1+2)equal 5.What are the uses of the
statickeyword 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.cppfile.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
3and then3.How does exception handling work in C++?
throwraises an exception object and the firstcatchwhose 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 byconst&to avoid slicing and put the most derived handler first. An uncaught exception callsstd::terminate. More in the try and catch docs.Does member order affect a struct's
sizeofon 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 8on x86-64 and ARM64 with GCC, Clang or MSVC. Anintmust start at an address divisible by 4, soAgets 3 bytes of padding aftercand 3 afterdto keep its size a multiple of 4. InBthe twochars share one padded block. Order members from largest to smallest alignment to save space.
C++ Basics Interview Questions
Basics from campus placements: C vs C++, compilation, operators, sizeof and tricky keywords.