C++

 

C++



Basics

Boilerplate

#include <iostream>using namespace std; int main() {    cout << "Welcome To CodeWithHarry";    return 0;}

Input/Output

  • Output (cout <<) – Prints to console
  • Input (cin >>) – Takes user input
string name;cout << "Enter name: ";cin >> name;cout << "Hello, " << name;

Data Types

C++ supports several data types, divided into categories:

TypeExampleSize (Typical)Description
charchar c='A';1 byteStores single character
intint x=10;4 bytesInteger numbers
shortshort s=100;2 bytesSmall integer
longlong l=100000;4-8 bytesLarge integer
floatfloat f=10.5;4 bytesSingle-precision decimal
doubledouble d=10.55;8 bytesDouble-precision decimal
boolbool flag=true;1 byteTrue/False values
voidRepresents no value

Escape Sequences

SequenceMeaning
\aAlert (beep)
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\\Backslash
\'Single quote
\"Double quote
\?Question mark
\0Null terminator
\nnnOctal value
\xhhHexadecimal value

Comments

// Single-line comment /* Multi-line   comment */

Strings

#include <string> string s1 = "Hello";string s2 = "World"; // Concatenationstring s3 = s1 + " " + s2; // Appends1.append(s2); // Lengthcout << s3.length(); // Access/modifys3[0] = 'h';

Math Functions (<cmath>)

FunctionExampleResult
max(a,b)max(5,10)10
min(a,b)min(5,10)5
sqrt(x)sqrt(144)12
ceil(x)ceil(1.9)2
floor(x)floor(1.9)1
pow(x,y)pow(2,3)8
abs(x)abs(-5)5
round(x)round(2.6)3

Decision Making

if (x > 0) { ... }else if (x == 0) { ... }else { ... } // Ternaryint result = (x > 0) ? 1 : -1; // Switchswitch (choice) {    case 1: cout << "One"; break;    case 2: cout << "Two"; break;    default: cout << "Other";}

Loops

// While loopwhile (i < 5) { i++; } // Do-while loopdo { i++; } while (i < 5); // For loopfor (int i=0; i<5; i++) { ... } // Break/Continuebreak;     // exits loopcontinue;  // skips current iteration

References

int a = 10;int &ref = a;ref = 20; // a becomes 20

Pointers

int x = 10;int *ptr = &x;   // Pointer to xcout << *ptr;    // Dereference (prints 10)
  • nullptr is used for null pointers in C++11+
  • Use -> operator to access members of objects through pointers

Functions & Recursion

int add(int a, int b) {    return a + b;} // Recursionint factorial(int n) {    if (n <= 1) return 1;    return n * factorial(n-1);}

Object-Oriented Programming

Class & Object

class Car {public:    string brand;    int year;    void drive() { cout << "Driving"; }}; Car c1;c1.brand = "BMW";c1.drive();

Constructor

class Car {public:    Car(string b, int y) {        brand = b;        year = y;    }    string brand;    int year;};Car c("Audi", 2023);

Inheritance

class Vehicle {public:    void honk() { cout << "Beep!"; }}; class Car : public Vehicle { }; Car obj;obj.honk(); // Inherited method

Polymorphism (Virtual Functions)

class Animal { public: virtual void sound() { cout<<"Some sound"; }};class Dog : public Animal { public: void sound() override { cout<<"Bark"; }};Animal* a = new Dog();a->sound(); // Bark

File Handling

#include <fstream>ofstream myFile("test.txt");  // writemyFile << "Hello";myFile.close(); ifstream readFile("test.txt");  // readstring line;while (getline(readFile, line)) { cout << line; }readFile.close();
  • Modes: ios::inios::outios::appios::binaryios::ateios::trunc

Exception Handling

try {    throw runtime_error("Error occurred");}catch (exception &e) {    cout << "Caught: " << e.what();}

Additional Key Concepts

  • Namespaces: Avoids name conflicts
namespace A { int x = 10; }cout << A::x;
  • Templates: Generic programming
template <typename T>T add(T a, T b) { return a + b; }
  • STL (Standard Template Library): vectormapsetstack, etc.
Post a Comment (0)
Previous Post Next Post