Industrial Training File
Name: Nishant Panchal
  Roll No: 190070800031
  Branch: Computer Engg.
  Done from: Excel Computer Classes
  Subject: C++
                        Class and Objects
Class: A class in C++ is the building block that leads to Object-
Oriented programming. It is a user-defined data type, which holds its
own data members and member functions, which can be accessed and
used by creating an instance of that class. A C++ class is like a
blueprint for an object.
Syntax:
class <class_name>{
//code;
};
Object: An Object is an instance of a Class. When a class is defined,
no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
Syntax:
class_name object_name;
Example:
#include<iostream>
#include<conio.h>
using namespace std;
class student{
      public:
      char name[20],branch[20],rollno[20];
};
int main(){
      student s;// object of class student
      system("cls");
      cout<<"enter the name of the student : ";
      cin>>s.name;
      cout<<"enter the roll no of the student : ";
      cin>>s.rollno;
      cout<<"enter the class of the student : ";
      cin>>s.branch;
      cout<<"\n\n\n\nName of the student is "<<s.name<<endl;
      cout<<"Class of the student is "<<s.name<<endl;
      cout<<"Roll no of the student is "<<s.name<<endl;
      getch();
      return 0;
                             Encapsulation
In normal terms Encapsulation is defined as wrapping up of data and
information under a single unit. In Object Oriented Programming,
Encapsulation is defined as binding together the data and the functions
that manipulates them.
Encapsulation also lead to data abstraction or hiding. As using
encapsulation also hides the data. In the above example the data of
any of the section like sales, finance or accounts is hidden from any
other section.
In C++ encapsulation can be implemented using Class and access
modifiers
Access modifiers: Access modifiers are used to implement an
important aspect of Object-Oriented Programming known as Data
Hiding.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected
Example:
#include<iostream>
using namespace std;
class Circle {
                 // private data member
       private:
                 double radius;
                 // public member function
       public:
                 void compute_area(double r) {
                    // member function can access private
                    // data member radius
                    radius = r;
                    double area = 3.14*radius*radius;
                    cout << "Radius is: " << radius << endl;
                    cout << "Area is: " << area;
};
// main function
int main() {
      // creating object of the class
      Circle obj;
      // trying to access private data member
      // directly outside the class
      obj.compute_area(1.5);
      return 0;
                                  Constructors
A constructor is a special type of member function of a class which
initializes objects of a class. In C++, Constructor is automatically called
when object(instance of class) create. It is special member function of
the class because it does not have any return type.
   Constructor has same name as the class itself
   Constructors don’t have return type
   A constructor is automatically called when an object is created.
   It must be placed in public section of class.
   If we do not specify a constructor, C++ compiler generates a default
    constructor for object (expects no parameters and has an empty
    body).
                           Types of Constructors
    1. Default Constructors: Default constructor is the constructor
       which doesn’t take any argument. It has no parameters.
    2. Parameterized Constructors: It is possible to pass arguments to
       constructors. Typically, these arguments help initialize an object
       when it is created. To create a parameterized constructor, simply
       add parameters to it the way you would to any other function.
       When you define the constructor’s body, use the parameters to
       initialize the object.
    3. Copy Constructor: A copy constructor is a member function
       which initializes an object using another object of the same class
    Example:
#include <iostream>
using namespace std;
class point {
       private:
              double x, y;
       public:
              // Non-default Constructor &
              // default Constructor
              point (double px, double py) {
                    x = px, y = py;
              }
};
int main(void) {
      // Define an array of size
      // 10 & of type point
      // This line will cause error
      point a[10];
      // Remove above line and program
      // will compile without error
      point b = point(5, 6);
}
                             Distructors
Destructor is an instance member function which is invoked
automatically whenever an object is going to be destroyed. Meaning, a
destructor is the last function that is going to be called before an object
is destroyed.
    Destructor function is automatically invoked when the objects are
     destroyed.
    It cannot be declared static or const.
    The destructor does not have arguments.
    It has no return type not even void.
    An object of a class with a Destructor cannot become a member of
     the union.
    A destructor should be declared in the public section of the class.
    The programmer cannot access the address of destructor.
Example:
class String {
       private:
              char* s;
              int size;
       public:
             String(char*); // constructor
             ~String(); // destructor
};
String::String(char* c) {
       size = strlen(c);
       s = new char[size + 1];
       strcpy(s, c);
}
String::~String() {
       delete[] s;
}
                                 Polymorphism
The word polymorphism means having many forms. In simple words,
we can define polymorphism as the ability of a message to be
displayed in more than one form. A real-life example of polymorphism,
a person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, an employee. So the
same person posses different behavior in different situations. This is
called polymorphism. Polymorphism is considered as one of the
important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
    Compile time Polymorphism
    Runtime Polymorphism
Compile time polymorphism: This type of polymorphism is achieved
by function overloading or operator overloading.
    Function Overloading: When there are multiple functions with
     same name but different parameters then these functions are said
      to be overloaded. Functions can be overloaded by change in
      number of arguments or/and change in type of arguments.
     Operator Overloading: C++ also provide option to overload
      operators. For example, we can make the operator (‘+’) for string
      class to concatenate two strings. We know that this is the addition
      operator whose task is to add two operands. So a single operator ‘+’
      when placed between integer operands , adds them and when
      placed between string operands, concatenates them.
Example:
    #include<iostream>
    using namespace std;
    class Complex {
          private:
                int real, imag;
          public:
                Complex(int r = 0, int i =0) {
                      real = r;
                      imag = i;
                }
               // This is automatically called when '+' is used with
               // between two Complex objects
               Complex operator + (Complex const &obj) {
                      Complex res;
                      res.real = real + obj.real;
                      res.imag = imag + obj.imag;
                      return res;
               void print() {
                      cout << real << " + i" << imag << endl;
};
int main() {
             Complex c1(10, 5), c2(2, 4);
             Complex c3 = c1 + c2; // An example call to "operator+"
             c3.print();
          Runtime polymorphism: This type of polymorphism is achieved
           by Function Overriding.
       Function overriding on the other hand occurs when a derived
        class has a definition for one of the member functions of the base
        class. That base function is said to be overridden.
Example:
        #include <bits/stdc++.h>
        using namespace std;
        class base {
           public:
                 virtual void print () {
                        cout<< "print base class" <<endl;
                 }
                  void show () {
                        cout<< "show base class" <<endl;
                  }
        };
        class derived:public base {
           public:
                  void print () { //print () is already virtual function in derived class,
        we could also declared as virtual void print () explicitly
                    cout<< "print derived class" <<endl;
               }
               void show () {
                     cout<< "show derived class" <<endl;
               }
   };
   //main function
   int main() {
       base *bptr;
       derived d;
       bptr = &d;
        //virtual function, binded at runtime (Runtime polymorphism)
        bptr->print();
        // Non-virtual function, binded at compile time
        bptr->show();
        return 0;
   }
           Defining functions outside the class
The member function can be declared outside the class using scope
resolution operator ( :: )
Example:
#include<iostream>
#include<conio.h>
using namespace std;
class math {
       private:
               int a,b,c;
       public:
               void sum();
};
void math::sum() {
       cout<<"enter two value:"<<endl;
       cin>>a>>b;
       c=a+b;
       cout<<"sum of two no is :"<<c;
int main() {
       math s;// object of calss student
       s.sum();
       getch();
       return 0;
      Defining operator overloading outside the class.
       return_type calss_name::operator (argument)
       {
       //code;
      }
                                  Friend function
In object-oriented programming, a friend function, that is a "friend" of
a given class, is a function that is given the same access as methods to
private and protected data. [1]
A friend function is declared by the class that is granting access, so
friend functions are part of the class interface, like methods. Friend
functions allow alternative syntax to use objects, for
instance f(x) instead of x.f() , or g(x,y) instead of x.g(y) .
Friend functions have the same implications on encapsulation as
methods.
 Example:
 #include <iostream>
 class A {
          private:
                int a;
          public:
                A() {
                         a = 0;
                friend class B; // Friend Class
 };
class B {
       private:
               int b;
       public:
               void showA(A& x) {
                        // Since B is friend of A, it can access
                        // private members of A
                        std::cout << "A::a=" << x.a;
};
int main() {
       A a;
       B b;
       b.showA(a);
       return 0;
}
                              Inheritance
The capability of a class to derive properties and characteristics from
another class is called Inheritance. Inheritance is one of the most
important feature of Object Oriented Programming.
Sub Class: The class that inherits properties from another class is
called Sub class or Derived Class.
Super Class:The class whose properties are inherited by sub class is
called Base Class or Super class.
Types of Inheritance in C++
1. Single Inheritance: In single inheritance, a class is allowed to
inherit from only one class. i.e. one sub class is inherited by one base
class only.
 Example:
 #include <iostream>
 using namespace std;
 // base class
 class Vehicle {
       public:
              Vehicle() {
                    cout << "This is a Vehicle" << endl;
 };
 // sub class derived from a single base classes
 class Car: public Vehicle {
 };
 // main function
 int main() {
        // creating object of sub class will
        // invoke the constructor of base classes
        Car obj;
        return 0;
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where
a class can inherit from more than one classes. i.e one sub class is
inherited from more than one base classes.
Example:
#include <iostream>
using namespace std;
// first base class
class Vehicle {
      public:
               Vehicle() {
                     cout << "This is a Vehicle" << endl;
};
// second base class
class FourWheeler {
      public:
               FourWheeler() {
                     cout << "This is a 4 wheeler Vehicle" << endl;
};
// sub class derived from two base classes
class Car: public Vehicle, public FourWheeler {
};
// main function
int main() {
      // creating object of sub class will
      // invoke the constructor of base classes
      Car obj;
      return 0;
}
3.Multilevel Inheritance: In this type of inheritance, a derived class is
created from another derived class.
  Example:
  #include <iostream>
  using namespace std;
  // base class
  class Vehicle
  {
    public:
     Vehicle()
     {
       cout << "This is a Vehicle" << endl;
     }
  };
  // first sub_class derived from class vehicle
  class fourWheeler: public Vehicle
  { public:
     fourWheeler()
     {
       cout<<"Objects with 4 wheels are vehicles"<<endl;
     }
  };
  // sub class derived from the derived base class fourWheeler
  class Car: public fourWheeler{
     public:
      Car()
      {
        cout<<"Car has 4 Wheels"<<endl;
      }
  };
   // main function
   int main()
   {
      //creating object of sub class will
      //invoke the constructor of base classes
      Car obj;
      return 0;}
4. Hierarchical Inheritance: In this type of inheritance, more than one
sub class is inherited from a single base class. i.e. more than one
derived class is created from a single base class.
Example:
#include <iostream>
using namespace std;
// base class
class Vehicle {
       public:
             Vehicle() {
                   cout << "This is a Vehicle" << endl;
             }
};
// first sub class
class Car: public Vehicle {
};
// second sub class
class Bus: public Vehicle {
};
// main function
int main() {
      // creating object of sub class will
      // invoke the constructor of base class
      Car obj1;
      Bus obj2;
      return 0;
}
5.Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by
combining more than one type of inheritance. For example: Combining
Hierarchical inheritance and Multiple Inheritance.
Example:
#include <iostream>
using namespace std;
// base class
class Vehicle {
      public:
               Vehicle() {
                     cout << "This is a Vehicle" << endl;
};
//base class
class Fare {
      public:
               Fare() {
                     cout<<"Fare of Vehicle\n";
};
// first sub class
class Car: public Vehicle {
};
// second sub class
class Bus: public Vehicle, public Fare {
};
// main function
int main() {
       // creating object of sub class will
       // invoke the constructor of base class
       Bus obj2;
       return 0;
}
                              Exception Handling
One of the advantages of C++ over C is Exception Handling.
Exceptions are run-time anomalies or abnormal conditions that a
program encounters during its execution. There are two types of
exceptions: a)Synchronous, b)Asynchronous(Ex:which are beyond the
program’s control, Disc failure etc). C++ provides following specialized
keywords for this purpose.
try: represents a block of code that can throw an exception.
catch: represents a block of code that is executed when a particular
exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that
a function throws, but doesn’t handle itself.
Example:
#include <iostream>
using namespace std;
int main() {
      int x = -1;
      // Some code
      cout << "Before try \n";
      try {
               cout << "Inside try \n";
               if (x < 0) {
                    throw x;
                    cout << "After throw (Never executed) \n";
      } catch (int x ) {
             cout << "Exception Caught \n";
      cout << "After catch (Will be executed) \n";
      return 0;
File Handling
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream
available in fstream headerfile.
ofstream:
Stream class to write on files
      ifstream: Stream class to read from files
             fstream: Stream class to both read and write from/to files.
                 Now the first step to open the particular file for read or write
operation. We can open file by
                    1. passing file name in constructor at the time of object
creation
                    2. using the open method
                    Open File by using constructor
                     ifstream (const char* filename, ios_base::openmode mode =
ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
       ifstream fin(“filename”);
Open File by using open method
Calling of default constructor
ifstream fin;
fin.open(filename, openmode)
fin.open(“filename”);
Modes :
Member Constant Stands For Access
in *    Input File open for reading:
the internal stream buffer supports input operations.
out     Output       File open for writing:
        the internal stream buffer supports output operations.
      binary         Binary        Operations are performed in binary mode rather
than text.
        ate     at end     The output position starts at the end of the file.
     app Append           All output operations happen at the end of the file,
appending to its existing contents.
       trunc Truncate            Any contents that existed in the file before it is open
are discarded.
Default Open Modes :
      ifstream         ios::in
      ofstream         ios::out
      fstream          ios::in | ios::out
Problem Statement :
      To read and write a File in C++.
Examples:
Input :
      Welcome in GeeksforGeeks. Best way to learn things.
      -1
Output :
      Welcome in GeeksforGeeks. Best way to learn things.
Recommended: Please try your approach on {
                 IDE
            first, before moving on to the solution.
            Below is the implementation by using ifstream & ofstream classes.
            •          C++
            /* File Handling with C++ using ifstream & ofstream class object*/
               /* To write the Content in File*/
               /* Then to read the content of file*/
#include <iostream>
               /* fstream header file for ifstream, ofstream,
                fstream classes */
#include <fstream>
               using namespace std;
// Driver Code
int main() {
      // Creation of ofstream class object
      ofstream fout;
      string line;
      // by default ios::out mode, automatically deletes
      // the content of file. To append the content, open in ios:app
      // fout.open("sample.txt", ios::app)
      fout.open("sample.txt");
      // Execute a loop If file successfully opened
while (fout) {
      // Read a Line from standard input
      getline(cin, line);
      // Press -1 to exit
      if (line == "-1")
                break;
      // Write line in file
      fout << line << endl;
// Close the File
fout.close();
// Creation of ifstream class object to read the file
ifstream fin;
// by default open mode = ios::in mode
fin.open("sample.txt");
    // Execute a loop until EOF (End of File)
    while (fin) {
           // Read a Line from File
           getline(fin, line);
           // Print line in Console
           cout << line << endl;
    // Close the file
    fin.close();
    return 0;