Thursday, 21 September 2017

C++ program to create, write and read from data file using class fstream

/*
 C++ program to create, write and read from data file using class fstream
*/

#include "iostream"
#include "fstream" // required 
using namespace std;

int main(){
 /* Block to write to file */
 fstream fileOb;
 fileOb.open("MyFile", ios::out | ios::in); 
 if(fileOb.is_open()){
  cout<<"\nSuccess .."<<endl;
  fileOb<<"First Line added to file. \n"; // operator << have been overloaded for putting contents into file
  fileOb<<"Second line added. \n"; 
  fileOb<<"Third line added. \n"; 
 
  //fileOb.close();  // close the file
 }else{
  cout<<"\nFile creation and opening failed .. "<<endl;
 }

C++ program to add user defined contents to file and to read the file later

/*
 C++ program to add user defined contents to file and to read the file later
*/

#include "iostream"
#include "fstream" // required 
using namespace std;

int main(){
 /* Block to write user-defined contents to file */
 int count, age;
 string name;
 ofstream outFile;
 outFile.open("MyFile", ios::out); // writing ios::out is optional as object used is outFile
 if(outFile.is_open()){
  cout<<"\nSuccess .."<<endl;
  cout<<"\nHow many entries do you wish to add to file: ";
  cin>>count;
  for(int i=0; i<count; i++){
   cout<<"\nEnter name: ";
   cin>>name;
   cout<<"\nEnter age: ";
   cin>>age;
   
   outFile<<name<<"\t"<<age<<endl;  // adding contents to file
  }
 

C++ program to create, write and read from data file

/*
 C++ program to create, write and read from data file
*/

#include "iostream"
#include "fstream" // required 
using namespace std;

int main(){
 /* Block to write to file */
 ofstream outFile;
 outFile.open("MyFile", ios::out); // writing ios::out is optional as object used is outFile
 if(outFile.is_open()){
  cout<<"\nSuccess .."<<endl;
  outFile<<"First Line added to file. \n"; // operator << have been overloaded for putting contents into file
  outFile<<"Second line even added. \n"; 
 
  outFile.close();  // close the file
 }else{
  cout<<"\nFile creation and opening failed .. "<<endl;
 }

Class templates having single level inheritance in C++

/*
 Class templates having single level inheritance 
*/
#include "iostream"
using namespace std;

template <class T>
class First{
 T x;
 public:
  void getFirst(T a){
   x = a;
  }
  void showFirst(){
   cout<<"\nx: "<<x<<endl;
  }
};

template <class T2>
class Second: public First<T2>{
 T2 y, z;
 public:
  Second(T2 m, T2 n){
   y = m;
   z = n;
  }
  void showAll(){
//   display();
   cout<<"\ny: "<<y<<"\tz: "<<z<<endl;
  }
};

Class template having function template definition outside class in C++

/*
 Class template having function template definition
 Note: If you write showData() definition outside class in normal way, means without template
 then age and name wont be accessible. thats the reason showData() is defined inside.
*/
#include "iostream"
using namespace std;

template <class T1, class T2>
class Person{
 T1 age;
 T2 name;
 public:
  void getData();
  void showData(){
   cout<<"\nage: "<<age<<"\tname: "<<name<<endl;
  }
};
template <class T1, class T2> void Person<T1,T2>:: getData(){
 cin>>age>>name;
}

Simple class template having simple function template in C++

/*
 Simple class template having simple function template
*/
#include "iostream"
using namespace std;

template <class T>
class Person{
 T age;
 public:
 void getData(T a){
  age = a;
 }
 T showData();
};

Class template having default and parameterized constructors in C++

/*
 Class template having default and parameterized constructors
*/

#include "iostream"
using namespace std;

template <typename T1, class T2>
class Person{
 T1 age;
 T2 name;
 public:
  Person(){
   age = 32; 
   name = "Pavan";
  }
  Person(T1 x, T2 y){
   age = x;
   name = y;
  }
 
  void display(){
   cout<<"\nAge: "<<age<<"\tname: "<<name<<endl;
  }
};

Class template in C++ to accept and display person details

/*
 Class template which have data members of different types
*/

#include "iostream"
using namespace std;

template <class T1, typename T2>
class Person{
 T1 age;
 T2 name;
 public:
  void getData(){
   cout<<"\nEnter age & name ";
   cin>>age>>name;
  }
 
  void showData(){
   cout<<"\nage: "<<age<<"\tname: "<<name<<endl;
  }
};

Function template with two generic types in C++

/*
 Function template with two generic types
*/

#include "iostream"
using namespace std;

template <class T1, class T2>
void display(T1 xx, T2 yy){
 cout<<endl<<xx<<" "<<yy;
}

Function template to swap two numbers in C++

/*
 Demonstrating function template
*/

#include "iostream"
using namespace std;

template <class T>
void swaparg(T &a, T &b){
 T temp;
 temp = a;
 a = b;
 b = temp;
}

Function template to check max numebr in C++

/*
 Function template demo to check max number in c++ 
*/
#include "iostream"
using namespace std;

template <typename T>
T getMax(T x, T y){
 return (x>y?x:y);
}

int main(){
 cout<<"Max No: "<< getMax <int> (4,5)<<endl;
 return 0;
}
/*
 OUTPUT
[pavan@localhost Template]$ g++ FunctionTemplate.cpp
[pavan@localhost Template]$ ./a.out 
Max No: 5
[pavan@localhost Template]$ 

*/

Smart pointer in C++

/*
 Smart pointer demonstration
 -- smart pointer as name suggest works smart. 
 -- In case of normal pointer, delete is expected to be called explicitley. 
 -- In case pf smart pointer, destruction happens automatically even though some exception occurs 
*/

#include "iostream"
using namespace std;

class Person{
 int age;
 char *name;

 public:
  Person():age(0),name(0){
  }

  Person(int age, char* name):age(age), name(name){

  }
  ~Person(){ }
 
  void display(){
   cout<<"\nAge: "<<age<<"\t"<<name<<endl;
  }
};

New and delete in C++

/*
 New Delete Demo in C++
*/
#include "iostream"
#include <new> // Some time you may have to include this file

using namespace std;

int main(){
 int *var = new int(10); //allocating single block of memory and initializing there only
 cout<<"\nVar: "<<*var;
 *var = 50;
 cout<<"\nVar: "<<*var;
 cout<<endl;

Pointer to obejct with dynamic memory allocation in C++

/*
 Pointer to object with dynamic memory allocation
*/
#include "iostream"
using namespace std;

class Box{
 public: 
  Box(){
   cout<<"\nConstructor called..";
  }
  ~Box(){
   cout<<"\nDestructor called.."<<endl;
  }
};

Array of pointers to charecter in C++

/*
 Array of poniters to character
*/

#include "iostream"
using namespace std;
const int MAX=3;

int main(){
 char *name[MAX] = {
  "Pavan",
  "Jaiswal",
  "Pune" };
 cout<<"\n Printing character array elements \n";
 for(int i=0; i<MAX; i++){
  cout<<" "<<name[i]; // *name[i] prints first character of each string, say P J P
 }
 cout<<endl;
 return 0;
}

Array of pointers in C++

/*
 Array of pointers in C++
*/
#include "iostream"
using namespace std;
const int MAX=3;

int main(){
 int var[MAX] = {10,20,30};
 int *ptr[MAX];
 
 cout<<"\nPrinting Array elements \n";
 for(int i=0; i<MAX; i++)
  cout<<" "<<var[i];
 cout<<endl;

Function pointer used to do bubble sort in C++

/*
 Function Pointer used for bubble sort
*/

#include "iostream"
using namespace std;

int compare(int i, int j){
 if(i>j) return 1;
 else return -1;

}

Basic demo of function pointer for callback purpose in C++

/*
    Basic demo of function pointer for callback purpose
*/

#include "iostream"
using namespace std;

void meaningOfLife(){
    cout<<"\nHi"<<endl;
}

void printANumber(int num, void (*ptr)()){
    cout<<"\nnum: "<<num;
    (*ptr)(); // simply ptr();

}

Function pointer in C++

/*
 Demonstrating function pointer that takes two int args and return back int value
*/

#include "iostream"
using namespace std;

void printHello(){

 cout<<endl<<"Hello All"<<endl;
}

Add and display data to array using pointer notation

/*
 Insert and display data entered using pointer notation
*/

#include "iostream"
using namespace std;

int main(){
 int arr[5];
 
 cout<<"\nEnter 5 elements \n";
 for(int i=0; i<5; i++){
  cin>>*(arr+i);
 }

 cout<<"\n\nPrinting Array elements";
 for(int i=0; i<5; i++){
  cout<<"\n"<<*(arr+i);
 }

Using array and pointers to print memory addresses in C++

/*
 Using Array and Pointer to print memory addresses in C++
*/

#include "iostream"
using namespace std;

int main(){
 int arr[5];
 int *ptr;
 
 
 cout<<"\nPrinting array addresses \n";
 for(int i=0; i<5; i++){
  cout<<"\n"<<&arr[i];
 }

Returning pointer from function in C++

/*
 Demo of returning pointer from function in C++
*/
#include "iostream"
using namespace std;

int globalN = 20;


int *returnPointerFromFun(){

 return &globalN;
}

Pointer to pointer demo in C++

/*
 Pointer to Pointer Demo in C++
*/

#include "iostream"
using namespace std;

int globalN=20;

void pointerToPointer(int **newp){
 *newp = &globalN;
}

Pointer demo in C++

/*
 Pointer Demo in C++
*/

#include "iostream"
using namespace std;
const int MAX=3;

int main(){
 int var[MAX] = {10,100,200};
 int *ptr = var; // or even you can write int *ptr = &var[0], but not just var[0] or &var
 cout<<"\nPrinting elements in ascending order"<<endl;
 for(int i=0; i<MAX; i++){
  cout<<*(ptr)<<endl; // printing elements in ascending order
  ptr++;
 /*
  or else below 
  cout<<*(ptr+i)<<endl;
  no need to write ptr++ then
 */
 }

Array of pointers in C++

/*
 Array of pointer in c++
*/

#include "iostream"
using namespace std;
const int MAX=3;

int main(){
 int var[MAX] = {10,100,200};
 int *ptr[MAX];
 cout<"\nPrinting array elements";
 for(int i=0; i<MAX; i++){
  cout<<var[i]<<endl;
 }
 

Virtual function demo in C++

/*
 Virtual function demo in C++
*/

#include "iostream"
using namespace std;

class Base{
 public: 
  virtual void show(){
   cout<<"\nIn Base";
  }
};

Function overriding demo in C++

/*
 Function overriding demo in C++
*/

#include "iostream"
using namespace std;

class Base{
 public: 
  void show(){
   cout<<"\nIn Base";
  }
};

New and delete operator in C++

/*
 New and delete operator in C++
*/

#include "iostream"
using namespace std;

int main(){

 int *p=new int;
 *p = 10;
 cout<<"\n*p: "<<*p;

 float *q = new float;
 *q = 20.05;
 cout<<"\n*q: "<<*q;
 int n=3;
 cout<<endl;
 int *r = new int[n] ;
 for(int i=0; i<n; i++){
  q[i] = i+1;
  cout<<q[i]<<endl;
 }
}
/*
 OUTPUT
[pavan@localhost Unit-2-Inheritance]$ g++ NewDelete.cpp
[pavan@localhost Unit-2-Inheritance]$ ./a.out 

*p: 10
*q: 20.05
1
2
3
[pavan@localhost Unit-2-Inheritance]$ 
*/

Multilevel inheritance in C++

/*
 Title: Example to demonstrate multilevel inheritance in C++
*/

#include "iostream"
using namespace std;

class Student{
 protected :
  int rollno;
  string name;
 public:
  void setStudentData(int rno, string sname){ 
   rollno = rno; name=sname;
  }
  void getStudentData(){
   cout<<"\nRollNo: "<<rollno<<"\tName: "<<name;
  }
};

Derive class inheriting from private base class C++ program of single level inheritance

/*
Title: Derive class inheriting from private base class
 Derive class inherits all members of base class except constructor and destructor
 Even though private members are inherited but cant be accessed directly into derive class
*/

#include "iostream"
using namespace std;

class PrivateDemo{
 string name;
 public: 
  PrivateDemo(){
   name = "Pavan";
   cout<<"\nBase Constructor";
  }
  void setName(){
   cout<<"\nEnter Name: ";
   cin>>name;
   cout<<"\nYou have entered: "<<name<<endl;
  }

};

Single level inheritance demo in C++

/*
 Single Level Inheritance Demo in c++ to calculate are of rectangle
*/
#include "iostream"
using namespace std;

class Shape{

 protected :
  int height, width;
 public:
  void setWidth(int ht){
   height = ht;
  }
  void setHeight(int wt){
   width = wt;
  }
};

Creating user defined namespace in C++

/*
 Creating user defined namespace in C++
*/
#include "iostream"

namespace first{

 int num1, num2;
 class Student{
  int marks;
  public:
   Student(int num1){
    marks = num1;
    std::cout<<"marks: "<<marks<<std::endl;
   }
 };
}

C++ program to demonstrate the use of static variable

/*
 C++ program to demonstrate the use of static variable 
*/
#include "iostream"
using namespace std;

int num;
void myfunc();

int main(){

 num = 10;
 cout<<"Num in main: "<<num;
 myfunc();
 myfunc();
 cout<<"\n Num at the end: "<<num; 
 return 0;
}

C++ program to demonstrate use of local and global variable

/*
 C++ program to demonstrate use of local and global variable
*/
#include "iostream"
using namespace std;

int num;
void myfunc();

int main(){

 num = 10;
 cout<<"Num in main: "<<num;
 myfunc();
 myfunc();
 cout<<"\n Num at the end: "<<num; 
 return 0;
}