Code with harry

 


>> jaise hum koi cheez google p search krte hain and google hume result deta hai to vo high level hota hai and jb hum google p andr dekhenge k vo result de kse rha hai kse kaam krra hai to vo low level khte hain.

similarly locgical things that we can do with computer is called high level language and jb programming language see hum hardware and memory ko control kr paae to use lowlevel language khte hain.



<< this is the insertion operator used in cout.
>> this is the extraction operator used in cin.




Agr ek c naam ka global variable hai and ek c naam ka local variable hai to agr function k andr print krenge c ko to local print hoga lekin agr hume global c ki value print krni hai to hum scope resolution operator(::) use kr skte hain.

Agr hum kisi function mein 34.4 pass krenge to vo use by default double smjhega isliye agr hume float bhjna hai to 34.4f or 34.4F krenge and agr long double bhejna hai to 34.4l or 34.4L.


>>Typecasting


>>Constants in C++



>>Manipulators






Pointers

Arrays


#include<iostream>
using namespace std;

int main(){
    // Array Example
    int marks[] = {23, 45, 56, 89};

    int mathMarks[4];
    mathMarks[0] = 2278;
    mathMarks[1] = 738;
    mathMarks[2] = 378;
    mathMarks[3] = 578;

    cout<<"These are math marks"<<endl;
    cout<<mathMarks[0]<<endl;
    cout<<mathMarks[1]<<endl;
    cout<<mathMarks[2]<<endl;
    cout<<mathMarks[3]<<endl;

    // You can change the value of an array
    marks[2] = 455;
    cout<<"These are marks"<<endl;
    // cout<<marks[0]<<endl;
    // cout<<marks[1]<<endl;
    // cout<<marks[2]<<endl;
    // cout<<marks[3]<<endl;

    for (int i = 0; i < 4; i++)
    {
        cout<<"The value of marks "<<i<<" is "<<marks[i]<<endl;
    }

    // Quick quiz: do the same using while and do-while loops?

    // Pointers and arrays
    int* p = marks;
    cout<<*(p++)<<endl;
    cout<<*(++p)<<endl;
    // cout<<"The value of *p is "<<*p<<endl;
    // cout<<"The value of *(p+1) is "<<*(p+1)<<endl;
    // cout<<"The value of *(p+2) is "<<*(p+2)<<endl;
    // cout<<"The value of *(p+3) is "<<*(p+3)<<endl; 
    
    return 0;
}


>>Structures, Union and enum

#include<iostream>
using namespace std;

typedef struct employee
{
    /* data */
    int eId; //4
    char favChar; //1
    float salary; //4
} ep;

union money
{
    /* data */
    int rice; //4
    char car; //1
    float pounds; //4
};


int main(){
    enum Meal{ breakfast, lunch, dinner};
    Meal m1 = lunch;
    cout<<(m1==2);
    // cout<<breakfast;
    // cout<<lunch;
    // cout<<dinner; 
    // union money m1;
    // m1.rice = 34;
    // m1.car = 'c';
    // cout<<m1.car;

    // ep harry;
    // struct employee shubham;
    // struct employee rohanDas;
    // harry.eId = 1;
    // harry.favChar = 'c';
    // harry.salary = 120000000;
    // cout<<"The value is "<<harry.eId<<endl; 
    // cout<<"The value is "<<harry.favChar<<endl; 
    // cout<<"The value is "<<harry.salary<<endl; 
    return 0;
}


>>Functions and their prototypes

#include<iostream>
using namespace std;

// Function prototype
// type function-name (arguments);
// int sum(int a, int b); //--> Acceptable
// int sum(int a, b); //--> Not Acceptable 
int sum(int, int); //--> Acceptable 
// void g(void); //--> Acceptable 
void g(); //--> Acceptable 

int main(){
    int num1, num2;
    cout<<"Enter first number"<<endl;
    cin>>num1;
    cout<<"Enter second number"<<endl;
    cin>>num2;
    // num1 and num2 are actual parameters
    cout<<"The sum is "<<sum(num1, num2);
    g();
    return 0;
}

int sum(int a, int b){
    // Formal Parameters a and b will be taking values from actual parameters num1 and num2.
    int c = a+b;
    return c;
}

void g(){
    cout<<"\nHello, Good Morning";
}



>>Call by value and Call by Reference(using & and reference variable

#include<iostream>
using namespace std;

int sum(int a, int b){
    int c = a + b;
    return c;
}

// This will not swap a and b
void swap(int a, int b){ //temp a b
    int temp = a;        //4   4  5   
    a = b;               //4   5  5
    b = temp;            //4   5  4 
}

// Call by reference using pointers
void swapPointer(int* a, int* b){ //temp a b
    int temp = *a;          //4   4  5   
    *a = *b;               //4   5  5
    *b = temp;            //4   5  4 
}

// Call by reference using C++ reference Variables
// int & 
void swapReferenceVar(int &a, int &b){ //temp a b
    int temp = a;          //4   4  5   
    a = b;               //4   5  5
    b = temp;            //4   5  4 
    // return a;
}

int main(){
    int x =4, y=5;
    // cout<<"The sum of 4 and 5 is "<<sum(a, b);
    cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl;
    // swap(x, y); // This will not swap a and b
    // swapPointer(&x, &y); //This will swap a and b using pointer reference
    swapReferenceVar(x, y); //This will swap a and b using reference variables
    // swapReferenceVar(x, y) = 766; //This will swap a and b using reference variables
    cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl; 
    return 0;
}


>>inline functions , default variables and constant variables.

#include<iostream>
using namespace std;

inline int product(int a, int b){
    // Not recommended to use below lines with inline functions
    // static int c=0; // This executes only once
    // c = c + 1; // Next time this function is run, the value of c will be retained
    return a*b;
}
// below factor variable is default variable and all default variables arguments are written at right.
float moneyReceived(int currentMoney, float factor=1.04){
    return currentMoney * factor;
}

// int strlen(const char *p){

// }
int main(){
    int a, b;
    // cout<<"Enter the value of a and b"<<endl;
    // cin>>a>>b;
    // cout<<"The product of a and b is "<<product(a,b)<<endl;
    int money = 100000;
    cout<<"If you have "<<money<<" Rs in your bank account, you will recive "<<moneyReceived(money)<< "Rs after 1 year"<<endl;
    cout<<"For VIP: If you have "<<money<<" Rs in your bank account, you will recive "<<moneyReceived(money, 1.1)<< " Rs after 1 year";
    return 0;
}


----------------------------------------------------------------------------

Function Overloading (same name k functions bana kr diff kaam kara skte hain kuki jb function call hoga to vo sbse phle arguments dekhega kiitni hai .)


       ----------------------------------------------------------------------------


#include<iostream>
using namespace std;

int sum(float a, int b){
    cout<<"Using function with 2 arguments"<<endl;
    return a+b;
}

int sum(int a, int b, int c){
    cout<<"Using function with 3 arguments"<<endl;
    return a+b+c;
}

// Calculate the volume of a cylinder
int volume(double r, int h){
    return(3.14 * r *r *h);
}

// Calculate the volume of a cube
int volume(int a){
    return (a * a * a);
}

// Rectangular box
int volume (int l, int b, int h){
    return (l*b*h);
}

int main(){
    cout<<"The sum of 3 and 6 is "<<sum(3,6)<<endl;
    cout<<"The sum of 3, 7 and 6 is "<<sum(3, 7, 6)<<endl;
    cout<<"The volume of cuboid of 3, 7 and 6 is "<<volume(3, 7, 6)<<endl;
    cout<<"The volume of cylinder of radius 3 and height 6 is "<<volume(3, 6)<<endl;
    cout<<"The volume of cube of side 3 is "<<volume(3)<<endl;
    return 0;
}




Below code mein jo private hai usko class k andr k functions hi access kr skte hain vo cheez main yaa aur kisi function jo k class k bahar hai usse access ni ho skti but public ko kahin se bhi access kr skte hain.


-------------------------------------------------------------


#include<iostream>
using namespace std;

class Employee
{
    private:
        int a, b, c;
    public:
        int d, e;
        void setData(int a1, int b1, int c1); // Declaration
        void getData(){
            cout<<"The value of a is "<<a<<endl;
            cout<<"The value of b is "<<b<<endl;
            cout<<"The value of c is "<<c<<endl;
            cout<<"The value of d is "<<d<<endl;
            cout<<"The value of e is "<<e<<endl;
        }
};

void Employee :: setData(int a1, int b1, int c1){
    a = a1;
    b = b1;
    c = c1;
}

int main(){
    Employee harry;
    // harry.a = 134; -->This will throw error as a is private
    harry.d = 34;
    harry.e = 89;
    harry.setData(1,2,4);
    harry.getData();
    return 0;
}


-------------------------------------------------------



// OOPs - Classes and objects

// C++ --> initially called --> C with classes by stroustroup
// class --> extension of structures (in C)
// structures had limitations
//      - members are public
//      - No methods
// classes --> structures + more
// classes --> can have methods and properties
// classes --> can make few members as private & few as public
// structures in C++ are typedefed
// you can declare objects along with the class declarion like this:
/* class Employee{
            // Class definition
        } harry, rohan, lovish; */
// harry.salary = 8 makes no sense if salary is private

// Nesting of member functions

#include <iostream>
#include <string>
using namespace std;

class binary
{
private:
    string s;
    void chk_bin(void);

public:
    void read(void);
    void ones_compliment(void);
    void display(void);
};

void binary::read(void)
{
    cout << "Enter a binary number" << endl;
    cin >> s;
}

void binary::chk_bin(void)
{
    for (int i = 0; i < s.length(); i++)
    {
        if (s.at(i) != '0' && s.at(i) != '1')
        {
            cout << "Incorrect binary format" << endl;
            exit(0);
        }
    }
}

void binary::ones_compliment(void)
{
    chk_bin();
    for (int i = 0; i < s.length(); i++)
    {
        if (s.at(i) == '0')
        {
            s.at(i) = '1';
        }
       else
        {
            s.at(i) = '0';
        }
    }
}

void binary::display(void)
{
    cout<<"Displaying your binary number"<<endl;
    for (int i = 0; i < s.length(); i++)
    {
        cout << s.at(i);
    }
    cout<<endl;
}

int main()
{
    binary b;
    b.read();
    // b.chk_bin();
    b.display();
    b.ones_compliment();
    b.display();

    return 0;
}


>> Memory Allocation in Class.

CLass k andr k function to class k saare object k liye same honge isliye class k data member and member funtion ko liye memory ek baar allocate hoti hai and vo sb object k liye common hote hain but object k data member mein jo value store hogi uski memory har object k liye alg hoti hai.


>>Using Arrays in Classes

#include <iostream>
using namespace std;

class Shop
{
    int itemId[100];
    int itemPrice[100];
    int counter;

public:
    void initCounter(void) { counter = 0; }
    void setPrice(void);
    void displayPrice(void);
};

void Shop ::setPrice(void)
{
    cout << "Enter Id of your item no " << counter + 1 << endl;
    cin >> itemId[counter];
    cout << "Enter Price of your item" << endl;
    cin >> itemPrice[counter];
    counter++;
}

void Shop ::displayPrice(void)
{
    for (int i = 0; i < counter; i++)
    {
        cout << "The Price of item with Id " << itemId[i] << " is " << itemPrice[i] << endl;
    }
}

int main()
{
    Shop dukaan;
    dukaan.initCounter();
    dukaan.setPrice();
    dukaan.setPrice();
    dukaan.setPrice();
    dukaan.displayPrice();
    return 0;
}


---------------------------------------------------------------



>> Static data member and methods(ek esa variable and method jo saare objects k liye same rahe change na ho)

static variable hmesha class k bahara initialize hoga and uski memory ek bar hi allocate hogi class ki memory k saath. 
static varible by default 0 hoga.

static member funtion isliye banate hain k vo saare static data members and other static funtions ko access kr sake 
ye function bss static data members and member funtion ko hi access kr skte hain aur kuch ni .
and ye funtion class k name and scope resolution operator (::) se hi access hota hai.


--------------------------------------------------------------------


#include <iostream>
using namespace std;

class Employee
{
    int id;
    static int count;

public:
    void setData(void)
    {
        cout << "Enter the id" << endl;
        cin >> id;
        count++;
    }
    void getData(void)
    {
        cout << "The id of this employee is " << id << " and this is employee number " << count << endl;
    }

    static void getCount(void){
        // cout<<id; // throws an error
        cout<<"The value of count is "<<count<<endl;
    }
};

// Count is the static data member of class Employee
int Employee::count; // Default value is 0

int main()
{
    Employee harry, rohan, lovish;
    // harry.id = 1;
    // harry.count=1; // cannot do this as id and count are private

    harry.setData();
    harry.getData();
    Employee::getCount();

    rohan.setData();
    rohan.getData();
    Employee::getCount();

    lovish.setData();
    lovish.getData();
    Employee::getCount();

    return 0;
}



>>Array of Objects 

#include <iostream>
using namespace std;

class Employee
{
    int id;
    int salary;

public:
    void setId(void)
    {
        salary = 122;
        cout << "Enter the id of employee" << endl;
        cin >> id;
    }

    void getId(void)
    {
        cout << "The id of this employee is " << id << endl;
    }
};

int main()
{
    // Employee harry, rohan, lovish, shruti;
    // harry.setId();
    // harry.getId();
    Employee fb[4];
    for (int i = 0; i < 4; i++)
    {
        fb[i].setId();
        fb[i].getId();
    }

    return 0;
}


>>Passing Objects as Function Argument.

#include<iostream>
using namespace std;

class complex{
    int a;
    int b;

    public: 
        void setData(int v1, int v2){
            a = v1;
            b = v2;
        }

        void setDataBySum(complex o1, complex o2){
            a = o1.a + o2.a;
            b = o1.b + o2.b;
        }

        void printNumber(){
            cout<<"Your complex number is "<<a<<" + "<<b<<"i"<<endl;
        }
};

int main(){
    complex c1, c2, c3;
    c1.setData(1, 2);
    c1.printNumber();

    c2.setData(3, 4);
    c2.printNumber();

    c3.setDataBySum(c1, c2);
    c3.printNumber();
    return 0;
}


>> Friend Funtions 

#include<iostream>
using namespace std;

// 1 + 4i
// 5 + 8i
// -------
// 6 + 12i 
class Complex{
    int a, b;
    friend Complex sumComplex(Complex o1, Complex o2);
    public:
        void setNumber(int n1, int n2){
            a = n1;
            b = n2;
        }

        // Below line means that non member - sumComplex funtion is allowed to do anything with my private parts (members)
        void printNumber(){
            cout<<"Your number is "<<a<<" + "<<b<<"i"<<endl;
        }
};

Complex sumComplex(Complex o1, Complex o2){
//cout << a;  it throws error because this funtion don't know what is a as it is not a member of class.
    Complex o3;
    o3.setNumber((o1.a + o2.a), (o1.b+o2.b));
    return o3;
}

int main(){
    Complex c1, c2, sum;
    c1.setNumber(1, 4);
    c1.printNumber();

    c2.setNumber(5, 8);
    c2.printNumber();

    sum = sumComplex(c1, c2);
    sum.printNumber();

    return 0;
}

/* Properties of friend functions
1. Not in the scope of class
2. since it is not in the scope of the class, it cannot be called from the object of that class. c1.sumComplex() == Invalid
3. Can be invoked without the help of any object
4. Usually contains the objects as arguments
5. Can be declared inside public or private section of the class
6. It cannot access the members directly by their names and need object_name.member_name to access any member.
7. Friend funtion ki declaration inside class hum public mein yaa private mein kahin bhi de skte hain koi frk ni pdta.
*/


------------------------------------------------------------------------


#include <iostream>
using namespace std;

// Forward declaration
class Complex;

class Calculator
{
public:
    int add(int a, int b)
    {
        return (a + b);
    }

    int sumRealComplex(Complex, Complex);
    int sumCompComplex(Complex, Complex);
};

class Complex
{
    int a, b;
    // Individually declaring functions as friends
    // friend int Calculator ::sumRealComplex(Complex, Complex);
    // friend int Calculator ::sumCompComplex(Complex, Complex);

    // Aliter: Declaring the entire calculator class as friend
    friend class Calculator;

public:
    void setNumber(int n1, int n2)
    {
        a = n1;
        b = n2;
    }

    void printNumber()
    {
        cout << "Your number is " << a << " + " << b << "i" << endl;
    }
};

int Calculator ::sumRealComplex(Complex o1, Complex o2)
{
    return (o1.a + o2.a);
}

int Calculator ::sumCompComplex(Complex o1, Complex o2)
{
    return (o1.b + o2.b);
}

int main()
{
    Complex o1, o2;
    o1.setNumber(1, 4);
    o2.setNumber(5, 7);
    Calculator calc;
    int res = calc.sumRealComplex(o1, o2);
    cout << "The sum of real part of o1 and o2 is " << res << endl;
    int resc = calc.sumCompComplex(o1, o2);
    cout << "The sum of complex part of o1 and o2 is " << resc << endl;
    return 0;
}


-----------------------------------------------------------



#include<iostream>
using namespace std;

class Y;

class X{
    int data;
    public:
        void setValue(int value){
            data = value;
        }
    friend void add(X, Y);    
};

class Y{
    int num;
    public:
        void setValue(int value){
            num = value;
        }
    friend void add(X, Y);    

};

void add(X o1, Y o2){
    cout<<"Summing data of X and Y objects gives me "<< o1.data + o2.num;
}

int main(){
    X a1;
    a1.setValue(3);

    Y b1;
    b1.setValue(15);

    add(a1, b1);
    return 0;
}


---------------------------------------------------------


#include<iostream>
using namespace std;
class c2;

class c1{
    int val1;
    friend void exchange(c1 & , c2 &);
    public:
        void indata(int a){
            val1 = a;
        }

        void display(void){
            cout<< val1 <<endl;
        }
};

class c2{
    int val2;
    friend void exchange(c1 &, c2 &);
    public:
        void indata(int a){
            val2 = a;
        }

        void display(void){
            cout<< val2 <<endl;
        }
};
/*
Trick to swap 2 numbers a and b:
temp = a;
a = b;
b = temp;

*/
void exchange(c1 &x, c2 &y){
    int tmp = x.val1;
    x.val1 = y.val2;
    y.val2 = tmp;
}

int main(){
    c1 oc1;
    c2 oc2;

    oc1.indata(34);
    oc2.indata(67);
    exchange(oc1, oc2);

    cout<<"The value of c1 after exchanging becomes: ";
    oc1.display();
    cout<<"The value of c2 after exchanging becomes: ";
    oc2.display();
    
    return 0;
}



>>Constructors

#include <iostream>
using namespace std;

class Complex
{
    int a, b;

public:
    // Creating a Constructor
    // Constructor is a special member function with the same name as of the class.
    //It is used to initialize the objects of its class
    //It is automatically invoked whenever an object is created

    Complex(void); // Constructor declaration

    void printNumber()
    {
        cout << "Your number is " << a << " + " << b << "i" << endl;
    }
};

Complex ::Complex(void) // ----> This is a default constructor as it takes no parameters
{
    a = 0;
    b = 0;
    // cout<<"Hello world";
}

int main()
{
    Complex c1, c2, c3;
    c1.printNumber();
    c2.printNumber();
    c3.printNumber();

    return 0;
}


/*  Characteristics of Constructors

1. It should be declared in the public section of the class 
2. They are automatically invoked whenever the object is created 
3. They cannot return values and do not have return types
4. It can have default arguments 
5. We cannot refer to their address
*/


>>Paramerterized and Default Constructors.

#include<iostream>
using namespace std;


class Complex
{
    int a, b;

public:
    Complex(int, int); // Constructor declaration

    void printNumber()
    {
        cout << "Your number is " << a << " + " << b << "i" << endl;
    }
};

Complex ::Complex(int x, int y) // ----> This is a parameterized constructor as it takes 2 parameters
{
    a = x;
    b = y;
    // cout<<"Hello world";
}

int main(){
    // Implicit call
    Complex a(4, 6);
    a.printNumber();

    // Explicit call
    Complex b = Complex(5, 7);
    b.printNumber();

    return 0;
}


-----------------------------------------------------------------------



#include <iostream>
#include<math.h>
using namespace std;

class point{
    int x, y;
    public:
        point(int a, int b){
            x = a;  y = b;
        }

        friend float distance(point, point);
};

float distance(point p1, point p2){
    float p, q, r;
    p = (p1.x - p2.x)*(p1.x - p2.x);
    q = (p1.y - p2.y)*(p1.y - p2.y);
    r = sqrt(p+q);
    return r;
}


int main(){
   point p1(1, 5);
   point p2(1, 1);

   float d;

   d = distance(p1, p2);
   cout << "Distance between point p1 and p2 is : " << d;

   return 0;
}


>>Constructor Overloading

#include <iostream>
using namespace std;

class Complex
{
    int a, b;

public:
    Complex(){
        a = 0;
        b =0;
    }

    Complex(int x, int y)
    {
        a = x;
        b = y;
    }

    Complex(int x){
        a = x;
        b = 0;
    }

  

    void printNumber()
    {
        cout << "Your number is " << a << " + " << b << "i" << endl;
    }
};
int main()
{
    Complex c1(4, 6);
    c1.printNumber();

    Complex c2(5);
    c2.printNumber();

    Complex c3;
    c3.printNumber();
    return 0;
}



>>Constructors with default arguments

#include<iostream>
using namespace std;

class Simple{
    int data1;
    int data2;
    int data3;

    public:
//agr hum koi b aur c k liye koi value pass ni krte argument k roop mein to vo b=9 and c = 8 ko hi apni 
// value bana lega in short these values are default values of b and c.
        Simple(int a, int b=9, int c=8){
            data1 = a;
            data2 = b;
            data3 = c;
        }

        void printData();

};

void Simple :: printData(){
    cout<<"The value of data1, data2 and data3 is "<<data1<<", "<< data2<<" and "<< data3<<endl;
}

int main(){
    Simple s(12, 13);
    s.printData();
    return 0;
}


>>Dynamic initialization of objects

#include<iostream>
using namespace std;


class BankDeposit{
    int principal;
    int years;
    float interestRate;
    float returnValue;

    public:
        BankDeposit(){}
        BankDeposit(int p, int y, float r); // r can be a value like 0.04
        BankDeposit(int p, int y, int r); // r can be a value like 14
        void show();
};

BankDeposit :: BankDeposit(int p, int y, float r)
{
    principal = p;
    years = y;
    interestRate = r;
    returnValue = principal;
    for (int i = 0; i < y; i++)
    {
        returnValue = returnValue * (1+interestRate);
    }
}

BankDeposit :: BankDeposit(int p, int y, int r)
{
    principal = p;
    years = y;
    interestRate = float(r)/100;
    returnValue = principal;
    for (int i = 0; i < y; i++)
    {
        returnValue = returnValue * (1+interestRate);
    }
}

void BankDeposit :: show(){
    cout<<endl<<"Principal amount was "<<principal
        << ". Return value after "<<years
        << " years is "<<returnValue<<endl;
}

int main(){
    BankDeposit bd1, bd2, bd3;
    int p, y;
    float r;
    int R;
    
    
    cout<<"Enter the value of p y and r"<<endl;
    cin>>p>>y>>r;
    bd1 = BankDeposit(p, y, r);
    bd1.show();

    cout<<"Enter the value of p y and R"<<endl;
    cin>>p>>y>>R;
    bd2 = BankDeposit(p, y, R);
    bd2.show();
    return 0;
}



>>Copy Constructor

#include<iostream>
using namespace std;


class Number{
    int a;
    public:
        Number(){
            a = 0;
        }

        Number(int num){
            a = num;
        }
        // When no copy constructor is found, compiler supplies its own copy constructor
        Number(Number &obj){
            cout<<"Copy constructor called!!!"<<endl;
            a = obj.a;
        }

        void display(){
            cout<<"The number for this object is "<< a <<endl;
        }
};
int main(){
    Number x, y, z(45), z2;
    x.display();
    y.display();
    z.display();

    Number z1(z); // Copy constructor invoked
    z1.display();

    z2 = z; // Copy constructor not called
    z2.display();

    Number z3 = z; // Copy constructor invoked
    z3.display();

    // z1 should exactly resemble z  or x or y

    return 0;
}


>>Destructor

#include<iostream>
using namespace std;

// Destructor never takes an argument nor does it return any value 
int count=0;

class num{
    public:
        num(){
            count++;
            cout<<"This is the time when constructor is called for object number"<<count<<endl;
        }

        ~num(){
            cout<<"This is the time when my destructor is called for object number"<<count<<endl;
            count--;
        }
};

int main(){
    cout<<"We are inside our main function"<<endl;
    cout<<"Creating first object n1"<<endl;
    num n1;
    {
        cout<<"Entering this block"<<endl;
        cout<<"Creating two more objects"<<endl;
        num n2, n3;
        cout<<"Exiting this block"<<endl;
    }
    cout<<"Back to main"<<endl;
    return 0;
}



>>Inheritance and its different types



#include <iostream>
using namespace std;

// Base Class
class Employee
{
public:
    int id;
    float salary;
    Employee(int inpId)
    {
        id = inpId;
        salary = 34.0;
    }
    Employee() {}
};

// Derived Class syntax
/*
class {{derived-class-name}} : {{visibility-mode}} {{base-class-name}}
{
    class members/methods/etc...
}
Note:
1. Default visibility mode is private
2. Public Visibility Mode: Public members of the base class becomes Public members of the derived class
3. Private Visibility Mode: Public members of the base class becomes Private members of the derived class
4. Private members are never inherited
5. In base class if we had made any parameterised constructor then it becomes necessary to make 
   default constructor otherwise the derieved class will through
   error because uska constructor call ni ho paaega... kuki derieved class ka constructor call
   hone se phle base class ka constructor call hota hai.
*/

// Creating a Programmer class derived from Employee Base class
class Programmer : public Employee
{
public:
    int languageCode;
    Programmer(int inpId)
    {
        id = inpId;
        languageCode = 9;
    }
    void getData(){
        cout<<id<<endl;
    }
};

int main()
{
    Employee harry(1), rohan(2);
    cout << harry.salary << endl;
    cout << rohan.salary << endl;
    Programmer skillF(10);
    cout << skillF.languageCode<<endl;
    cout << skillF.id<<endl;
    skillF.getData();
    return 0;
}



>>Single Inheritance Deep Dive

#include <iostream>
using namespace std;

class Base
{
    int data1; // private by default and is not inheritable
public:
    int data2;
    void setData();
    int getData1();
    int getData2();
};

void Base :: setData(void)
{
    data1 = 10;
    data2 = 20;
}

int Base::getData1()
{
    return data1;
}

int Base::getData2()
{
    return data2;
}

class Derived : public Base
{ // Class is being derived publically
    int data3;

public:
    void process();
    void display();
};

void Derived ::process()
{
    data3 = data2 * getData1();
}

void Derived ::display()
{
    cout << "Value of data 1 is " << getData1() << endl;
    cout << "Value of data 2 is " << data2 << endl;
    cout << "Value of data 3 is " << data3 << endl;
}

int main()
{
    Derived der;
    der.setData();
    der.process();
    der.display();

    return 0;
}



>>Protected Access Modifier

#include<iostream>
using namespace std;

class Base{
    protected:
        int a; 
    private:
        int b;

};
/*
For a protected member:
                        Public derivation   Private Derivation   Protected Derivation
    1. Private members      Not Inherited   Not Inherited       Not Inherited
    2. Protected members    Protected       Private             Protected
    3. Public members       Public          Private             Protected
*/
class Derived: protected Base{
   
};

int main(){
    Base b;
    Derived d;
    // cout<<d.a; // Will not work since a is protected in both base as well as derived class
    return 0;
}


>>Multilevel Inheritance]

#include <iostream>
using namespace std;

class Student
{
protected:
    int roll_number;

public:
    void set_roll_number(int);
    void get_roll_number(void);
};

void Student ::set_roll_number(int r)
{
    roll_number = r;
}

void Student ::get_roll_number()
{
    cout << "The roll number is " << roll_number << endl;
}

class Exam : public Student
{
protected:
    float maths;
    float physics;

public:
    void set_marks(float, float);
    void get_marks(void);
};

void Exam ::set_marks(float m1, float m2)
{
    maths = m1;
    physics = m2;
}

void Exam ::get_marks()
{
    cout << "The marks obtained in maths are: " << maths << endl;
    cout << "The marks obtained in physics are: " << physics << endl;
}

class Result : public Exam
{
    float percentage;

public:
    void display_results()
    {
        get_roll_number();
        get_marks();
        cout << "Your result is " << (maths + physics) / 2 << "%" << endl;
    }
};

int main()
{
    /*
    Notes: 
        If we are inheriting B from A and C from B:[ A--->B--->C ]
        1. A is the base class for B and B is the base class for C
        2. A-->B-->C is called Inheritance Path
    */

    Result harry;
    harry.set_roll_number(420);
    harry.set_marks(94.0, 90.0);
    harry.display_results();
    return 0;
}



>>Multiple Inhertance

#include <iostream>
using namespace std;

// Syntax for inheriting in multiple inheritance
// class DerivedC: visibility-mode base1, visibility-mode base2
// {
//      Class body of class "DerivedC"
// };

class Base1{
protected:
    int base1int;

public:
    void set_base1int(int a)
    {
        base1int = a;
    }
};

class Base2{
protected:
    int base2int;

public:
    void set_base2int(int a)
    {
        base2int = a;
    }
};

class Base3{
protected:
    int base3int;

public:
    void set_base3int(int a)
    {
        base3int = a;
    }
};

class Derived : public Base1, public Base2, public Base3
{
    public: 
        void show(){
            cout << "The value of Base1 is " << base1int<<endl;
            cout << "The value of Base2 is " << base2int<<endl;
            cout << "The value of Base3 is " << base3int<<endl;
            cout << "The sum of these values is " << base1int + base2int + base3int << endl;
        }
};
/*
The inherited derived class will look something like this:
Data members:
    base1int --> protected
    base2int --> protected

Member functions:
    set_base1int() --> public
    set_base2int() --> public
    set_show() --> public
*/
int main()
{
    Derived harry;
    harry.set_base1int(25);
    harry.set_base2int(5);
    harry.set_base3int(15);
    harry.show();
    
    return 0;
}


>>Ambiguity in Inheritance

#include<iostream>
using namespace std;

class Base1{
    public:
        void greet(){
            cout<<"How are you?"<<endl;
        }
};

class Base2{
    public:
        void greet()
        {
            cout << "Kaise ho?" << endl;
        }
};


class Derived : public Base1, public Base2{
   int a;
   public:
    void greet(){
        Base2 :: greet();
    }
};

class B{
    public:
        void say(){
            cout<<"Hello world"<<endl;
        }
};

class D: public B{
    int a;
    // D's new say() method will override base class's say() method
    public:
        void say()
        {
            cout << "Hello my beautiful people" << endl;
        }
};

int main(){
    // Ambibuity 1
    // Base1 base1obj;
    // Base2 base2obj;
    // base1obj.greet();
    // base2obj.greet();
    // Derived d;
    // d.greet();

    // Ambiguity 2
    B b;
    b.say();

    D d;
    d.say();

    return 0;
}



>>Virtual Base Class

Upr waali pic mein class A se 'a' naam ka object class B and C mein jaaega aur uske baad jb vo class D mein jaaega to Ambigiuity aa jaaegi because 'a' 2 jgah se aara hai and class D ko smj ni aaega kaunsa waala 'a' lena hai .

Isko solve krne k liye virtual base class banate hain 
for example jb hum class B and c ko ingeritre krenge to class A ki visiblity mode k phle virtual laga denge jisse class A virtual class bn jaaegi 
jo k a ko ek hi baar copy kregi baaki saari classes mein jisse Ambiguity solve ho jaaegi.


#include<iostream>
using namespace std;
/*
Inheritance:
student -->test [Done]
student-->sports [Done]
test --> result [Done]
sports --> result [Done]
*/

class Student{
    protected:
        int roll_no;
    public:
        void set_number(int a){
            roll_no = a;
        }
        void print_number(void){
            cout<<"Your roll no is "<< roll_no<<endl;
        }
};

class Test : public virtual Student{
    protected:
        float mathsphysics;
        public:
            void set_marks(float m1float m2){
                maths = m1;
                physics = m2;
            }

            void print_marks(void){
                cout << "You result is here: "<<endl
                     << "Maths: "<< maths<<endl
                     << "Physics: "<< physics<<endl;
            }
};

class Sportsvirtual public Student{
    protected:
        float score;
    public:
        void set_score(float sc){
            score = sc;
        }

        void print_score(void){
            cout<<"Your PT score is "<<score<<endl;
        }

};

class Result : public Testpublic Sports{
    private:
        float total;
    public:
        void display(void){
            total = maths + physics + score;
            print_number();
            print_marks();
            print_score();
            cout<< "Your total score is: "<<total<<endl;
        }
};

int main(){
    Result harry;
    harry.set_number(4200);
    harry.set_marks(78.999.5);
    harry.set_score(9);
    harry.display();
    return 0;
}


#include<iostream>
using namespace std;


class b {
    public:
    int a = 10;
        void sqr(){
            a *= a;
        }
};

class c {
    public :
    int a = 20;
        void cube(){
            a *= a;
        }
};

class d :virtual public bvirtual public c{
    public:
        void print(){
            cube();
            sqr();
            cout << c::a << endl;
            cout << b::a;
        }
};

int main(){
    d obj;
    obj.print();
}

#include <iostream>
#include <cmath>
using namespace std;
/*
Create 2 classes:
    1. SimpleCalculator - Takes input of 2 numbers using a utility function and perfoms +, -, *, / and displays the results using another function.
    2. ScientificCalculator - Takes input of 2 numbers using a utility function and perfoms any four scientific operations of your chioice and displays the results using another function.

    Create another class HybridCalculator and inherit it using these 2 classes:
    Q1. What type of Inheritance are you using? ---> Multiple inheritance
    Q2. Which mode of Inheritance are you using? ---> public SimpleCalculator, public ScientificCalculator
    Q3. Create an object of HybridCalculator and display results of simple and scientific calculator.
    Q4. How is code reusability implemented?
*/
class SimpleCalculator {
    int a, b;
    public:
        void getDataSimple()
        {
            cout<<"Enter the value of a"<<endl;
            cin>>a;
            cout<<"Enter the value of b"<<endl;
            cin>>b;
        }

        void performOperationsSimple(){
            cout<<"The value of a + b is: "<<a + b<<endl;
            cout<<"The value of a - b is: "<<a - b<<endl;
            cout<<"The value of a * b is: "<<a * b<<endl;
            cout<<"The value of a / b is: "<<a / b<<endl;
        }
};

class ScientificCalculator{
    int a, b;

    public:
        void getDataScientific()
        {
            cout << "Enter the value of a" << endl;
            cin >> a;
            cout << "Enter the value of b" << endl;
            cin >> b;
        }

        void performOperationsScientific()
        { 
            cout << "The value of cos(a) is: " << cos(a) << endl;
            cout << "The value of sin(a) is: " << sin(a) << endl;
            cout << "The value of exp(a) is: " << exp(a) << endl;
            cout << "The value of tan(a) is: " << tan(a) << endl;
        }
};

class HybridCalculator : public SimpleCalculator, public ScientificCalculator{
    
};
int main()
{
    // SimpleCalculator calc;
    // ScientificCalculator calc;
    // calc.getData();
    // calc.performOperations();
    HybridCalculator calc;
    calc.getDataScientific();
    calc.performOperationsScientific();
    calc.getDataSimple();
    calc.performOperationsSimple();
    
    return 0;
}

>>COnstructors in Derived Class


#include<iostream>
using namespace std;
/*
Case1:
class B: public A{
   // Order of execution of constructor -> first A() then B()
};

Case2:
class A: public B, public C{
    // Order of execution of constructor -> B() then C() and A()
};

Case3:
class A: public B, virtual public C{
    // Order of execution of constructor -> C() then B() and A()
};

*/

class Base1{
    int data1;
    public:
        Base1(int i){
            data1 = i;
            cout<<"Base1 class constructor called"<<endl;
        }
        void printDataBase1(void){
            cout<<"The value of data1 is "<<data1<<endl;
        }
};

class Base2{
    int data2;

    public:
        Base2(int i){
            data2 = i;
            cout << "Base2 class constructor called" << endl;
        }
        void printDataBase2(void){
            cout << "The value of data2 is " << data2 << endl;
        }
};

class Derivedpublic Base2public Base1{
    int derived1derived2;
    public:
        Derived(int aint bint cint d) : Base2(b), Base1(a)
        {
            derived1 = c;
            derived2 = d;
            cout<< "Derived class constructor called"<<endl;
        }
        void printDataDerived(void)
        {
            cout << "The value of derived1 is " << derived1 << endl;
            cout << "The value of derived2 is " << derived2 << endl;
        }
};
int main(){
    Derived harry(1234);
    harry.printDataBase1();
    harry.printDataBase2();
    harry.printDataDerived();
    return 0;
}


>>Initialization List in constructors

#include <iostream>
using namespace std;
/*
Syntax for initialization list in constructor:
constructor (argument-list) : initilization-section
{
    assignment + other code;
}

class Test{
    int a;
    int b;
    public:
        Test(int i, int j) : a(i), b(j){constructor-body}
};

*/
class Test
{
    int a;
    int b;

public:
    // Test(int i, int j) : a(i), b(j)
    // Test(int i, int j) : a(i), b(i+j)
    // Test(int i, int j) : a(i), b(2 * j)
    // Test(int i, int j) : a(i), b(a + j)
    // Test(int i, int j) : b(j), a(i+b) -->RED Flag this will create problems because a will be initialized first
    Test(int iint j)
    {
        a = i;
        b = j;
        cout << "Constructor executed"<<endl;
        cout << "Value of a is "<<a<<endl;
        cout << "Value of b is "<<b<<endl;
    }
};

int main()
{
    Test t(46);

    return 0;
}


>>new and delete keyword in Pointers


#include<iostream>
using namespace std;

int main(){
    // Basic Example
    int a = 4;
    int* ptr = &a;
    *ptr = 999;
    cout<<"The value of a is "<<*(ptr)<<endl;

    // new operator
    // int *p = new int(40);
    float *p = new float(40.78);
    cout << "The value at address p is " << *(p) << endl;

    int *arr = new int[3];
    arr[0] = 10;
    *(arr+1) = 20;
    arr[2] = 30;
    // delete[] arr;
    cout << "The value of arr[0] is " << arr[0] << endl;
    cout << "The value of arr[1] is " << arr[1] << endl;
    cout << "The value of arr[2] is " << arr[2] << endl;

    // delete operator
    
    return 0;
}



>>Pointers to object and Arrow operator

#include<iostream>
using namespace std;

class Complex{
    int real, imaginary;
    public:
        void getData(){
            cout<<"The real part is "<< real<<endl;
            cout<<"The imaginary part is "<< imaginary<<endl;
        }

        void setData(int a, int b){
            real = a;
            imaginary = b;
        }

};
int main(){
    // Complex c1;
    // Complex *ptr = &c1;
    Complex *ptr = new Complex;
    // (*ptr).setData(1, 54); is exactly same as
    ptr->setData(1, 54);

    // (*ptr).getData(); is as good as 
    ptr->getData(); 


    // Array of Objects
    Complex *ptr1 = new Complex[4]; 
    ptr1->setData(1, 4); 
    ptr1->getData();
    return 0;
}



>>Array of objects using pointers


#include<iostream>
using namespace std;

class ShopItem
{
    int id;
    float price;
    public:
        void setData(int afloat b){
            id = a;
            price = b;
        }
        void getData(void){
            cout<<"Code of this item is "<< id<<endl;
            cout<<"Price of this item is "<<price<<endl;
        }
};
        // 1 2 3
        //     ^
        //     |
        //     |
        //     ptr
        // ptrTemp
int main(){
    int size = 3;
    // int *ptr = &size;
    // int *ptr = new int [34];

    // 1. general store item
    // 2. veggies item
    // 3. hardware item
    ShopItem *ptr = new ShopItem [size];
    ShopItem *ptrTemp = ptr;
    int pi;
    float q;
    for (i = 0i < sizei++)
    {
        cout<<"Enter Id and price of item "<< i+1<<endl;
        cin>>p>>q;
        // (*ptr).setData(p, q);
        ptr->setData(pq);
        ptr++; 
    }

    for (i = 0i < sizei++)
    {
        cout<<"Item number: "<<i+1<<endl;
        ptrTemp->getData();
        ptrTemp++;
    }
    
    
    return 0;
}


>>this pointer in C++

#include<iostream>
using namespace std;
class A{
    int a;
    public:
        // A & setData(int a){
        A& setData(int a){
            this->a = a;
            return *this;
        }

        void getData(){
            cout<<"The value of a is "<<a<<endl;
        }
};

int main(){
    // this is a keyword which is a pointer which points to the object which invokes the member function
    // in other words this keyword uss object ko point krta hai jisne yha p setdata() yaa aur kisi member funtion ko call kia hai
    A a;
    a.setData(4).getData();
    return 0;
}





>>Polymorphism



    // Polymorphism
    //  - one name and multiple forms
    //  - eg. Function overloading, operator overloading
    //  - eg. Virtual Functions
    /*
    Polymorphism in C++ can be of two types:
    1. Compile time polymorphism(Static or Early Binding)
       Compile-time polymorphism in C++ is achieved using:
        1.1 - Function overloading
        1.2 - Operator Overloading
    2. Run time polymorphism(Dynamic or late Binding)
       Run time polymorphism in C++ is achieved using:
        2.1 - Virtual functions


>>Pointers to Derived class and Virtual funtions

#include<iostream>
using namespace std;

class BaseClass{
    public:
        int var_base;
        void display(){
            cout<<"Dispalying Base class variable var_base "<<var_base<<endl;
        }
};

class DerivedClass : public BaseClass{
    public:
            int var_derived;
            void display(){
                cout<<"Dispalying Base class variable var_base "<<var_base<<endl;
                cout<<"Dispalying Derived class variable var_derived "<<var_derived<<endl;
            }
};
/*
1.  agr base class k pointer derieved class k object ko point krta hai 
    to jo data member and functions base class mein hain whi access kr skte hain.
2.  agr derieved class ka pointer base class k object ko point kre to error show hoga

3.  jaise k hm main funtion mein dekh skte hain 
    jb base class ka pointer derieved class k object ko point krta hai to display base waala call hota hai
    and
    jb derieved class ka pointer derieved class k object ko point krta hai to display() fn derieved waala hi call
    hota hai.

    isko hi run time polymorphism khte hain kuki ye run time me decide hora hai k kaunsa funtion bind hoga.
4.  now jb hum base class pointer use krre hain point krne k liye derieved class k object ko tb hume base class waala display
    use ni krna hai but derieved class waala hi display hi use krna hai to base class waale funtion ko virtual bana do 
    isse hoga ye k run time mein jb binding  hori hogi to compiler derieved class waale funtion k address ko bind krega and vo run ho jaaega.
5.  agr derieved class ka pointer derieved class k object ko hi point krra hai and derieved class waale display ko virtual krdia
    phir bhi derieved class waala display hi run hoga.
*/
int main(){
    BaseClass * base_class_pointer;
    BaseClass obj_base;

    DerivedClass obj_derived;

    base_class_pointer = &obj_derived; // Pointing base class pointer to derived class

    base_class_pointer->var_base = 34;
    // base_class_pointer->var_derived= 134; // Will throw an error
    base_class_pointer->display();

    base_class_pointer->var_base = 3400
    base_class_pointer->display();

    DerivedClass * derived_class_pointer;
    derived_class_pointer = &obj_derived;
    derived_class_pointer->var_base = 9448;
    derived_class_pointer->var_derived = 98;
    derived_class_pointer->display();

    // DerivedClass * p;   //will show error
    // p = &obj_base;
    // p->var_base = 90;
    // p->display();

    
    return 0;
}



>>Rules of Virtual function

/*
Rules for virtual functions
1.  They cannot be static
2.  They are accessed by object pointers
3.  Virtual functions can be a friend of another class
4.  A virtual function in the base class might not be used.
5.  If a virtual function is defined in a base class, there is no necessity of redefining it in the derived class.
    mtlb agr yha iss code mein agr CWHVideo ka display function nahi hota to base class waala virtual display run 
    hojata.
*/

#include<iostream>
using namespace std;

class CWH{
    protected:
        string title;
        float rating;
    public:
        CWH(string sfloat r){
            title =  s;
            rating = r;
        }
        virtual void display(){}
};

class CWHVideopublic CWH
{
    float videoLength;
    public:
        CWHVideo(string sfloat rfloat vl): CWH(sr){
            videoLength = vl;
        }
        void display(){
            cout<<"This is an amazing video with title "<<title<<endl;
            cout<<"Ratings: "<<rating<<" out of 5 stars"<<endl;
            cout<<"Length of this video is: "<<videoLength<<" minutes"<<endl;
        }
};    

class CWHTextpublic CWH
{
    int words;
    public:
        CWHText(string sfloat rint wc): CWH(sr){
            words = wc;
        }
     void display(){
      cout<<"This is an amazing text tutorial with title "<<title<<endl;
      cout<<"Ratings of this text tutorial: "<<rating<<" out of 5 stars"<<endl;
      cout<<"No of words in this text tutorial is: "<<words<<" words"<<endl;
         }
};

int main(){
    string title;
    float ratingvlen;
    int words;

    // for Code With Harry Video
    title = "Django tutorial";
    vlen = 4.56;
    rating = 4.89;
    CWHVideo djVideo(titleratingvlen);

    // for Code With Harry Text
    title = "Django tutorial Text";
    words = 433;
    rating = 4.19;
    CWHText djText(titleratingwords);

    CWHtuts[2];
    tuts[0] = &djVideo;
    tuts[1] = &djText;

    tuts[0]->display();
    tuts[1]->display();

    return 0;
}




>>Abstract Base Class and Pure Virtual Functions

/*
Pure Virtual Functions in C++
Pure virtual function is a function that doesn’t perform any operation and the function
is declared by assigning the value 0 to it. Pure virtual functions are declared in abstract base classes.

Abstract Base Class in C++
Abstract base class is a class that has at least one pure virtual function in its body. 
The classes which are inheriting the base class must need to override the pure virtual function of the abstract 
class otherwise the compiler will throw an error.
*/
#include<iostream>
using namespace std;

class CWH{
    protected:
        string title;
        float rating;
    public:
        CWH(string sfloat r){
            title =  s;
            rating = r;
        }
        // this is called pure virtual function jo kuch krta ni hai but isliye hai kuki isko un classes mein 
        // define kia jaaega jo is CWH class se inherite hongi. and yhan ye CWH class Abstract Base class hai.
        virtual void display()=0;
};

class CWHVideopublic CWH
{
    float videoLength;
    public:
        CWHVideo(string sfloat rfloat vl): CWH(sr){
            videoLength = vl;
        }
        void display(){
            cout<<"This is an amazing video with title "<<title<<endl;
            cout<<"Ratings: "<<rating<<" out of 5 stars"<<endl;
            cout<<"Length of this video is: "<<videoLength<<" minutes"<<endl;
        }
};    

class CWHTextpublic CWH
{
    int words;
    public:
        CWHText(string sfloat rint wc): CWH(sr){
            words = wc;
        }
     void display(){
      cout<<"This is an amazing text tutorial with title "<<title<<endl;
      cout<<"Ratings of this text tutorial: "<<rating<<" out of 5 stars"<<endl;
      cout<<"No of words in this text tutorial is: "<<words<<" words"<<endl;
         }
};


int main(){
    string title;
    float ratingvlen;
    int words;

    // for Code With Harry Video
    title = "Django tutorial";
    vlen = 4.56;
    rating = 4.89;
    CWHVideo djVideo(titleratingvlen);

    // for Code With Harry Text
    title = "Django tutorial Text";
    words = 433;
    rating = 4.19;
    CWHText djText(titleratingwords);

    CWHtuts[2];
    tuts[0] = &djVideo;
    tuts[1] = &djText;

    tuts[0]->display();
    tuts[1]->display();

    return 0;
}





>>File I/O 

The file is a patent of data that is stored in the disk. Anything written inside the file is called a patent, for example: “#include” is a patent. The text file is the combination of multiple types of characters, for example, semicolon “;” is a character.

The computer read these characters in the file with the help of the ASCII code. Every character is mapped on some decimal number. For example, the ASCII code for the character “A” is “65” which is a decimal number. These decimal numbers are converted into a binary number to make them readable for the computer because the computer can only understand the language of “0” and “1”.

The reason that computers can only understand binary numbers is that a computer is made up of switches and switches only perform two operations “true” or “false”.

File Input and Output in C++

The file can be of any type whether it is a file of a C++ program, a file of a game, or any other type of file. There are two main operations that can be performed on files

  • Read File
  • Write File

An image is shown below to show the process of file read and write.




Figure 1: File Read and Write Diagram

As shown in figure 1,

  1. The user can provide input to the C++ program by using the keyboard through the “cin>>” keyword
  2. The user can get output from the C++ program on the monitor through the “cout<<” keyword
  3. The user can write on the file
  4. The user can read the file


>>File reading and writing

These are some useful classes for working with files in C++

  • fstreambase
  • ifstream --> derived from fstreambase
  • ofstream --> derived from fstreambase

In order to work with files in C++, you will have to open it. Primarily, there are 2 ways to open a file:

  • Using the constructor
  • Using the member function open() of the class

An example program is shown below to demonstrate the concept of reading and writing files

#include<iostream>
#include<fstream>

using namespace std;

int main(){
    string st = "Harry bhai";
    // Opening files using constructor and writing it
    ofstream out("sample60.txt"); // Write operation
    out<<st;

    return 0;
}

Code Snippet 1: Writing Files Example Program

As shown in a code snippet 1,

  1. We have created a string “st” which has a value “harry Bhai”
  2. Object “out” is created of the type ofstream and the file “sample60.txt” is passed to it
  3. The string “st” is passed to object “out”

The output of the following program is shown in figure 1


Figure 1: Writing File Operation Output

#include<iostream>
#include<fstream>

using namespace std;

int main(){
    string st2;
    // Opening files using constructor and reading it
    ifstream in("sample60b.txt"); // Read operation
    in>>st2;
    getline(in, st2);  
    cout<<st2;

    return 0;
}

Code Snippet 2: Reading Files Example Program

As shown in a code snippet 1,

  1. We have created a string “st2” which is empty
  2. We have made a text file “sample60b.txt” and written “This is coming from a file” in it
  3. Object “in” is created of the type instream and the file “sample60b.txt” is passed to it
  4. The function “getline” is called and the object “in” and the string “st2” are passed to it. The main thing to note here is that the function “getline” is used when we want to read the whole line
  5. String “st2” is printed

The output of the following program is shown in figure 2



>>FIle Read and Write in Same Program and Closing File

#include<iostream>
#include<fstream>
using namespace std;

int main(){
    string st;
    // getline se multiword string input le skte hain.
    cout << "Enter Your name : ";
    getline(cins);

    ofstream write("11.txt");
    write << s + " is my name.\n";
    // jb read yaa write operation perform kr lo to file ko close kr dete hain.
    // isse agr usi file ko read krna hoga phrse to kr skte hain agr ye use ni kia to ek hi file ko read write ni kr skte.
    write.close();

    ifstream read("11.txt");
    getline(readt);
    cout << t;
    read.close();

    return 0;
}



>>File I/O open() and eof() functions

#include<iostream>
#include<fstream>
using namespace std;

int main(){
    string stu;
    // getline se multiword string input le skte hain.
    cout << "Enter Your name : ";
    getline(cins);

    // opening file using constructor
    ofstream write("11.txt");
    write << s + " is my name.\n";
    write << "What is your name?\n";
    write << "HUH?";
    // jb read yaa write operation perform kr lo to file ko close kr dete hain.
    // isse agr usi file ko read krna hoga phrse to kr skte hain agr ye use ni kia to ek hi file ko read write ni kr skte.
    write.close();

    ifstream read;

    // opening file using open() function
    read.open("11.txt");
    // below lines print first and second letter of the first line.
    // read >> t;      read >> u;
    // cout << t + u;

    // to read all the data which is in file use while loop.
    // while loop k andr ka statement ye bol rha hai k jbtk end of file is false tbtk while loop chalate rho.
    while(read.eof() == 0){
        getline(readt);
        cout << t << endl;
    }
    read.close();

    return 0;
}




>>Templates



// template is nothing but it creates class with the data member we want
// jaise humne float datatype template mein pass kia to float ka class bana dena 
// iss program mein jahan jahan T likha hoga uske jgah vo data type laga dega.
// this is very important in competitive coding and it saves time.

#include<iostream>
using namespace std;

template <class T>
    class vector{
    T *arr;
    int size;
    T d = 0;
    public:
        vector(int n) : size(n){
            arr = new T[size];
        }
        void getdata(){
            cout << "Enter values in vector : ";
            for(int i = 0i < sizei++){
                cin >> arr[i];
            }
        }
        T dotproduct(vector &v){
            for(int i = 0i < sizei++){
                d += this->arr[i] * v.arr[i];
            }
            return d;
        }
    };

int main(){
    vector<floatv1(3);
    v1.getdata();

    vector<floatv2(3);
    v2.getdata();

    float ans;
    ans = v2.dotproduct(v1);
    cout << "Dot product is : " << ans;

    return 0;
}




>>Template with multiple arguments and default arguments

// template here have multiple argument or it takes multiple datatype as an argument.

#include<iostream>
using namespace std;

// isme maine default argument passs kia hai isse hoga ye k agr maine obj bnate wkt koi data member ni dia as a argument 
// to ye default argument use ho jaaenge aur agr datatype de dia to default na use hokr jo dia hai vo use ho jaaega.
template <class T1 = intclass T2 = floatclass T3 = char>
    class data{
        T1 a;
        T2 b;
        T3 c;
        public:
            data(T1 xT2 yT3 z) : a(x), b(y), c(z){}
            void putdata(){
                cout << "T1 : " << a << endl;
                cout << "T2 : " << b << endl;
                cout << "T3 : " << c << endl;
            }
    };

int main(){
    data<charcharfloatobj('P''c'1.5);
    obj.putdata();

    cout << endl;

    data<> obj1(13.4's');
    obj1.putdata();

    return 0;
}


>>Function Template with arguments

#include<iostream>
using namespace std;

template<class T1, class T2>
    float avg(T1 a, T2 b){
        float x;
        x = (a+b)/2.0;
        return x;
    }

int main(){
    float l;
    l = avg(2.4, 4);
    cout << l;
    return 0;
}


>>Defining member function outside template and overloading template functions

#include<iostream>
using namespace std;

// ---------------------------------------------------------------------------------------
// ye template bss isliye banaya hai taaki ye bata sake k template k andr k 
// member function ko class k bhrr kse define krte hain.
template<class T>
    class data{
        T d;
        public:
            data(T x):d(x){}
            
            void putdata();
    };

template<class T>
    void data<T> :: putdata(){
        cout << "The value of d is : "<< d << endl;
    }
// ----------------------------------------------------------------------------------------

void func(int q){
    cout << "In func which is not templatised : " <<  q << endl;
}

template<class C>
    void func(C q){
        cout << "In func which is templatised : " << q << endl;
    }

int main(){
    // for defining member function outside the class
    data<charobj('p');
    obj.putdata();

    // ye func isliye banaya hai taaki bata paae k templatised function se jyada priority 
    // not templatised function ko milti hai.
    func(3);

    return 0;
}




>>Standard Template Library(STL)

RA = random access



>>Vectors

#include<iostream>
#include<vector>
using namespace std;


void display(vector<int&v){
    for (int i = 0i < v.size(); i++)
    {
        cout << v.at(i<< "\t";
    }     

int main(){
    // diff ways to declare vector
    // zero length integer vector.
    vector<intv1;
    // 4-element integer vector.
    vector<intv2(4);
    // same as v2 4-element integer array
    vector<intv3(v2);
    // 4-element vector in f's. iske container mein 4 char ka space hota hai and sbme 'f' stored hota hai.
    vector<charv4(4'f');
    int sizeelement;

    cout << "Enter size of an array : ";
    cin >> size;

    for (int i = 0i < sizei++){
        cout << "Enter vector element number " << (i+1<< " : ";
        cin >> element;
        // baki sb element ko ek step back push kr deta hai and element ko last mein add kr deta hai.
        v1.push_back(element);
    }
    // // pops out last object
    // v1.pop_back();
    // it makes and iterator which points to the first object of tha container.
    vector<int> :: iterator iter = v1.begin();
    // it inserts value 69 in container 5 times at the postion first.
    // agr insert mein iter ki jgha iter+1 use krlia to vo postion 2 p same result print kr dega.
    v1.insert(iter+2569);
    display(v1);

    return 0;
}



>>List

#include<iostream>
#include<list>
using namespace std;

void display(list<int&ls){
    list<int> :: iterator it;

    for (it = ls.begin(); it != ls.end(); it++){
        cout << *it << " ";
    }
    cout << endl;
}

int main(){
    // empty list of 0 length.
    list<intl1;
    for (int i = 0i < 3i++){
        l1.push_front((i+1)*2);
    }
    l1.push_back(2);
    l1.sort();
    cout << "List 1 : ";
    display(l1);
    // // jitni jgah bhi 2 hoga list mein vo remove ho jaaega remove function se.
    // l1.remove(2);
    // display(l1);
    
    // empty list of length 4
    list<intl2(4);
    list<int> :: iterator ite;
    ite = l2.begin();
    *ite = 45;
    ite++;
    *ite = 5;
    ite++;
    *ite = 4;
    ite++;
    *ite = 78;
    ite++;
    l2.sort();
    cout << "List 2 : ";
    display(l2);
    
    cout << "Merged List : ";
    l1.merge(l2);
    display(l1);

    cout << "Reverse of Merged List : ";
    l1.reverse();
    display(l1);

    return 0;
}



>>Map

#include<iostream>
#include<map>
#include<iomanip>
using namespace std;

int main(){
    map<stringintm1;
    // map is like dictionary in python here name is key and marks are value of it.
    m1["Priyansh"] = 95;
    m1["pratik"] = 73;
    m1["Akshita"] = 35;
    m1["Ritanshu"] = 45;

    m1.insert({{"Akash"24}, {"Sneha"65}});
    map<stringint> :: iterator it;
    for (it = m1.begin(); it != m1.end(); it++){
        cout << setw(8)<< (*it).first << "   |" << setw(5)<< (*it).second << endl;
    }
    
    return 0;
}



>>Function object

#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;

int main(){
    // Function Objects(Functor) : Function wrapped in a class so that it is available like an object.
    int arr[] = {16436549670};

    // by default it sorts in ascending order.
    sort(arrarr+9);
    for (int i = 0i < 9i++){
        cout << arr[i<< " ";
    }
    
    cout << endl;
    // if we pass greaterfunctor then it will sort in descending order.
    sort(arrarr+9greater<int>());
    for (int i = 0i < 9i++){
        cout << arr[i<< " ";
    }

    return 0;
}



<>Operator overloading, 

Comments