Showing posts with label why. Show all posts
Showing posts with label why. Show all posts

Thursday, February 7, 2013

Why static Variable auto intialize to 0

Ans. Because It's not goes in the stack memory area.

Fact that u must know before this program:
        1. GLOBAL and STATIC variable auto initialize to 0
        2. Global Variable text-segment m jata hai.

-----------------------------------------------------------------------------------------------
 Note: in blue color is actual code rest code is to get clear output
#include <iostream>
using namespace std;

    int normalLocal;              //global variable
    static int normalLocalStatic; //global static variable
   
    class Demo
    {
        public:
            int classInstance;
            static int classInstanceStatic;
    };
   
    int Demo::classInstanceStatic;
   
    void test()
    {
        int functionLocal;
        static int functionLocalStatic;
       
        cout << "\n    functionLocal is : " << functionLocal <<endl;
        cout << "\nfunctionLocalStatic is : " << functionLocalStatic <<endl;
    }
   
    class DemoHeap
    {
        public:
            int classHeapInstance;
            static int classHeapInstanceStatic;
    };
   
    int DemoHeap::classHeapInstanceStatic;

int main()
{
    int mainLocal;
    static int mainLocalStatic;

   
    cout << "\n\n-----------just below header files (Means global area)-------------" << endl;
    cout << "\n       normalLocal is : " << normalLocal  

           << "\t Please Notice this is GLOBAL variable" <<endl;
    cout << "\n normalLocalStatic is : " << normalLocalStatic  

           << "\t Please remember STATIC variable" <<endl;
   
    cout << "\n\n-----------Inside function-------------" << endl;
    test();
       
    Demo d;    //This makes object on stack
    cout << "\n\n-----------This object on stack-------------" << endl;
    cout << "\n      classInstance is : " << d.classInstance << endl;
    cout << "\nclassInstanceStatic is : " << d.classInstanceStatic << endl;

   
    cout << "\n\n-----------Inside Main-------------";
    cout << "\n         mainLocal is : " << mainLocal << endl;
    cout << "\n   mainLocalStatic is : " << mainLocalStatic << endl;

   
   
    DemoHeap * dh = new DemoHeap(); //This makes object on heap
    cout << "\n\n-------This object on heap-------------" << endl;
    cout << "\n        classHeapInstance is : " << dh->classHeapInstance 

           << "  surprise(local var auto-intializ to 0)" << endl;
   cout << "\n  classHeapInstanceStatic is : " << dh->classHeapInstanceStatic << endl;
    delete dh;
    dh = 0;

   
    return 0;
}

OUTPUT:

Moral of the story:
  1.  jo variable stack m jayega vo default garbage value lega;(ab samjha java har variable aotu 0 kyu hota hai)
  2. jo variable static or heap or text-segment m jayega vo aotu 0 initialized ho hoga.
  3. isliye global and static variable kahi bhi ho vo auto 0 initialized hote hai.
For more on Stack and Heap...

Saturday, December 29, 2012

why use interfaces

So if an interface implements no functionality then why should we use them?
     Using interface based design concept provides loose coupling, component-based programming, easier maintainability, makes your code base more scalable and makes code reuse much more accessible because implementation is separated from the interface. Interfaces add a plug and play like architecture into your applications. Interfaces help define a contract (agreement or blueprint, however you chose to define it), between your application and other objects. This indicates what sort of methods, properties and events are exposed by an object.


This article not complete yet, we are in developing  phase, we are sorry

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” ?

Wednesday, September 26, 2012

What is Polymorphism

What is Polymorphism:
  • Polymorphisms is a generic term that means 'many shapes'.
  • Polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).
  • Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
  • More precisely Polymorphisms means the ability to request the same operations be Performed on a wide range of different types of things. (operator overloading)
  • Polymorphism is the ability of one object to be treated, or used, like another.

  • It is closely related to the inheritance hierarchy.
  • Function polymorphism is a kind of overloading and overriding.
  • Class polymorphism is like inheriting parent class/interface and instantiating the subclass with parent class/interface.
  • (class doesn't support polymorphism by default.) (we achieve class level polymorphism by  interface/abstract class)
  • (object doesn't support polymorphism by default; we cannot add 1 to any object) (we achieve  polymorphism in object by 'operator function')

By polymorphism we can develop new ability.  (child jab born hota hai. to vo polymorphic nature nahi rakhata, use ability di jati hai polymorphic hone ki.)

Polymorphhism in Plain English:
Noun: 1. The occurrence of something in different forms, in particular.
         2. The occurrence of different forms among the members of a population or colony.
Synonym: Multiformity

Why polymorphism:
  1. It makes our code simple (by giving polymorphic nature)
  2. U don't have remember which methode to call. (eg. multi-language SW) (function/operator overloading)
  3. To extend the behaviour of base class. (function overriding)

            The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.
            In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.

There are various forms of Polymorphism:
  • Function overloading: Defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.   
  • Virtual methods in OOP: A method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.
  • Templates: A feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.