Object Oriented Programming in C++



        

Object Oriented Programming in C++



Object-oriented programming – As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding,abstraction,encapsulation, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

Importance in c++ language:
           
  1. Class
  2. Objects
  3. Encapsulation
  4. Abstraction
  5. Polymorphism
  6. Inheritance
  7. Dynamic binding
  8. Message passing
           

Class : 

                    Class is the collection of similar objects.

                   The building block of C++ that leads to Object-Oriented programming is a Class. 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 class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.

  • A Class is a user-defined data-type which has data members and member functions.
  • Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions define the properties and behaviour of the objects in a Class.
  • In the above example of class Car, the data member will be speed limit, mileage etc and member functions can apply brakes, increase speed etc.


Objects :

                       An Object is an identifiable entity with some characteristics and behaviour. 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.

     Object take up space in memory and have an associated address like a record in pascal or structure or union in C.

When a program is executed the objects interact by sending messages to one another.

Each object contains data and code to manipulate the data. Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted and type of response returned by the objects.



Encapsulation : 

     


  





Encapsulation means binding data and the code.

 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 manipulate them.

Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when for some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”.

Encapsulation also leads 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 are hidden from any other section.


Abstraction : 


 Data abstraction is one of the most essential and important features of object-oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.

Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of the car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.

  • Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to the outside world and which is not.
  • Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate the power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating the power of numbers.


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 person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations. This is called polymorphism.

An operation may exhibit different behaviours in different instances. The behaviour depends upon the types of data used in the operation.


There are two types of polymorphism:

 1] Compile time                     2] Run time


1] compile time  

        i)  function overloading

        ii) operator overloading

2] Run time

        i) function overriding


C++ supports operator overloading and function overloading.

  • Operator Overloading: The process of making an operator to exhibit different behaviours in different instances is known as operator overloading.
  • Function Overloading: Function overloading is using a single function name to perform different types of tasks.
    Polymorphism is extensively used in implementing inheritance.

Example: Suppose we have to write a function to add some integers, some times there are 2 integers, some times there are 3 integers. We can write the Addition Method with the same name having different parameters, the concerned method will be called according to parameters.


                                   int main()
                                      {
                                          sum1=sum(30,50);
                                          sum2=sum(50,32,10);
                                       }
 
 int sum(int a, int b)                                       int sum(int a, int b, int c)
   {                                                                       {
       return (a+b);                                                     return (a+b+c);
    }                                                                       }



Inheritance :
                              It is a process to creating new class from existing class.
new class = derived class, child class
existing clss = base class, parent class

 The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features 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.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.


The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming. 

Inheritance is a feature or a process in which, new classes are created from the existing classes. The new class created is called “derived class” or “child class” and the existing class is known as the “base class” or “parent class”. The derived class now is said to be inherited from the base class.








Types of inheritance:

1]  single

2]  multiple

3]  multilevel

4]  hierarchical

5]  hybrid


1] Single inheritance :

        In single inheritance, a class is allowed to inherit from only one class. i.e. one subclass is inherited by one base class only.

                                  Single inheritance enables a derived class (child class) to inherit properties and behavior from a single parent class (base class).

Syntax:

class subclass_name : access_mode base_class
{
  // body of subclass
};

OR

class A
{ 
... .. ... 
};

class B: public A
{
... .. ...
};

2] Multiple Inheritance:

    Multiple Inheritance is a feature of C++ where a class can inherit from more than one class.

 i.e one subclass is inherited from more than one base class.

Syntax:


class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
  // body of subclass
};



class B
{ 
... .. ... 
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};


3] Multilevel Inheritance:

   In this type of inheritance, a derived class is created from another derived class.


Syntax:


class C
{ 
... .. ... 
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};

4] Hierarchical Inheritance:

 In this type of inheritance, more than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class.


Syntax:


class A  
{  
    // body of the class A.  
}    
class B : public A   
{  
    // body of class B.  
}  
class C : public A  
{  
    // body of class C.  
}   
class D : public A  
{  
    // body of class D.  
}   
5] Hybrid (Virtual) Inheritance:
 Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. 
Below image shows the combination of hierarchical and multiple inheritances:
Example:
// C++ program for Hybrid Inheritance
 
#include <iostream>
using namespace std;
 
// base class
class Vehicle {
public:
    Vehicle() { cout << "This is a Vehicle\n"; }
};
 
// 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;
}

Dynamic binding :

 In dynamic binding, the code to be executed in response to function call is decided at runtime. 


 Message passing :

Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function and the information to be sent.



 c++ program to display hello world :

                                                The “Hello World” program is the first step towards learning any programming language and is also one of the simplest programs you will learn. All you have to do is display the message “Hello World” on the screen. Let us now look at the program:


// c++ program to display hello world

#include<iostream>      // header file for input output functions
 //using namespace std;
 int main()             // main function where the execution of program begin
  {  
      cout<<"hello world";     // print hello world
   //  std:: cout<<"hello world";
   // If we cant use the namespace std then we should be use this above line...
      return 0;
  }


 Comments : 

             Comment is used for ignore the statements or display the additional information about the program.

             Compiler just ignore the comment and skip the line and execute the other line of program.

              There are two types of comments in c++

              1. single line comment:

                   e.g.   //this is single line comment

              2. Multiline comment:

                  e.g.  / *  This is a 

                                multiline comment...

                           ........ */


using namespace std;  

       This line is used to import the entirely of the std namespace of the program.

       The statement using namespace std is generally considered a bad practise.

        when we import the namespace we are essentially pulling all types of difinations into the current scope.

The std namespace is huge.

The alternative to this statements is to specify the namespace to which the identifier belongs using the scope resolution operation ( :: ) each time we declare a type.



main ( ) function : 


This line is used to declare a function named “main” which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C++ program begins with the main() function, no matter where the function is located in the program. So, every C++ program must have a main() function. 


 {  and  } :  

 The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’ indicates the ending of the main function. Everything between these two comprises the body of the main function.


std :: cout << " hello world " ;  : 

  This line tells the compiler to display the message “Hello World” on the screen. This line is called a statement in C++. Every statement is meant to perform some task. A semi-colon ‘;’ is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The std::cout is used to identify the standard character output device which is usually the desktop screen. Everything followed by the character “<<” is displayed to the output device. 


return 0;   :

This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function.


Important Points to Note while Writing a C++ Program:

  1. Always include the necessary header files for the smooth execution of functions. For example, <iostream> must be included to use std::cin and std::cout.
  2. The execution of code begins from the main() function.
  3. It is a good practice to use Indentation and comments in programs for easy understanding.
  4. cout is used to print statements and cin is used to take inputs.


Is it fine to write void main() or main() in C/C++?


In C++ the default return type of main is void, i.e. main() will not return anything. But, in C default return type of main is int, i.e. main() will return an integer value by default.

In C, void main() has no defined(legit) usage, and it can sometimes throw garbage results or an error. However, main() is used to denote the main function which takes no arguments and returns an integer data type.



C++ Data Types :


All variables use data-type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type requires a different amount of memory.

C++ supports a wide variety of data types and the programmer can select the data type appropriate to the needs of the application. Data types specify the size and types of value to be stored. However, storage representation and machine instructions to manipulate each data type differ from machine to machine, although C++ instructions are identical on all machines.


 C ++ support the following data types:

                       1. Primary or Built in or Fundamental data type

                         2. Derived data type

                         3. User defined data types


1] Primary or Built in or Fundamental data type

                                           These data types are built-in or predefined data types and can be used directly by the user to declare variables. example: int, char, float, bool, etc. Primitive data types available in C++ are: 

    1.integer
    2.boolean
    3.character
    4.floating point
    5.double floating point
    6.void
    7.wild character


2] Derived data type :
                                      The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. These can be of four types namely: 

     1.function
     2.array
     3.pointer
     4.reference

3] Abstract or User defined data type:
                                        These data types are defined by the user itself. Like, as defining a class in C++ or a structure. C++ provides the following user-defined datatypes: 

      1.Class
      2.Structure
      3.Union
      4.Typedef
      5.Enum



Basic Input / Output in C++  :


C++ comes with libraries that provide us with many ways for performing input and output. In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams.

  • Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard) to the main memory then this process is called input.
  • Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device( display screen ) then this process is called output.

Header files available in C++ for Input/Output operations are: 

  1. iostream: iostream stands for standard input-output stream. This header file contains definitions of objects like cin, cout, cerr, etc.
  2. iomanip: iomanip stands for input-output manipulators. The methods declared in these files are used for manipulating streams. This file contains definitions of setw, setprecision, etc.
  3. fstream: This header file mainly describes the file stream. This header file is used to handle the data being read from a file as input or data being written into the file as output.

The two instances cout in C++ and cin in C++ of iostream class are used very often for printing outputs and taking inputs respectively. These two are the most basic methods of taking input and printing output in C++. To use cin and cout in C++ one must include the header file iostream in the program.

This article mainly discusses the objects defined in the header file iostream like the cin and cout.  

  • Standard output stream (cout): Usually the standard output device is the display screen. The C++ cout statement is the instance of the ostream class. It is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<).

#include<iostream>
 using namespace std;
  int main()
   {
       char sample[]="learn world ~";
       cout<<sample << " this is computer science portal for learning programming..";
       return 0;
   }



Output: 
learn world ~ this is computer science portal for learning programming..






















































































































          In the above program, the insertion operator(<<) inserts the value of the string variable sample followed by the string “A computer science portal for learning programming..” in the standard output stream cout which is then displayed on the screen.



  • standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. 
  • The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.
#include<iostream>
 using namespace std;
  int main()
   {
       int age;
       cout<<"Enter your age:";   // insertion operator(<<)
       cin>>age;                // extraction operator(>>)
       cout<<"Your age is:"<<age;  
       return 0;
   }


Output: 

Enter your age:
Your age is: 18

The above program asks the user to input the age. The object cin is connected to the input device. The age entered by the user is extracted from cin using the extraction operator(>>) and the extracted data is then stored in the variable age present on the right side of the extraction operator.


  • Un-buffered standard error stream (cerr): The C++ cerr is the standard error stream that is used to output the errors. This is also an instance of the iostream class. As cerr in C++ is un-buffered so it is used when one needs to display the error message immediately. It does not have any buffer to store the error message and display it later.
  • The main difference between cerr and cout comes when you would like to redirect output using “cout” that gets redirected to file if you use “cerr” the error doesn’t get stored in file.(This is what un-buffered means ..It cant store the message)
#include <iostream>
 
using namespace std;
 
int main()
{
    cerr << "An error occurred";
    return 0;
}


Output: 

An error occurred

  • buffered standard error stream (clog): This is also an instance of ostream class and used to display errors but unlike cerr the error is first inserted into a buffer and is stored in the buffer until it is not fully filled. or the buffer is not explicitly flushed (using flush()). The error message will be displayed on the screen too.

#include <iostream>
 
using namespace std;
 
int main()
{
    clog << "An error occurred";
 
    return 0;
}


Output: 

An error occurred
program:Simple program to create class.
#include<iostream>
using namespace std;

 class student
 {
   private:
           int rollno;         //private data member
           char name[20];      //private data member
   public:
           void get()          //member function,methods
           {
              cout<<"enter the rollno:";
              cin>>rollno;
              cout<<"\nenter the name:";
              cin>>name;
           }
           void put()          //member function
           {
             cout<<"\n Rollno:"<<rollno;
             cout<<"\n Name:"<<name;
           }
 };    
   
 int main()    // non member function
{
  class student s1;
  s1.get();
  s1.put();
}

// Data member : when we declare the variables in the class then it is called as data members..
// methods/ member function  : it is part of a class.
//non member function  : it is not part of the class.

program:

If we want to write a defination of function outside of the class then use

the scope resolution operator ( :: )

Syntax: return type class name :: function name


#include<iostream>
using namespace std;

 class student
 {
   private:
           int rollno;         //private data member
           char name[20];      //private data member
   public:
           void get()          //member function,methods
           {
              cout<<"enter the rollno:";
              cin>>rollno;
              cout<<"\nenter the name:";
              cin>>name;
           }
           void put();          //member function
         
 };    
           void student:: put()
            {
             cout<<"\n Rollno:"<<rollno;
             cout<<"\n Name:"<<name;
            }
   
 int main()    // non member function
{
  class student s1;
  s1.get();
  s1.put();
}

// Data member : when we declare the variables in the class then it is called as data members..
// methods/ member function  : it is part of a class.
//non member function  : it is not part of the class.


Output:

enter the rollno:50

enter the name:Jacks

 Rollno:50 

 Name:Jacks


program:


//  Program of Array of object
//used for to store a multiple records..
#include<iostream>
using namespace std;

 class student
 {
   private:
           int rollno;        
           char name[20];      
   public:
           void get()          
           {
              cout<<"enter the rollno:";
              cin>>rollno;
              cout<<"enter the name:";
              cin>>name;
           }
           void put()          
           {
             cout<<"\n Rollno:"<<rollno;
             cout<<"\n Name:"<<name;
           }
 };    
   int main()    
{
  class student s1[10];   //Array of object
   int n;
   cout<<"\nenter the no. of records:";
   cin>>n;
    for(int i=0;i<n;i++)
        s1[i].get();
    for(int i=0;i<n;i++)
        s1[i].put();
}
Output:
enter the no. of records:3
enter the rollno:50
enter the name:Adam
enter the rollno:8
enter the name:lucy
enter the rollno:80
enter the name:stifler

 Rollno:50   
 Name:Adam   
 Rollno:8    
 Name:lucy   
 Rollno:80   
 Name:stifler
program:
// scope resolution operator ::
// uses: 1. To access global data
//2.To write a defination of member function outside of class.
 
#include<iostream>
using namespace std;
 int a=100;  // global variable

 int main()
 {
     int a=80;
     cout<<"a:"<<a;
     cout<<"\na:"<<::a;
 }
 // if we access the global variable then use scope resolution operator ( :: )
 // before variable


Output:

a:80 

a:100



// function - Inline function
// inline function increasing excution speed..
#include<iostream>
using namespace std;

class Data
{
  private:
          int a,b;
  public :
          void get()
           {
               cout<<"\n Enter the value of a and b:";
               cin>>a>>b;
           }
           void put();
};
         inline void Data::put()
          {
             cout<<"\na:"<<a<<"\nb:"<<b;
          }
 int main()
 {
     Data d1;
     d1.get();
     d1.put();
 }


OUTPUT:

Enter the value of a and b:5

8


a:5

b:8


//Reference variable
// Syntax: data_type &ref_var_name=existing_var_name;
#include<iostream>
using namespace std;
int main()
{
    int a=100;
    int &b=a;
    cout<<"\na:"<<a;
    cout<<"\nb:"<<b;
    cout<<"\n Address of a :"<<&a;
    cout<<"\n Address of b :"<<&b;
    b=200;
    cout<<"\n a:"<<a;
    cout<<"\n b:"<<b;
 }


OUTPUT:

a:100

b:100

 Address of a :0x61ff08

 Address of b :0x61ff08

 a:200

 b:200


/* Pass by/Call by reference
  Syntax: return_type func_name(data_type &ref_var,...)
            {

            }
*/
#include<iostream>
using namespace std;
 int sum1(int a,int b)        //call by value
  {
      return (a+b);
  }
 int sum2(int *p1,int *p2)    //call by address
  {
      return (*p1 + *p2);
  }
 int sum3(int &a,int &b)     // call by reference
  {
      return (a+b);
  }
 int main()
 {
     int a=10;
     int b=20;
     cout<<"\nSum1:"<<sum1(a,b);
     cout<<"\nSum2:"<<sum2(&a,&b);
     cout<<"\nSum3:"<<sum3(a,b);

 }
 


OUTPUT:

Sum1:30

Sum2:30

Sum3:30


/*
 Static Data Member
 - Class variable    --> sheared between object (Only one copy is created)
 - Instance variable --> Separate for object    (separate copy is created)
 - Local variable    --> variable passed/ declared in function called..
 */
 
 #include<iostream>
 using namespace std;

 class data
 {
   private:
           int a;     // Instance variable
    static int b;     // Class/static variable
   public:
          void get()
           {
               cout<<"\n Enter a :";
               cin>>a;
               cout<<"\n Enter b :";
               cin>>b;
           }
           void put()
           {
               cout<<"\n a:"<<a<<"\n b:"<<b;
           }
           void calsquare(int n)
            {
                int r=n*n;            // n and r is Local variable
                cout<<"\n Square of "<<n<<" is:"<<r;
            }
 };
    int data :: b=100;
    //static data member redeclaration outside the class..

    int main()
    {
        data d1,d2;
        d1.get();
        d2.get();
        d1.put();
        d2.put();
        d1.calsquare(5);
    }
    //here output of value b is printing same value for d1 and d2
    // because b is static or only one copy is created
    // which is change with time..


OUTPUT:

 Enter a :50


 Enter b :88


 Enter a :10


 Enter b :20


 a:50

 b:20

 a:10

 b:20

 Square of 5 is:25



// Static member function

#include<iostream>
using namespace std;

class data
{
  private:
   static int count;
          int a;
  public:
  static void  getcnt();
         void putcnt()
         {
             cout<<"\n No. of objects created:"<<count;
             a=100;
         }

};
         void data:: getcnt()
         {
             count++;
         }
         int data :: count=0;

 int main()
 {
     data d1;
     data :: getcnt();  // u can access using class without object
     data d2;
     data :: getcnt();
     d1.putcnt();
 }


OUTPUT:
No. of objects created:2


// function with default parameter or orgument
#include<iostream>
using namespace std;

int sum(int a=0 ,int b=0)
{
    int c;
    c=a+b;
    cout<<"\nAddition :"<<c;
}

int sum2(int a,int b=0 ,int c=9)
{
    int d ;
    d=a+b+c;
    cout<<"\nAddition:"<<d;
}
int main()
{
    sum();
    sum(3,4);
    sum(2);
    sum2(10);
}


OUTPUT:

Addition :0

Addition :7

Addition :2

Addition:19


// function with default parameter or argument
#include<iostream>
using namespace std;
class data
{
    public:
           int sum(int a=0 ,int b=0)
           {
            int c;
            c=a+b;
            cout<<"\nAddition :"<<c;
           }

          int add(int a=0,int b=0 ,int c=9)
           {
               int d ;
               d=a+b+c;
               cout<<"\nSum:"<<d;
           }
};
int main()
{
    data d;
    d.sum();
    d.sum(3,4);
    d.sum(2);
    d.add();
    d.add(10);
}


OUTPUT:

Addition :0

Addition :7

Addition :2

Sum:9      

Sum:19 


// Private data only accessible to member function
// Private data is not  accessible to non- member function called (data hinding)
// Public data is accessible for all (member and non member function)

#include<iostream>
using namespace std;
class data
{
  private:
         int a,b;
  public:
          void get()       //member function
           {
             cout<<"\nEnter a:";
             cin>>a;
             cout<<"\nEnter b:";
             cin>>b;
           }
          void put()       //non-member function
           {
            cout<<"\n a:"<<a;
            cout<<"\n b:"<<b;
           }
         friend int sum(data d);
};
        int sum(data d)
         {
            int c;
            c=d.a+d.b;
            cout<<"\nSum :"<<c;
         }
int main()
{
    data d;
    d.get();
    d.put();
    sum(d);
}


OUTPUT:


Enter a:5


Enter b:3


 a:5  

 b:3  

Sum :8


//friend function
// one function friend in two class
#include<iostream>
using namespace std;

class B;  //forward declaration
class A
{
    private:
            int a;
    public:
           void get();
         friend void put(A,B);
};
class B
{
    private:
            int b;
    public:
           void get();
         friend void put(A,B);
};

void A :: get()
 {
    cout<<"\n Enter a:";
    cin>>a;
 }

 void B :: get()
 {
    cout<<"\n Enter b:";
    cin>>b;
 }

 void put(A a1 , B b1)
 {
    cout<<"\n a:"<<a1.a<<"\n b:"<<b1.b;
 }

 int main()
 {
    A a1;
    B b1;
    a1.get();
    b1.get();
    put(a1,b1);
 }


OUTPUT:

Enter a:5


 Enter b:8


 a:5

 b:8


Class And types of class:

//local class
#include<iostream>
using namespace std;
void local()
{
    class data
    {
        public:
              void put()
              {
                cout<<"hello I'm local class";
              }
    };
    data d;
    d.put();
}
int main()
{
    local();
}


OUTPUT:

hello I'm local class



///global class
#include<iostream>
using namespace std;

    class data
    {
        public:
              void put()
              {
                cout<<"hello I'm Global class";
              }
    };
 void local()
 {
    data d;
    d.put();
 }
int main()
{
    local();
}


OUTPUT:

hello I'm Global class


//friend class
 #include<iostream>
 using namespace std;
 
 class data
 {
    private:
           int a,b;
    public:
          void get()
          {
            cout<<"\n Enter a:";
            cin>>a;
            cout<<"\n Enter b:";
            cin>>b;
          }
          void put()
          {
            cout<<"\n a:"<<a<<"\n b:"<<b;
          }
          friend class operations;
 };
 class operations
 {
    public:
         void add(data d1)
         {
            int c = d1.a + d1.b;
            cout<<"\n Addition       :"<<c;
         }
         
         void sub(data d1)
         {
            int c = d1.a - d1.b;
            cout<<"\n Substraction   :"<<c;
         }
         
         void mul(data d1)
         {
            int c = d1.a * d1.b;
            cout<<"\n Multiplication :"<<c;
         }
         
         void div(data d1)
         {
            int c = d1.a / d1.b;
            cout<<"\n Division       :"<<c;
         }
 };

 int main()
 {
    data d;
    d.get();
    d.put();
    operations op;
    op.add(d);
    op.sub(d);
    op.mul(d);
    op.div(d);
 }


OUTPUT:


Enter a:8


Enter b:5


 a:8

 b:5

 Addition       :13

 Substraction   :3 

 Multiplication :40

 Division       :1 



// nested class
#include<iostream>
using namespace std;

class Bdate
{
    private:
            int DD, MM, YYYY;
    public:
           void get()
           {
             cout<<"\n Enter the day  :";
             cin>>DD;
             cout<<"\n Enter the month:";
             cin>>MM;
             cout<<"\n Enter the year :";
             cin>>YYYY;
           }
           void put()
           {
            cout<<DD<<"/"<<MM<<"/"<<YYYY;
           }
};
class student
{
    private:
           int rno;
           char name[20];
           Bdate dob;
    public:
           void get()
           {
             cout<<"\n Enter Rollno   :";
             cin>>rno;
             cout<<"\n Enter Name     :";
             cin>>name;
             cout<<"\n Enter Birthdate:";
             dob.get();
           }
           void put()
           {
            cout<<"\n Rollno   :"<<rno;
            cout<<"\n Name     :"<<name;
            cout<<"\n Birthdate:";
            dob.put();
           }
};

int main()
{
    student st;
    st.get();
    st.put();

}


OUTPUT:

Enter Rollno     :50

Enter Name     :Swapnil


 Enter Birthdate:

 Enter the day    :26

 Enter the month:1

 Enter the year   :2001


 Rollno     :50       

 Name      :Swapnil  

 Birthdate :26/1/2001


CONSTRUCTOR:


/*Constructor: constructor is member function is used for initialized
               data memeber of a class when object is created.

  Constructor: 1.no return type
               2.used for initialized data members
               3.class name and constructor (function) name same
               4.when object is created then constructor automatically called

Types of constructor:
       1. default
       2. parametrized
       3. copy
       4. empty
       5. dynamic
 */

//default constructor-
#include<iostream>
using namespace std;

class data
{
  private:
         int a,b;
  public:
         data()
         {
            a=0;
            b=0;
            cout<<"\n Constructor is called..";
         }
         void put()
         {
            cout<<"\n a:"<<a<<"\n b:"<<b;
         }
};
int main()
{
    data d1,d2,d3;        
    d1.put();
}



OUTPUT:


 Constructor is called..

 Constructor is called..

 Constructor is called..

 a:0

 b:0



//parameterized constructor-
#include<iostream>
using namespace std;

class data
{
  private:
         int a,b;
  public:
         data(int a1,int b1)
         {
            a=a1;
            b=b1;
            cout<<"\n Constructor is called..";
         }
         void put()
         {
            cout<<"\n a:"<<a<<"\n b:"<<b;
         }
};
int main()
{
    data d1(22,33),d2(50,80);        
    d1.put();
    d2.put();
}


OUTPUT:


 Constructor is called..

 Constructor is called..

 a:22

 b:33

 a:50

 b:80



// Empty Constructor
#include<iostream>
using namespace std;

class data
{
  private:
          int a,b;
  public:
         data()
         {   }
};
int main()
{
    data d1;
}



NO OUTPUT



/*Copy constructor:
         copy constructor is member function that initializes an object
         using another object of the same class.
 */

#include<iostream>  
using namespace std;

class data
{
  private:
          int a,b;
  public:
         data()
         {  }
         data( data &obj)
          {
            a=obj.a;
            b=obj.b;
          }
         void get()
         {
            cout<<"\n Enter a:";
            cin>>a;
            cout<<"\n Enter b:";
            cin>>b;
         }
         void put()
         {
            cout<<"\n a:"<<a;
            cout<<"\n b:"<<b;
         }
};

int main()
{
    data d1;
    d1.get();
    d1.put();

    data d2=d1;
    d2.put();

    data d3(d1);
    d3.put();
}


OUTPUT:


 Enter a:50

 Enter b:80


 a:50

 b:80

 a:50

 b:80

 a:50

 b:80



/* dynamic constructor
 dynamic memory allocation  and deallocation in c++
    1. new    --> Allocation
    2. delete --> Deallocation
*/

#include<iostream>
using namespace std;
int main()
{
   int * ptr = new int;
   cout<<"\n Enter the integer number:";
   cin>>*ptr;
   cout<<"\n Interger:"<<*ptr;
   delete ptr;
   
}


OUTPUT:

Enter the integer number:50


 Interger:50


/*Destructor:
             -Constructor are overloaded
             -Destructor are not overloaded
*/
#include<iostream>
using namespace std;

class data
{
    private:
          int a;
    public:
          data()
          {
            cout<<"\n Constructor..";
          }
          ~data()
          {
            cout<<"\n Destructor..";
          }
};
int main()
{
    data d;
}
 


OUTPUT:

 Constructor..

 Destructor.. 



/* Function overloading
    - same function name,but different parameter.
*/

#include<iostream>
using namespace std;

class data
{
    public:
          void sum(int a, int b)
          {
            cout<<"\n Sum is :"<<a+b;
          }
          void sum(int a, int b, int c)
          {
            cout<<"\n Sum is :"<<a+b+c;
          }
          void sum(double a, double b)
          {
            cout<<"\n Sum is :"<<a+b;
          }
};

int main()
{
    data d;
    d.sum(5,8);
    d.sum(5,7,8);
    d.sum(5.0,8.8);
}



OUTPUT:

 Sum is :13  

 Sum is :20  

 Sum is :13.8



/* Function overloading:
     -In function overloading two or more functions can have same name ,
         but declaration or parameter is different..
     -compile time polymorphism
     -e.g. 1. add(int a, int b)
           2. add(double a, double b)
           3. add(int a, int b, int c)

  function overriding:
    -In function overriding same name and same function signature (parameter and their data types)
         in both base class and derived class with a different function defination.
    -Run time polymorphism
*/

//Constructor Overloading or Function overloading:

#include<iostream>
using namespace std;

class data
{
    private:
          int a;
    public:
          data()     // Constructor Overloading
          {
            a=0;
            cout<<"\n Default Constructor..";
          }

          data(int a)
          {
            this->a=a;        
            cout<<"\n Parameterized Constructor..";
          }
  /* when data member and local variable is same then compiler is confused,
     which a is local variable or which a is data member
     then we use this pointer..*/

          data(data &d1)
          {
            a=d1.a;
            cout<<"\n Copy Constructor..";
          }

          void put()
          {
            cout<<"\n a: "<<a;
          }
        ~data()
        {
          cout<<"\n here all objects are destroyed or freed...";
        }
};
int main()
{
    data d1,d2(100),d3(d2);
    d1.put();
    d2.put();
    d3.put();
}


OUTPUT:


 Default Constructor..

 Parameterized Constructor..

 Copy Constructor..

 a: 0

 a: 100

 a: 100

 here all objects are destroyed or freed...

 here all objects are destroyed or freed...

 here all objects are destroyed or freed...




/* Function overloading
    - same function name,but different parameter.
*/

#include<iostream>
using namespace std;

class data
{
    public:
          void sum(int a, int b)
          {
            cout<<"\n Sum is :"<<a+b;
          }
          void sum(int a, int b, int c)
          {
            cout<<"\n Sum is :"<<a+b+c;
          }
          void sum(double a, double b)
          {
            cout<<"\n Sum is :"<<a+b;
          }
};

int main()
{
    data d;
    d.sum(5,8);
    d.sum(5,7,8);
    d.sum(5.0,8.8);
}


OUTPUT:


 Sum is :13  

 Sum is :20  

 Sum is :13.8



/* this pointer:
   -this pointer is inbuilt pointer.
   -no need to declare.
   -it is a redimate pointer.
   -this pointer contain the reference address of currently used object.
   -this pointer is only used in member function.
   -this pointer is not used in non member function.
*/

#include<iostream>
using namespace std;

class data
{
  private:
         int a;
  public:
        void get()
         {
            cout<<"\n Enter a:";
            cin>>this->a;        //cin>>this->a; by default this pointer inbuilt  
         }
        void put()
        {
            cout<<"\n Address of a: "<<this;
            cout<<"\n a: "<<this->a;
        }
};

int main()
{
    data d1;
    cout<<"\n Address of d1: "<<&d1;
    d1.get();
    d1.put();

    data d2;
    cout<<"\n\n Address of d2: "<<&d2;
    d2.get();
    d2.put();
}


OUTPUT:


 Address of d1: 0x61ff0c

 Enter a:50


 Address of a: 0x61ff0c 

 a: 50


 Address of d2: 0x61ff08

 Enter a:80


 Address of a: 0x61ff08

 a: 80



/* operator overloading:
 - some operator are overloaded using only member function.
 - some operator are overloaded using only non - member function.
 - some overloaded by both member or non member function.
 - some operator not overloaded e.g. dot(.) operaotr,scop resolution(::)operator, arrow operator...
 - insertion(<<) operator,extraction(>>)operator only overloaded using friend function.
 - to overload any operator we have to write operator overloading.
 - 1.unary operator , 2.binary operator
 Example: +
         addition of 2 number
         addition of 2 string
         addition of 2 matrix
*/

#include<iostream>
using namespace std;

class data
{
 private:
         int a,b;
 public:
        data(int a1, int b1)
        {
          a = a1;
          b = b1;
        }
        void put()
        {
            cout<<"\n a: "<<a;
            cout<<"\n b: "<<b;
        }
        void operator ++()     //unary operator, member function
        {
          a = a+1;  //this->a = this->a+1;
          b = b+1;  //this->b = this->b+1;
        }

        // friend void operator ++(data &d)  //non member fun.
        // {
        //   d.a = d.a+1;
        //   d.b = d.b+1;
        // }
       
        ~data()
        {
            cout<<"\n object freed";
        }

};   //don't miss (;) semicolon here.

int main()
{
  data d1(100,200);
  d1.put();
  ++d1;
  d1.put();
}

/*
                         operator overloading
                                  |
             ------------------------------------------------
            |                                               |
          unary                                          binary
 (operator overloading fun.)                  (operator overloading fun.)
             |                                             |
     ------------------                          -------------------
    |                 |                         |                  |
member fun.     non-member fun.            member fun.       non-member fun.
   |                 |                         |                  |
no parameter   one parameter            one parameter         two parameter

*/







OUTPUT:


 a: 100      

 b: 200      

 a: 101      

 b: 201      

 object freed




/* Inheritance:
   - Inheritance is a mechanism of reusing and extending existing classes without modifying them,
      thus producing hierarchical relationships between them.
   - Inheritance is a reusability.
   - sharing the existing code.
 
 1. Single Inheritance :
   - Single inheritance allows a derived class (child class) to inherit the properties and behavior of a base class (parent class).
   - In Inheritance create the object of the child class,
       do not need create object of parent class.
   - child class is stronger than base class,
       becaz child class inherits the all properties of the base class,
       & add it's owns property so...
*/

#include<iostream>
using namespace std;

class data                          // parent class / base class
{
 // private:
  protected:
          int a,b;
  public:
         void get()
         {
            cout<<"\n Enter  a & b :";
            cin>>a>>b;
         }
         void put()
         {
            cout<<"\n a: "<<a<<"\n b: "<<b;
         }
};
   class operations : public data         // child class / derived class
   {
      private:
              int c;
      public:
             void add()
             {
                c = a+b;                       // here a & b are not access becaz they r private in base class,
                cout<<"\n addition is :"<<c;   //  so we need to make protected them to use in child class
             }
   };

int main()
{
    operations d1;        // create the object of child class..
    d1.get();
    d1.put();
    d1.add();
}



OUTPUT:



 Enter  a & b :50  80


 a: 50

 b: 80

 addition is :130





/*
Constructors and Destructors in multiple classes[Inheritance]
*/

#include<iostream>
using namespace std;

class base
{
public:
    base()
    {
    cout<<"\n This is Base class Constructor";
    }
    ~base()
    {
    cout<<"\n This is Base class Destructor";
    }
};
class derived:public base
{
public:
    derived()
    {
    cout<<"\n This is Derived class Constructor";
    }
    ~derived()
    {
    cout<<"\n This is Derived class Destructor";
    }
};

main()
{
derived obj;
}

/* OUTPUT:
This is Base class Constructor      
 This is Derived class Constructor    
 This is Derived class Destructor    
 This is Base class Destructor        
 */





/*
Constructors and Destructors in multiple classes[Inheritance]
*/

#include<iostream>
using namespace std;

class base1
{
public:
    base1()
    {
    cout<<"\n This is Base1 class Constructor";
    }
    ~base1()
    {
    cout<<"\n This is Base1 class Destructor";
    }
};
class base2
{
public:
    base2()
    {
    cout<<"\n This is Base2 class Constructor";
    }
    ~base2()
    {
    cout<<"\n This is Base2 class Destructor";
    }
};

class derived:public base2,public base1
{
public:
    derived()
    {
    cout<<"\n This is Derived class Constructor";
    }
    ~derived()
    {
    cout<<"\n This is Derived class Destructor";
    }
};

main()
{
derived obj;
}

/* OUTPUT:
This is Base2 class Constructor  
 This is Base1 class Constructor  
 This is Derived class Constructor
 This is Derived class Destructor  
 This is Base1 class Destructor  
 This is Base2 class Destructor    
 */





/*
Constructors and Destructors in multiple classes[Inheritance]
*/

#include<iostream>
using namespace std;

class base
{
private:
    int a,b;
public:
    base(int a1,int b1)
    {
    cout<<"\n This is Base class Constructor";
    a=a1;
    b=b1;
    }
    void put()
    {
    cout<<"\n a="<<a<<"\n b="<<b;
    }
    ~base()
    {
    cout<<"\n This is Base class Destructor";
    }
};
class derived:public base
{
private:
    int c,d;
public:
    derived(int a1, int b1, int c1, int d1):base(a1,b1)
    {
    c=c1;
    d=d1;
    cout<<"\n This is Derived class Constructor";
    }

/*  derived(int a1, int b1):base(a1,b1)
    {

    }
*/
    void put()
    {
    base::put();
    cout<<"\n c="<<c<<"\n d="<<d;
    }
   
    ~derived()
    {
    cout<<"\n This is Derived class Destructor";
    }
};

main()
{
derived obj(10,20,30,40);
obj.put();
}

/* OUTPUT:
This is Base class Constructor  
 This is Derived class Constructor
 a=10
 b=20
 c=30
 d=40
 This is Derived class Destructor
 This is Base class Destructor  
 */




/* Hirarchical Inheritance */
#include<iostream>
using namespace std;

class data
{
protected :
   int a,b;
public:
   void get()
   {
   cout<<"\n Enter a and b=";
   cin>>a>>b;
   }
   void put()
   {
   cout<<"\n a="<<a<<"\n b="<<b;
   }
};

class D1 : public data
{
public:
   void add()
   {
   cout<<"\n Addition="<<a+b;
   }
};

class D2:public data
{
public:
   void mul()
   {
   cout<<"\n Multiplication="<<a*b;
   }
};

main()
{
D1 d1;
D2 d2;
d1.get();
d1.add();
d2.get();
d2.mul();
}

/*OUTPUT:
 Enter a and b=50
 80

 Addition=130
 Enter a and b=5
 8

 Multiplication=40
 
 */




/* Hybrid Inheritance

   A    B
     C
     D
*/

#include<iostream>
using namespace std;

class A
{
protected:  
    int a;
public:
    A(int a1)
    {
    a=a1;
    }
};

class B
{
protected:  
    int b;
public:
    B(int b1)
    {
    b=b1;
    }
};
class C:public A, public B
{
public:
    C(int a1, int b1):A(a1),B(b1)
    {
    }
};
class D:public C
{
public:
    D(int a1, int b1):C(a1,b1)
    {
    }
    void put()
    {
    cout<<"\n a="<<a<<"\n b="<<b;
    }
};
main()
{
D obj(100,200);
obj.put();
}

/* OUTPUT:
 a=100
 b=200
 */



/* Demo of Multiple Inheritance */
#include<iostream>
using namespace std;

class pinfo
{
private:
    char name[20];
    char phone[12];
public:
    void get();
    void put();
};

class einfo
{
private:
    char degree[10];
    int per;
public:
    void get();
    void put();
};

class demo:public pinfo,public einfo
{
private:
    char post[10];
    int sal;
public:
    void get();
    void put();
};

void pinfo::get()
{
cout<<"\n Enter Name =";
cin>>name;
cout<<"\n Enter Phone Number=";
cin>>phone;
}
void pinfo::put()
{
cout<<"\n Name ="<<name<<"\n Phone Number="<<phone;
}

void einfo::get()
{
cout<<"\n Enter Degree =";
cin>>degree;
cout<<"\n Enter Per=";
cin>>per;
}
void einfo::put()
{
cout<<"\n Degree ="<<degree;
cout<<"\n Per    ="<<per;
}

void demo::get()
{
pinfo::get();
einfo::get();
cout<<"\n Enter Post =";
cin>>post;
cout<<"\n Enter Sal=";
cin>>sal;
}
void demo::put()
{
pinfo::put();
einfo::put();
cout<<"\n Post ="<<post;
cout<<"\n Sal  ="<<sal;
}

main()
{
demo d1;
d1.get();
d1.put();
}

/* OUTPUT
 Enter Name =Sunny

 Enter Phone Number=123

 Enter Degree =Bcs

 Enter Per=90

 Enter Post =Student

 Enter Sal=100000

 Name =Sunny
 Phone Number=123
 Degree =Bcs
 Per    =90
 Post =Student
 Sal  =100000  
 */




/* Demo of Multilevel Inheritance
        A
        |
        B
        |
        C
*/
#include<iostream>
using namespace std;
class A
{
protected:
    int a;
public :
    A(int a1)
    {
    a=a1;
    }
};

class B:public A
{
protected :
    int b;
public:
    B(int a1,int b1):A(a1)
    {
    b=b1;
    }
};
class C:public B
{
private:
    int c;
public:
    C(int a1, int b1):B(a1,b1)
    {

    }
    void add()
    {
    c=a+b;
    cout<<"\n Result="<<c;
    }
};

main()
{
C obj(100,200);
obj.add();
}

/* OUTPUT:
 Result=300
 */




/* Mutiple copies of Base class can be avoided by virtual base class

         A    
      B     C
     D  
*/

#include<iostream>
using namespace std;
class A
{
protected :
    int a;
public:
    A()
    {
    a=100;
    }
};

class B: virtual public A
{
};

class C: virtual public A
{
};

class D: public B, public C
{
public:
    void put()
    {
    cout<<"\n a="<<a;
    }
};
main()
{
D obj;
obj.put();
}

/* OUTPUT:
 a=100
 */




/*
-runtime polymorphism
-overriding
-virtual function
-pure virtual function
-abstract class
*/

#include<iostream>
using namespace std;
class A
{
public:
    virtual void put()
    {
    cout<<"\n Hi from A";
    }
    //  virtual void print()=0; --> pure virtual fun

    virtual void print()
    {
    }
};

class B: public A
{
public :
    void put()
    {
    cout<<"\n Hi from B";
    }
    void print()
    {
    cout<<"\n Print hi from B";
    }
};
main()
{
A *ptr;
A obj1;
B obj2;
ptr=&obj1;
ptr->put();
ptr=&obj2;
ptr->put();
ptr->print();
}

/*OUTPUT
Hi from A
 Hi from B
 Print hi from B
 
*/




format ios :

#include<iostream>
using namespace std;
main()
{
int a=10000;
float b=123545;
cout.width(10);
cout.fill('$');
cout<<a<<endl;
cout.setf(ios::floatfield,ios::fixed);
cout.precision(2);
cout<<b<<endl;
}

/*OUTPUT
$$$$$10000
123545.00
*/




#include<iostream>
#include<iomanip>
using namespace std;
main()
{
int a=10;
cout<<dec<<a<<endl;
cout<<hex<<a<<endl;
cout<<oct<<a<<endl;
cout<<setw(10)<<a<<endl;
cout<<setiosflags(ios::dec);
cout<<setiosflags(ios::left);
cout<<setw(10)<<setfill('*')<<a;

}

/*OUTPUT:
10
a
12
        12
10********
*/



// class Templates-

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

template <class T>
class data
{
private:
    T a[5];
public:
    void get()
    {
    int i;
    for(i=0;i<5;i++)
    cin>>a[i];
    }
    void put()
    {
     int i;
    for(i=0;i<5;i++)
    cout<<a[i]<<endl;
    }
};

main()
{
//data <int> d1;
//data <float> d1;
data <char> d1;
d1.get();
d1.put();
}


                  

function templates-

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

template <class T1,class T2>
T2 sum(T1 x, T2 y)
{
return(x+y);
}

main()
{
cout<<sum(12,2.3);
cout<<endl<<sum(1.2,23);
cout<<endl<<sum(12,23);
cout<<endl<<sum(1.2,2.3);
}

/*OUTPUT:
14.3
24  
35  
3.5
*/




#include<iostream>
using namespace std;
main()
{
int a,b,c;
cout<<"\n Enter Value of a & b =";
cin>>a>>b;
try
{
    if(b!=0)
    {
    c=a/b;
    cout<<"\n Result of Division="<<c;
    }
    else
    throw b;
}
catch(int b)
{
cout<<"\n b="<<b;
cout<<"\n Plz Enter b non-zero value";
}
}

/* OUTPUT:

 Enter Value of a & b =2  0
 b=0
 Plz Enter b non-zero value
 
 */




#include<iostream>
using namespace std;
main()
{
int i;
cout<<"\n Multiple Catch Block ";
try
{
cout<<"\n Enter Value of i =";
cin>>i;
if(i==1)
throw 10;
else if (i==2)
throw '*';
else if (i==3)
throw 1.3;
else if (i==4)
cout<<"\n Normal Execution";
}
catch(int c)
{
cout<<"\n Caught a int exception";
}
catch(char c)
{
cout<<"\n Caught a char exception";
}
catch(double c)
{
cout<<"\n Caught a double exception";
}
catch(...)
{
cout<<"\n Caught a all exception";
}
}

/* OUTPUT:
Multiple Catch Block
 Enter Value of i =3

 Caught a double exception
 */




#include<iostream>
using namespace std;
main()
{
int i;
cout<<"\n Multiple Catch Block ";
try
{
cout<<"\n Enter Value of i =";
cin>>i;
if(i==1)
throw 10;
else if (i==2)
throw '*';
else if (i==3)
throw 1.3;
else if (i==4)
cout<<"\n Normal Execution";
}
catch(...)
{
cout<<"\n Caught a all exception";
}
}

/*OUTPUT:
Multiple Catch Block
 Enter Value of i =1  

 Caught a all exception
 */






#include <fstream>
#include <iostream>
using namespace std;
 
int main ()
{
   char data[100];

   // open a file in write mode.
   ofstream outfile("afile.dat");
   //outfile.open("afile.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: ";
   cin.getline(data, 100);

   // write inputted data into the file.
   outfile << data << endl;

   cout << "Enter your age: ";
   cin >> data;
   cin.ignore();
   
   // again write inputted data into the file.
   outfile << data << endl;

   // close the opened file.
   outfile.close();

   // open a file in read mode.
   ifstream infile;
   infile.open("afile.dat");
 
   cout << "Reading from the file" << endl;
   infile >> data;

   // write the data at the screen.
   cout << data << endl;
   
   // again read the data from the file and display it.
   infile >> data;
   cout << data << endl;

   // close the opened file.
   infile.close();

   return 0;
}


/*OUTPUT:
Writing to the file
Enter your name: Swpanil
Enter your age: 22
Reading from the file
Swpanil
22
*/



/*
File Pointer
get pointer ==> read mode ==> tellg() seekg()
put pointer ==> write mode ==> tellp() seekp()
*/

#include<fstream>
#include<iostream>
using namespace std;
class stud
{
private:
    int rno;
    char name[20];
public:
    void get()
    {
    cout<<"\n Enter Rno =";
    cin>>rno;  
    cout<<"\n Enter Name =";
    cin>>name;
    }
    void put()
    {
    cout<<"\n Rno ="<<rno;
    cout<<"\n Name ="<<name;
    }
};
main()
{
stud s;
ifstream file1;
file1.open("stud.dat",ios::in|ios::ate);
cout<<"\n Size of Record="<<sizeof(s);
cout<<endl<<file1.tellg();
file1.seekg(-24,ios::end);
cout<<endl<<file1.tellg();
file1.read((char*)&s,sizeof(s));
cout<<endl<<file1.tellg();
s.put();
file1.seekg(-48,ios::end);
file1.read((char*)&s,sizeof(s));
s.put();
file1.close();
}





#include<fstream>
#include<iostream>
using namespace std;
class stud
{
private:
    int rno;
    char name[20];
public:
    void get()
    {
    cout<<"\n Enter Rno =";
    cin>>rno;  
    cout<<"\n Enter Name =";
    cin>>name;
    }
    void put()
    {
    cout<<"\n Rno ="<<rno;
    cout<<"\n Name ="<<name;
    }
};
main()
{
ofstream file;
stud s;
int i,n;
cout<<"\n NO of Students=";
cin>>n;
file.open("stud.dat",ios::out|ios::app);
for(i=1;i<=n;i++)
{
s.get();
file.write((char*)&s,sizeof(s));
}
file.close();

ifstream file1;
file1.open("stud.dat",ios::in);
for(i=1;i<=n;i++)
{
file1.read((char*)&s,sizeof(s));
s.put();
}
file1.close();
}

/*OUTPUT:
 NO of Students=3

 Enter Rno =50

 Enter Name =Swapnil

 Enter Rno =80

 Enter Name =Sunny

 Enter Rno =141

 Enter Name =Omkar

 Rno =50      
 Name =Swapnil
 Rno =80      
 Name =Sunny  
 Rno =141    
 Name =Omkar
 */

             





                                  End

Comments

Post a Comment

hey

Popular posts from this blog

Practical slips programs : Machine Learning

Full Stack Developement Practical Slips Programs

Android App Developement Practicals Programs