Skip to content

C++

Type Safety in C++

C++ is a strongly typed language. It means that all variables' data type should be specified at the declaration, and it does not change throughout the program. Moreover, we can only assign the values that are of the same type as that of the variable.

Note that <<endlflushes the output buffer, but \n​ not

Function in C++

1. Pass by Value

In pass by value method, a variable's value is copied and then passed to the function. As the result, any changes to the parameter inside the function will not affect the variable's original value in the caller.

2. Pass by Reference

In pass-by-reference method, instead of passing the value of the argument, we pass the reference of an argument to the function. This allows the function to change the value of the original argument.

3. Pass by Pointer

The pass-by-pointer is very similar to the pass-by-reference method. The only difference is that we pass the raw address of the argument as the parameter to the function instead of reference.

#include <iostream>
#include <cassert>

static int foo(int a);
static int bar(int * a);
static int fubar(int& a);

int main() {
    int my_var = 9;
    printf("foo(my_var): %d\n", foo(my_var));
    printf("bar(&my_var): %d\n", bar(&my_var));
    printf("fubar(my_var): %d\n", fubar(my_var));
    printf("my_var: %d\n", my_var);
    return 0;
}

static int foo(int a) {
    return a * 10;
}

static int bar(int * a) {
    assert(a != nullptr);
    return *a * 100;
}

static int fubar(int& a) {
    a = 1;
    return a * 1000;
}

Default Argument

#include <iostream>
using namespace std;

// Function with default height 'h' argument
double calcArea(double l, double h = 10.0) {
//Note that default parameter must start from right
    return l * h;
}

int main() {
    cout << "Area 1:  "<< calcArea(5)
    << endl;

    cout << "Area 2: "<< calcArea(5, 9);
    return 0;
}

Array

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {2, 4, 8, 12, 16};

    // Traversing and printing arr
    for (int i = 0; i < 5; i++)
        cout << arr[i] << " ";

    return 0;
}

Pointer

#include <bits/stdc++.h>
using namespace std;

int main() {
    int var = 10;

    // Store the address of 
    // var variable
    int* ptr = &var;

    // Access value using (*)
    // operator
    cout << *ptr;
    return 0;
}

Structures

C++ Structures are used to create user defined data types which are used to store group of items of different data types

#include <iostream>
using namespace std;

// Class like structure
struct Point {
private:
    int x, y;
public:

    // Constructors
    Point(int a, int b) {
        x = a;
        y = b;
    }

    // Member function
    void show() {
        cout << x << " " << y << endl;
    }

    // Destructor
    ~Point() {
        cout << "Destroyed Point Variable" << endl;
    }
};

int main() {

    // Creating Point variables using constructors
    Point s1;
    Point s2(99, 1001);

    s1.show();
    s2.show();
    return 0;
}

typedef

In C++, typedef is used to create an alias for an existing variable. Similarly, with structures, typedef creates an alias for the original name of the structure.

#include <iostream>
using namespace std;

typedef struct GeeksforGeeks {
    int x, y;

// Alias is specified here
} GfG;

int main() {

    // Using alias
    GfG s = { 0, 1 };
    cout << s.x << " " << s.y << endl;
    return 0;
}

Enumeration

Easy example, By default, the first name in an enum is assigned the integer value 0, and the subsequent ones are incremented by 1.

#include <iostream>
using namespace std;

// Defining enum
enum direction {
    EAST, NORTH, WEST, SOUTH
};

int main() {

    // Creating enum variable
    direction dir = NORTH;
    cout << dir;
    return 0;
}

Another example

#include <iostream>
using namespace std;

// Define the enum class
enum class Day { Sunday = 1, Monday, Tuesday,
                Wednesday, Thursday, Friday, 
                Saturday };

int main() {

    // initializing
    Day today = Day::Thursday;

    // Print the enum
    cout << static_cast<int>(today);
    return 0;
}

New and delete operator

#include <iostream>
using namespace std;

int main() {
    int *ptr = NULL;

    // Request memory for integer variable
    // using new operator
    ptr = new int(10);
    if (!ptr) {
        cout << "allocation of memory failed";
        exit(0);
    }

    cout << "Value of *p: " << *ptr << endl;

    // Free the value once it is used
    delete ptr;

    // Allocate an array
    ptr = new int[3];
    ptr[2] = 11;
    ptr[1] = 22;
    ptr[0] = 33;
    cout << "Array: ";
    for (int i = 0; i < 3; i++)
        cout << ptr[i] << " ";

    // Deallocate when done
    delete[] ptr;

    return 0;
}

Polymorphism

A. Function Overloading

#include <bits/stdc++.h>
using namespace std;

class Geeks {
public:

    // Function to add two integers
    void add(int a, int b) {
        cout << "Integer Sum = " << a + b
        << endl;
    }

    // Function to add two floating point values
    void add(double a, double b) {
        cout << "Float Sum = " << a + b
        << endl ;
    }
};

int main() {
    Geeks gfg;

    // add() called with int values
    gfg.add(10, 2);

    // add() called with double value
    gfg.add(5.3, 6.2);

    return 0;
}

B. Operator Overloading

#include <iostream>
using namespace std;

class Complex {
public:
    int real, imag;

    Complex(int r, int i) :
    real(r), imag(i) {}
//This is the member initializer list. 
//initializing member variables before the constructor body
//real and imag are member variables

    // Overloading the '+' operator
    Complex operator+(const Complex& obj) {
        return Complex(real + obj.real,
        imag + obj.imag);
    }
};

int main() {
    Complex c1(10, 5), c2(2, 4);

    // Adding c1 and c2 using + operator
    Complex c3 = c1 + c2;  
    cout << c3.real << " + i" << c3.imag;
    return 0;
}

Inheritance

#include <bits/stdc++.h>
using namespace std;

// Base class that is to be inherited
class Parent {
public:
    int id_p;
    Parent(int x = 22) : id_p(x) {}
    void printID_p() {
        cout << "Base ID: " << id_p << endl;
    }
};

// Derived publicly inheriting from Base
// Class
class Child : public Parent {
public:
    int id_c;
    Child(int x = 22) : id_c(x) {}
    void printID_c() {
        cout << "Child ID: " << id_c << endl;
    }
};

int main() {
    Child obj1;

    // An object of class child has all data members
    // and member functions of class parent
    // so we try accessing the parents method and data from
    // the child class object.
    obj1.id_p = 7;
    obj1.printID_p();

    // finally accessing the child class methods and data
    // too
    obj1.id_c = 91;
    obj1.printID_c();
    return 0;
}
---
7
91

Abstraction

#include<iostream>
using namespace std;

class Vehicle
{
  private:
          void piston()
        {
            cout<<"4 piston\n";
        }

        void manWhoMade()
        {
            cout<<"Markus Librette\n";
        }
    public:
        void company()
        {
            cout<<"GFG\n";
        }
        void model()
        {
            cout<<"SIMPLE\n";
        }
        void color()
        {
            cout<<"Red/GREEN/Silver\n";
        }
        void cost()
        {
            cout<<"Rs. 60000 to 900000\n";
        }
        void oil()
        {
            cout<<"PETROL\n";
        }
};
int main()
{

    Vehicle obj;
    obj.company();
    obj.model();
    obj.color();
    obj.cost();
    obj.oil();
}
---
GFG
SIMPLE
Red/GREEN/Silver
Rs. 60000 to 900000
PETRO