C++
1. C vs C++
C++ is a superset of C, offering OOP, exception handling, and better memory management,STL making it more versatile
2. Signed vs Unsigned
Overflow in signed integers results in undefined behavior.
Overflow in unsigned integers wraps back to zero.
Signed integers: Support negative values.
Unsigned integers: Only support positive values but have higher range
3. What is reference variable?
Unlike pointers, references cannot be null and must be initialized.
int* ptr = nullptr; // Valid
int& ref = nullptr; // Invalid (won't compile)
int x = 10;
int& ref = x; // Valid
int& ref2; // Invalid (must be initialized)
4. sizeof Operator
Returns the size (in bytes) of a variable or data type.
5. typedef in C++
typedef is a keyword in C++ (and C) used to create type aliases. It allows you to define a new name for an existing type, making code more readable and maintainable.
typedef unsigned int uint;
uint age = 25; // Equivalent to unsigned int age = 25;
6. OOPs
A way of writing programs by creating objects. An object is an instance of class that has properties (data) and behavior (actions)
A class is like a template or blueprint that defines the structure of an object. Objects are created from classes.
We use oops to make programs simple & organized, make the code reusable, Better for big projects
Pillars:
Inheritance - Inheritance allows one class to take features (properties & actions) from another class.
A "Vehicle" class has wheels and engine. A "Car" class can inherit this and add extra features like doors, air conditioning, etc.
π» In C++ Code:
class Vehicle {
public:
int wheels = 4;
void start() {
cout << "Vehicle is starting..." << endl;
}
};
// Car class inherits Vehicle class
class Car : public Vehicle {
public:
string brand;
};
int main() {
Car myCar;
myCar.start(); // Inherited from Vehicle class
cout << "Car has " << myCar.wheels << " wheels" << endl;
}
π Car is inheriting Vehicle. That means Car automatically gets all the properties of Vehicle.
Polymorphism:
Polymorphism means the same function behaves differently for different objects.
π‘ Example:
A Person can be a Teacher at School π and a Father at Home π‘. Same person, but different roles.
There are two types of polymorphism:
β
Method Overloading (Same function, different parameters)
β
Method Overriding (Child class changes parent function)
π» In C++ Code (Overloading):
class Math {
public:
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
// Function to add three numbers
int add(int a, int b, int c) {
return a + b + c;
}
};
int main() {
Math obj;
cout << obj.add(2, 3) << endl; // Calls first add()
cout << obj.add(2, 3, 4) << endl; // Calls second add()
}
π Here, add() function works differently based on parameters.
π» In C++ Code (Overriding):
class Animal {
public:
void sound() {
cout << "Animals make sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() {
cout << "Dog barks" << endl;
}
};
int main() {
Dog myDog;
myDog.sound(); // Output: Dog barks
}
π Here, Dog overrides the sound() function of Animal.
Encapsulation:
Encapsulation β (Hiding Data for Security)
Encapsulation hides data to protect it and allows access only through special functions.
π‘ Example:
Your bank account details π¦ are private. You can only access them using an ATM card (a special function).
π» In C++ Code:
class BankAccount {
private:
int balance; // Private data
public:
void setBalance(int amount) {
balance = amount;
}
int getBalance() {
return balance;
}
};
int main() {
BankAccount myAccount;
myAccount.setBalance(5000);
cout << "Balance: " << myAccount.getBalance() << endl;
}
π The balance variable is hidden, and we use setBalance() & getBalance() to access it.
Abstraction β (Hiding Complex Details)
Abstraction means hiding unnecessary details and only showing important parts.
π‘ Example:
When you turn on a TV, πΊ you just press a button. You don't need to know how circuits work inside.
π» In C++ Code:
class Car {
public:
void startCar() {
startEngine();
cout << "Car is starting..." << endl;
}
private:
void startEngine() {
cout << "Engine started!" << endl;
}
};
int main() {
Car myCar;
myCar.startCar(); // Can't access startEngine() directly
}
π The startEngine() function is hidden (private), and we only use startCar().
Struct vs Class
Default Access Modifier:
- struct: public
- class: private
Final Keyword in C++
The final keyword prevents a class or function from being overridden or inherited.
Example:
class Base {
public:
virtual void show() final { // Cannot be overridden
std::cout << "Base class show()" << std::endl;
}
};
class Derived : public Base {
public:
// void show() override { } // Error: Cannot override final function
};
class FinalClass final {}; // Cannot be inherited
Dangling Pointer
A dangling pointer is a pointer that points to memory that has been deleted or deallocated.
#include <iostream>
using namespace std;
int main()
{
// Allocating memory
int* ptr = new int(5);
// Deallocating memory
delete ptr;
// Now, ptr becomes a dangling pointer
cout << *ptr << endl;
return 0;
}
Solution: Nullify the Pointer
delete ptr;
ptr = nullptr; // β
Safe: Now ptr does not point to invalid memory
What Does using namespace std; Do?
The Standard Library (std) contains built-in functions and classes, such as cout, cin, string, vector, etc. To access these, you usually prefix them with std::
However, writing std:: every time can be tedious. By adding:
using namespace std;
What is #include in C++?
The #include directive is a preprocessor command that allows you to include external files (header files) in your program before compilation.
Vector vs Array
// C++ program demonstrating how a dangling pointer is
// created
#include <iostream>
#include<vector>
using namespace std;
int main() {
int arr[5]={1,1,1,1,1};
vector<int>a;
cout<<"1st capacity and size of vector "<<a.capacity()<<" "<<a.size()<<endl;
for(int i=0;i<5;i++){
a.push_back(2);
}
cout<<"1st capacity and size of vector "<<a.capacity()<<" "<<a.size()<<endl;
a.push_back(2);
cout<<"1st capacity and size of vector "<<a.capacity()<<" "<<a.size()<<endl;
a.push_back(2);
cout<<"1st capacity and size of vector "<<a.capacity()<<" "<<a.size()<<endl;
a.push_back(2);
cout<<"1st capacity and size of vector "<<a.capacity()<<" "<<a.size()<<endl;
a.push_back(2);
cout<<"1st capacity and size of vector "<<a.capacity()<<" "<<a.size()<<endl;
}
Database
Types of DBMS
Hierarchical DBMS
π Data is organized like a tree (parent-child relationship).
π One parent can have multiple children, but each child has only one parent.
Network DBMS
π Similar to hierarchical DBMS, but a child can have multiple parents.
π Uses a graph structure instead of a tree.
Relational DBMS (RDBMS)
π Uses tables to store data.
π Data is related through keys (Primary Key, Foreign Key).
π Uses SQL (Structured Query Language) for queries.
NoSQL DBMS (Non-Relational DBMS)
π Designed for big data and unstructured/semi-structured data.
π Does not use traditional tables; instead, it uses:
- Key-Value Stores (Redis, DynamoDB)
- Document Stores (MongoDB, CouchDB)
- Column-Family Stores (Cassandra, HBase)
- Graph Databases (Neo4j)
What is PostgreSQL
It is an ORDBMS (Object-Relational Database Management System).
PostgreSQL combines features of both RDBMS (Relational DBMS) and OODBMS (Object-Oriented DBMS).
PostgreSQL extends the traditional relational model by supporting object-oriented features such as:
- User-Defined Data Types
What is ORM
ORM (Object-Relational Mapping) is a technique that allows developers to interact with a relational database (like PostgreSQL, MySQL, etc.) using object-oriented programming (OOP) languages.
Instead of writing raw SQL queries (SELECT * FROM users), ORM lets you interact with the database using objects and methods.
PostgreSQL Schema
Contains tables, views, sequences, indices
What is a Transaction in a Database?
A transaction in a database is a sequence of operations (like inserting, updating, or deleting records) that are performed as a single unit of work. ACID
What is pgAdmin?
π· pgAdmin is a GUI (Graphical User Interface) tool for managing PostgreSQL databases. It allows users to interact with PostgreSQL without writing SQL queries manually.
How to Create a Backup of a PostgreSQL Database?
In PostgreSQL, you can create a backup using pg_dump (command-line) or pgAdmin (GUI tool).
π· pg_dump is a utility that helps export a PostgreSQL database into a file.
How to Enhance Querying Performance
- Indexing
- Partitioning tables
- Reducing processing overhead by reducing the number of unrequired columns in SELECT statements
How to Handle Error
Using callback functions
What is a Trigger in PostgreSQL?
A trigger in PostgreSQL is a special function that automatically executes when a specified event occurs on a table. It is used to enforce business rules, maintain data integrity, and automate actions in the database.
β
Automatic execution β Runs without manual intervention.
β
Event-driven β Executes on INSERT, UPDATE, or DELETE operations.
β
Can modify or prevent actions β You can alter data, log changes, or even reject operations.
What is MVCC (Multi-Version Concurrency Control)?
MVCC is a database management technique used to handle concurrent data access without locking the data. It helps ensure that multiple transactions can occur at the same time without conflicting with each other. In simple terms, MVCC allows for read consistency while multiple transactions are being executed simultaneously.
π How MVCC Works:
In traditional databases, when one transaction is updating data, other transactions are blocked from reading or modifying the same data until the first transaction is finished. This can lead to performance bottlenecks.
MVCC solves this by keeping multiple versions of a data record. When a transaction reads data, it sees a snapshot of the data at the time the transaction started.
AWS SQS
AWS SQS is a fully managed message queuing service that allows asynchronous communication between distributed services.
AWS SQS Components & Workflow:
Producer (Message Sender)
- The service/application that sends messages to the SQS queue.
- Example: Flipkart's order service pushes an "Order Placed" event into SQS.
Consumer (Message Receiver & Processor)
- Services that fetch messages from the queue and process them.
- Example: Payment Service picks an order message and starts payment processing.
Workflow:
- When a consumer picks a message, it becomes invisible to others for a certain time.
- If processing is successful, the message is deleted from the queue.
- If the consumer fails, the message becomes available again for reprocessing.
- If a message fails multiple times, it is moved to DLQ for debugging.
- SQS stores multiple copies across different AZs for fault tolerance.
Celery
Celery is a distributed task queue framework that enables you to run background tasks asynchronously.
Monitoring
What is Loki?
Loki is a log aggregation system developed by Grafana Labs, designed to collect, store, and query logs efficiently without full-text indexing, making it lightweight and cost-effective.
Log Collection β It collects logs from sources like Promtail, Fluentd, or Docker.
Indexing Strategy β Unlike Elasticsearch, Loki only indexes metadata (labels), not full logs, reducing storage cost.
Storage β It stores logs in object storage (S3, GCS, etc.), making it highly scalable.
Querying β It uses LogQL (Loki Query Language) to filter and search logs in Grafana.
Grafana vs Loki
Grafana and Loki are both developed by Grafana Labs, but they serve different purposes.
Feature Grafana π¨ Grafana Loki π
Purpose Visualization & monitoring Log aggregation & searching
Data Type Metrics & dashboards Logs
Indexing Uses time-series databases Indexes only metadata (labels)
Works With Prometheus, InfluxDB, MySQL, etc. Promtail, Fluentd, Docker logs
Query Language PromQL, SQL, etc. LogQL
What is OpenTelemetry Monitoring?
OpenTelemetry is an open-source observability framework that helps collect, process, and export telemetry data (logs, metrics, and traces) for monitoring distributed systems
Top comments (0)