Wednesday, October 31, 2012

What is Template

Template helps us to create the generic functions and classes. In the generic function or class, the type of data upon which the function or class operates and specified as a parameters.

//Function Template
#include <iostream>
using namespace std;

template <class T>
T GetMax (T a, T b)
{
    T result;
    result = (a>b)?a:b ;
    return (result);
}


int main()
{
    int i = 5, j = 6, k;
    long l = 10, m = 5, n;

    k = GetMax<int>(i,j);
    n = GetMax<long>(l,m);

   
    cout << k << endl;
    cout << n << endl;
}

OUTOUT:
6
10 

int x, y;
GetMax <int> (x,y);
when the compiler encounters this call to a template function, it uses the template to automatically generate a function replacing each appereance of mytype by the type passed as the actual template parameter (int in this case) and then calls it. this process is automatically performed by the compiler and is invisible to the programmer.
______________________________________________________________________

// function Template 2
#include <iostream>
using namespace std;

template <class T>
T GetMax(T a, T b)
{
    T result;
    result = (a>b)?a:b ;
    return (result);
}

int main()
{
    int i = 5, j = 6, k;
    long l = 10, m = 5, n;
    k = GetMax(i,j);
    n = GetMax(l,m);
         //Notice here we don't declare the type
   
    cout << k << endl;
    cout << n << endl;
}

OUTOUT:
6
10

Notice how in this case, we called our function template Getmax() without explicitly specifying the type between angle-brackets <>. The compiler automatically determine what type is needed on each call.  

Tuesday, October 30, 2012

What is Encapsulation

Notes from my guru Sandeep Karan sir.

Encapsulation [A information(data or implementation) hiding mechanism]

capsule means in plain english

  1. A structure that encloses a body part (function or class)
  2. A small container

Encapsulation is a process of binding data members (variables, properties) and member functions (methods, operation) into a single unit”. eg. Function And Class is the best example of encapsulation.

Encapsulation is a process of hiding all the internal details of an object(real entity, not class ka object) from the outside world.

The ultimate goal of Encapsulation is to achieve SIMPLICITY in our code.
__________________________________________________________________________
In “Students” Example let's Implement Encapsulation.
class Students          //No matter there is union or struct 

{
   public double totalMarks;              //data, variable or attribute
   public double MarksScored;

   
   public double GetPercentageMarks()      //operation
   {
       double Percentage =(MarksScored /totalMarks) * 100;
       return Percentage;
   }

}

Students ComputerStd = new Students(); 

In above code we have encapsulated totalMarks, MarksScored and method GetPercentageMarks. While creating a “ComputerStd” object, the implementation of GetPercentageMarks will not be shown.

________________________________________________________________________

Encapsulation
help us to achieve a rule of software enginerring called simplicity (and by simplicity we achieve maintainability & security)

  • encapsulation is achieved by class, function, delegate, property.
________________________________________________________________________
Function is also example of Encapsulation

void add()
{
    int a = 4;
    int b = 5;          //data, variable or attribute
    int  c;

    c =  a + b;       //operation

    cout << "Addtion of 2 no is: " << c;
}   
________________________________________________________________________


Advance definition:
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. 
                                                        OR
In other words, encapsulation is the ability of an object to be a container (or capsule) for related properties (ie. data variables) and methods (ie. functions).             
                                                                                     OR
Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation                                                            (contractual--Relating to or part of a binding legal agreement)
==========================================================

Through encapsulation a class can hide the internal details of how an object does something. Encapsulation solves the problem at the implementation level.
      
    A class or structure can specify how accessible each of its members (variables, properties, and methods) is to code outside of the class or structure. Encapsulation simplifies the interaction between objects. An object can use another object without knowing all its data or how its data is maintained. For example, a Client object might have name, address, company, and department properties. If a Bank object wants to use a Client object, it can request the name and address for the bank without needing to know the company and department details of the Client object.
 
    With the help of encapsulation, a class can change the internal implementation without hurting the overall functionality of the system. Encapsulation protects abstraction.
_________________________________________________________________________
class Counter
{
    private int Count;

    public Counter()
    {
        Count = 0;
    }

    public void setCount( int newVal )
    {
        Count = newVal;
    }

    public int getCount()
    {
        return Count;
    }
}

This piece of code is also encapsulated, showing that you can have encapsulation without data hiding, but you cannot have data hiding without encapsulation.
____________________________________________________________________________ 
Now consider the function Substring() which returns the string based on the start index and length. The underlying algorithm and the internal data structures used to find the substring is specific to the String class and hidden from the external code who makes use of Substring() in which case the external code does not have previliges to modify the algorithm or the datastructures which are internal to (or encapsulated in) String class. This is known as encapsulation.
____________________________________________________________________________ 

Links to understand encapsulation: 

Tuesday, October 23, 2012

How to install GCC 4.7.2 in ubuntu 12.04 for c++11

Ubuntu 12.04 comes with GCC compiler for C language only (not for c++).
First check which version of GCC ubuntu already installed. If it is <4.7.2 then proceed.
  • gcc is used to compile C program
  • g++ is used to compile C++ program
  1. gcc -v (to check the gcc version)
  2. g++ -v (to check the g++ version)
  3. sudo apt-get update
  4. sudo apt-get install build-essential (to install g++ & some other other stuff)
  5. sudo apt-get update
  6. g++ -v (now check g++ is installed)

(Now add source from which we get GCC latest stable version)
  1. sudo add-apt-repository ppa:ubuntu-toolchain-r/test
  2. sudo apt-get update
  3. sudo apt-get install gcc-4.7
  4. sudo apt-get install g++-4.7
  • ls -lh /usr/bin/g++*

Install Alternatives(remember the version of gcc/g++):
  1. sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 10
  2. sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 20
  1. sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 10
  2. sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.7 20
  1. sudo update-alternatives --install /usr/bin/cc cc /usr/bin/gcc 30 (avoid the warning)
  2. sudo update-alternatives --set cc /usr/bin/gcc
  1. sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++ 30
  2. sudo update-alternatives --set c++ /usr/bin/g++
  • gcc -v
  • g++ -v (conform that you successfully installed the GCC)

configuring the default commands for gcc, g++:
  1. sudo update-alternatives --config gcc
  2. sudo update-alternatives --config g++
Source:
  1. Repository
  2. Nice detailed explanation
  3. Install Alternatives

Famous Links by Sandeep Karan ser

Sunday, October 21, 2012

Setter & Getter in c++

  1. A property, is a special sort of class member; or intermediate between a field (or data member) and a method.
  2. Properties are read and written like fields, but property reads and writes are (usually) translated to get and set method calls.
  3. Property allows us data validation.

That is, properties are intermediate between member code (methods) and member data  (instance variables) of the class, and properties provide a higher level of encapsulation than public fields.

//property in c++

#include <iostream>
using namespace std;

class student
{
    public:
        void setName(string x)
        {
            name = x;
        }
        string getName()
        {
            return name;
        }
       
    private:
        string name;
};

int main()
{
    student bio_stud;


    bio_stud.setName("sir Virender");
    cout << bio_stud.getName();   
}


OUTPUT:
sir Virender


NOTE:
  1. C++ does not have first class properties, but there exist several ways to emulate properties to a limited degree.
  2. C++ require the programmer to define a pair of accessor and mutator methods.  
Further reading property and indexer in cpp

Wednesday, October 17, 2012

What is the retrun-type of printf

About printf:    
printf is the formatted print routine that comes as part of the standard C library. the first argument to print is a format string. it describes how any remaining argument are to be printed. The charater % begins a print specification for an argument. In our program, %d told printf to interpret and print the next argument as a decimal number. printf can also output literal characters. In our program, we "printed" a newline character by giving its name (\n) in the format string. 
-----------------------------------------------------------------------------------------------
#include <stdio.h>

int main()
{
    int a = 57;
    printf ("\n");
   
    //What is the output of this

    printf ("%d ");    // This gives garbage value
    printf ("\n\n");    //this is used only to get clear output
   
    //What is the output of this
    printf ("%d",printf("%d",56));  //without space
    printf ("\n\n");
   
    //What is the output of this

    printf ("%d",printf("%d ",56));
    printf ("\n\n");
   
    //What is the output of this
    printf ("%d",printf("%d ",a));
    printf ("\n\n");
   
    //What is the output of this
    printf("%d ",printf("%d ",printf("%d ",56))); //that's very interesting
    printf ("\n\n");
   
    //What is the output of this
    printf ("%d \t %d ",58, a);               // 'space' -->takes 1 character
    printf ("\n\n");
   
    //What is the output of this
    printf("%d",printf ("%d \t %d ",58, a));  // \t -->takes 1 character
    printf ("\n\n");
   
    //What is the output of this
    printf("%d",printf ("%d\n\t %d ",a,59));  // \n -->takes 1 character
    printf ("\n");
   
    return 0;
}


OUTPUT:

Program to understand STATIC variable

Static is multipurpose keyword, we can use static in context of variable, function and classes.
Here we discuss about the static variable.
__________________________________________________________________
//In this program we are not using static variable 
 #include<stdio.h>
#include<conio.h>

void show()
{
    int i=0;          //Note, we are not declaring 'i' as a static variable here
    i++;               //variable 'i' increased by 1


    printf("output is %d\n" ,i);
}

void main()
{
    show();            //here we are calling show 3 times
    show();
    show();
}


output:
       output is 1
       output is 1

       output is 1

You can see that  output is 1, although we are calling show function 3 time.
That because the variable i not retaining the value.

  •  So to retain the value we use this variable as a static variable. (see next program)
  •  Static variable is useful when we want to count the no of attempt performed by the client. (see last program)
__________________________________________________________________
//using STATIC variable
#include<stdio.h>
#include<conio.h>

int show()
{
    static int i=0;            //here we use static variable
             i++;
             printf("output is %d\n" ,i);
}

void main()
{
    show();
    show();
    show();
}

output:
          output is 1
          output is 2
          output is 3

__________________________________________________________________
//In this program we want that user have only 4 chance to enter right password
#include<iostream>
#include<string>
#include<stdlib.h>              //for exit(0);
using namespace std;

int show()
{
     static int i=0;            //here we use static variable
           // int i=0;


    
string password;           
     i++;
                      
            if(i<=3)
            {
                cout << "\nenter your password: ";
                cin >> password;
               
                if (password == "foobar")
                    {
                        cout << "\nwelcome you log in!\n";
                        exit(0);
                    }
            }
  
            else
            {
                cout << "recover your password";
            }
           
}

int main()
{
    show();              //here we can use the loop also
    show();
    show();
    show();
}

Tuesday, October 16, 2012

Difference and making of namespace in c++ and c#

//How to write a program for namespace in visual c++

#include"StdAfx.h"
#include<iostream>
using namespace std;

namespace uptu
{
    class abes
    {
        private:
            int x;
           
        public:
          void assign() {
            x=100;
          }
         
          void show() {
            cout<<x; 
          }
    };
   
    class akeg
    {
        private:
            int x;
           
        public:
            void assign() {
                x=121;
            }
           
            void show() {
                cout<<x;
            }
    };
}

int  main()

    {
        uptu::abes a;
        a.assign();
       
        uptu::akeg b;
        b.assign();
        b.show();

        return 0;
    }
___________________________________________________________________
 // namespace in csharp
// must be added at beginning


using System;
using y=india.uptu;

namespace india
{
    namespace uptu
    {
        public class abes
        {
            public void show()
            {
                Console.WriteLine("This is alias");
            }
 
            public static void Main()
            {
                y.abes a=new y.abes();
                a.show();
            }
        }
    }
}

Monday, October 15, 2012

Advantages and disadvantages of inline function in c++

The purpose of inline functions is to insert the code of a called function at the point where the function is called.It can improve the application's performance but not always.If you have two or three statements then it works otherwise compiler will ignore inline keyword.

    We put inline keyword in front of a function which requests a compiler to make that function as inline function. When we call an inline function, it expands (similar to macro) itself and skipped from actual function call as in case of normal functions happen. Let’s take a small example.


inline int minimum (int x, int y)
{
      return x < y ? x: y;
}

int main()
{
      cout << “minimum of 50 and 70 is” << minimum (50, 70);
      return 0;
}

As we put inline keyword so the function is expanded like below at the time of invocation.

int main()
{
      cout <<“minimum of 50 and 70 is” << (50 < 70? 50: 70;
      return 0;
}

Pros:

1. It increases performance.
2. It is better than macros because it does type checking.

Cons:

1. Compiler often generates a lot of low level code to implement inline functions.
2. It is necessary to write definition for an inline function (compared to normal function) in every module (compilation unit) that uses it otherwise it is not possible to compile a single module independently of all other modules.
3. If we use many inline functions then executable size will also be increased.
4. Little bit it breaks encapsulation because it exposes the internal of the objects






Thursday, October 11, 2012

What is a CLASS

class is a keyword or mechanism which used to create user-defined datatype or we can say that a comprehensive.
  • data type, which represents a blue-print of objects.
  • A class is like a template.
A class is composed of a set of data members and a set of operations that can be performed on the data.
A class defines the characteristics of an object.
characteristics include: 
1. Attributes                                     |car
   (data fields --> properties)             |[year, make, model, color, numbers of doors, engine] 

2. behaviors                                     |
   (
operation --> methods or fun.)        |[on(), off(), changes(), accelerate(), turn(), break()]


Note: Here, Properties means characteristic of  object or entity (thing).

         Don't get confused Property which is a concept in oops.
______________________________________________________________________
          public class Students
          {

               /*--code------*/
          }
          Students BiologyStd  = new Students();
          Students ComputerStd = new Students(); 


In our above example “Students” is a Class
which has objects “Biology Students” &  “Computer Students”.
_____________________________________________________________________
Note: class in c# by default reference type while in c++ it is valued type.



A class is composed of a set of data members and a set of operations that can be performed on the data.
Class rectangle

{

      private:                     |  //we can use private, public and protected,  (internal in c#)

                  int x;               |  set of data member

                  int y;                |  //data members are private by default



        public:                                           | this is set of operation
                 void set_values (int, int);   | //1st function (only declaration)
                 int area ()                             | //2nd function (with definition)
                 {                                             | //function must be public
                      return (x*y);                     |
                 }                                             |
};

In C++, a class type can be declared with the keywords union, struct, or class.

·         The members of a class declared with the keyword class are private by default. A class is inherited privately by default.
·      The members of a class declared with the keyword struct are public by default. A structure is inherited publicly by default.
·      The members of a union (declared with the keyword union) are public by default. A union cannot be used as a base class in derivation.
__________________________________________________________________________________
class X
{
     /* define class members here */
};
int main()
{
      X xobject1;       // create an object of class type X
      X xobject2;       // create another object of class type X
}
You may have polymorphic classes in C++. Polymorphism is the ability to use a function name that appears in different classes (related by inheritance), without knowing exactly the class the function belongs to, at compile time.

concepts related to C++ Classes and Objects, discuss below
Concept
Description
Class member functions
A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.
Class access modifiers
A class member can be defined as public, private or protected. By default members would be assumed as private.
Constructor & destructor
A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.
C++ copy constructor
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
C++ friend functions
A friend function is permitted full access to private and protected members of a class.
C++ inline functions
With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function.
The this pointer in C++
Every object has a special pointer this which points to the object itself.
Pointer to C++ classes
A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.
Static members of a class
Both data members and function members of a class can be declared as static.

·         Classes not only include information regarding the real world object, but also functions to access the data, and classes possess the ability to inherit from other classes.
·         A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.
·         An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
·         Remember : A class is a type, and an object of this class is just a variable.

Classes are generally declared using the keyword class, with the following format:
class class_name {
  access_specifier_1:    //please notice : these colon
    member1;
  access_specifier_2:
    member2;
  ...
  } object_names;

Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.

All is very similar to the declaration on data structures, except that we can now include also functions and members, but also this new thing called access specifier. An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them acquire:
·      private members of a class are accessible only from within other members of the same class or from their friends.
·      protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.
·      Finally, public members are accessible from anywhere where the object is visible.








class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area (void);
  } rect;
Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of this class called rect. This class contains four members: two data members of type int (member x and member y) with private access (because private is the default access level) and two member functions with public access: set_values() and area(), of which for now we have only included their declaration, not their definition.

// classes example
#include <iostream>
using namespace std;

class CRectangle {
    int x, y;
  public:
    void set_values (int,int);  //prototype
    int area ()
    {
      return (x*y);
    }
};

void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

int main ()
{
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}
The most important new thing in this code is the operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class definition itself.

You may notice that the definition of the member function area() has been included directly within the definition of the CRectangle class given its extreme simplicity, whereas set_values() has only its prototype declared within the class, but its definition is outside it. In this outside definition, we must use the operator of scope (::) to specify that we are defining a function that is a member of the class CRectangle and not a regular global function.
The only difference between defining a class member function completely within its class or to include only the prototype and later its definition, is that in the first case the function will automatically be considered an inline member function by the compiler, while in the second it will be a normal (not-inline) class member function, which in fact supposes no difference in behavior.

 


Interview question: why u want to make class?
Answer: 1). better organization of data.
                    --give its a logical entity
                    --In class we all declared variable have a continues memory location
                    --class gives us grouping of variable in one place.
                    --by organise we achieve –maintainbility, security, efficiency.
2). Safety of data (private or protected)
3). Reusability (via inheritance)
4). Polymorphism (see above)
5). abstraction

Analogy:
         If a class is a house, then the functions will be the doors and the variables will be the items inside the house.

Class help us to achieve encapsulation:
If a class is a house, then the functions will be the doors and the variables will be the items inside the house. The functions usually will be the only way to modify the variables in this structure, and they are usually the only way even to access the variables in this structure. This might seem silly at first, but the idea to make programs more modular - the principle itself is called "encapsulation". The key idea is that the outside world doesn't need to know exactly what data is stored inside the class--it just needs to know which functions it can use to access that data. This allows the implementation to change more easily because nobody should have to rely on it except the class itself.

Constructor and destructor:
            Classes must always contain two functions: a constructor and a destructor. The syntax for them is simple: the class name denotes a constructor, a ~ before the class name is a destructor.
            When the programmer declares an instance of the class, the constructor will be automatically called. The only time the destructor is called is when the instance of the class is no longer needed--either when the program ends, the class reaches the end of scope, or when its memory is deallocated using delete
            Keep in mind that neither constructors nor destructors return arguments! This means you do not want to (and cannot) return a value in them.
            Note that you generally want your constructor and destructor to be made public so that your class can be created! The constructor is called when an object is created, but if the constructor is private, it cannot be called so the object cannot be constructed. This will cause the compiler to complain.

// example: class constructor
#include <iostream>
using namespace std;

class CRectangle
{
    int width, height;
  public:
    CRectangle (int,int);
    int area ()
    {
      return (width*height);
    }
};

CRectangle::CRectangle (int a, int b) 
{
  width = a;
  height = b;
}

int main ()
{
  CRectangle rect (3,4);
  CRectangle rectb (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}
You can  see how neither the constructor prototype declaration (within the class) nor the latter constructor definition include a return value; not even void.


Question. What is the difference between “C++ class” and “C# class” ?