Knowledge / Computer Applications / C++ essentials

C++ essentials

Computer Applications (BCA) · Programming · free study notes for exams, placements and interviews

In short

C++ is a compiled, statically typed language created by Bjarne Stroustrup (1979-83, "C with Classes") that adds classes, function and operator overloading, references, templates, exceptions and the Standard Template Library (STL) on top of C, while keeping C's performance and low-level control. It is standardised by ISO/IEC 14882 — commonly used editions are C++11, C++14, C++17 and C++20 (C++23 is the latest edition); compile with g++ -std=c++17. In BCA/BSc-CS and MCA syllabi (IGNOU, Pune, Mumbai, Bangalore City University, AICTE model curriculum) it is the standard vehicle for teaching object-oriented programming, and it carries marks in UGC-NET and university theory and practical exams (GATE CS sets its programming questions in C, not C++). In placements it is the default language for coding rounds at TCS NQT, Infosys, Wipro, Cognizant, Zoho, Amazon and most competitive-programming based hiring, and in industry it runs trading engines, embedded firmware, CAD/graphics, databases and game engines.

Explained

From C to C++: structure, I/O and type safety

Functions: overloading, defaults, inline, templates of behaviour

Classes in C++: members, constructors, static, friend, this

Operator overloading and type conversion

Inheritance and virtual functions (the C++ mechanics)

Templates, STL and generic programming

ContainerStructureTypical cost
vectordynamic arrayindex O(1), push_back amortised O(1), middle insert O(n)
dequesegmented arraypush/pop both ends O(1)
listdoubly linked listinsert/erase O(1) at a known position, no indexing
set / mapbalanced BST (red-black)find/insert/erase O(log n), sorted order
unordered_set / unordered_maphash tableaverage O(1), worst O(n), unordered
stack / queue / priority_queueadaptorspush/pop O(1); priority_queue top O(1), push/pop O(log n)

Exception handling and file streams

Key points

Examples

1. Constructor/destructor order and the static counter.

#include <iostream>
using namespace std;
class Student {
    static int count;          // shared
    int roll;
public:
    Student(int r) : roll(r) { ++count; cout << "ctor " << roll << " "; }
    ~Student()               { --count; cout << "dtor " << roll << " "; }
    static int alive()       { return count; }
};
int Student::count = 0;        // definition outside the class
int main() {
    Student a(101), b(102);
    { Student c(103); cout << "| alive=" << Student::alive() << " "; }
    cout << "| alive=" << Student::alive() << endl;
}

Step by step: a then b then c are constructed → count = 3 → inner block ends, c is destroyed → count = 2 → b then a destroyed (reverse order). Output: ctor 101 ctor 102 ctor 103 | alive=3 dtor 103 | alive=2 dtor 102 dtor 101

2. Virtual function: runtime polymorphism, with numbers.

class Shape { public: virtual double area() const = 0; virtual ~Shape() {} };
class Rect : public Shape { double w,h; public:
    Rect(double a,double b):w(a),h(b){} double area() const override { return w*h; } };
class Circle : public Shape { double r; public:
    Circle(double x):r(x){} double area() const override { return 3.14159*r*r; } };

Shape* s[2] = { new Rect(4,2.5), new Circle(3) };
double total = 0; for (int i=0;i<2;i++) total += s[i]->area();

If virtual were removed from area(), each call would bind to Shape::area by pointer type — with a pure virtual that is a compile error, and with a Shape::area() returning 0 the total would print 0. That contrast is the standard exam question.

3. Operator overloading on a Complex class.

class Complex {
    double re, im;
public:
    Complex(double r = 0, double i = 0) : re(r), im(i) {}
    Complex operator+(const Complex &c) const { return Complex(re+c.re, im+c.im); }
    Complex operator*(const Complex &c) const {
        return Complex(re*c.re - im*c.im, re*c.im + im*c.re);
    }
    double abs() const { return sqrt(re*re + im*im); }
    friend ostream& operator<<(ostream &o, const Complex &c) {
        return o << c.re << (c.im < 0 ? "" : "+") << c.im << "i";
    }
};
Complex p(3,4), q(1,2);

4. STL in one program (a frequent coding-round pattern).

vector<int> v{42, 17, 93, 17, 8};
sort(v.begin(), v.end());                       // 8 17 17 42 93
int sum   = accumulate(v.begin(), v.end(), 0);  // 177
int mx    = *max_element(v.begin(), v.end());   // 93
int twos  = count(v.begin(), v.end(), 17);      // 2
bool has42 = binary_search(v.begin(), v.end(), 42); // true (sorted)
map<string,int> freq;                           // word count
for (string w : {"c++","java","c++"}) freq[w]++;  // c++ -> 2, java -> 1

Check: 42 + 17 + 93 + 17 + 8 = 177. map prints in key order: c++ 2, java 1; unordered_map would print the same pairs in an unspecified order.

**5. Object layout and padding (sizeof).** On a typical 64-bit g++ build (sizes are implementation-defined):

struct A { int i; double d; char c; };  // 4 + 4 pad + 8 + 1 + 7 pad = 24
struct B { double d; int i; char c; };  // 8 + 4 + 1 + 3 pad = 16
FeatureCC++
ParadigmProceduralProcedural + OOP + generic
Data hidingNone (struct members public)private/protected/public
I/Oprintf/scanf (format strings)cout/cin (type-safe streams)
Memorymalloc/freenew/delete, smart pointers
OverloadingNot allowedFunctions and operators
Error handlingReturn codes, errnoExceptions + return codes
ReuseFunctions, copy-pasteClasses, inheritance, templates, STL
BindingWhen decidedMechanismExample
Static (early)Compile timeOverload resolution, name lookupoverloaded functions, templates, non-virtual calls
Dynamic (late)Run timevptr → vtable lookupvirtual function via base pointer/reference

Where it is used

Interview questions

Common mistakes

Related topics

C programming fundamentals · Pointers and dynamic memory · Object-oriented programming concepts · Java essentials · Data structures and algorithms · C# and .NET basics

Open in the Knowledge reader →Find jobs →