Showing posts with label polymorphism. Show all posts
Showing posts with label polymorphism. Show all posts

Monday, February 18, 2013

Interview question on Virtual Function

Que. Can a methode in base class which is declared as virtual be called  using the base class pointer which is pointing to a derived  class object?
 


#include <iostream>
using namespace std;

class B
{
    public:
        virtual void foo()
        {
            cout << "\n its from B" << endl;
        }
};

class D: public B
{
    public:
         void foo()
        {
            cout << "\n its from D" << endl;
        }
};

int main()
{
    B * b = new D();
    b->B::foo();
    b->foo();   //here parent class access the function of child class
//  b->D::foo();  //error -->'D' is not a base of 'B'
    delete b;
    b = 0;

//    D * d = new B;  //error --> invalid conversion from 'B*' to 'D*'
    return 0;
}


OUTPUT:

See in C# also CLICK HERE

Saturday, December 15, 2012

A program for understanding 'Array of pointer'

#include <iostream>
#include <string.h>
using namespace std;

class city
{
    protected:
        int len;
        char*name;
       
    public:
        city()
        {
            len = 0;
            name = new char[len + 1];
        }
       
        void getname()
        {
            char *a;
            a = new char[30];
       
            cout << "\n Enter city name: ";
            cin >> a;
            len = strlen(a);
            name = new char[len + 1];
            strcpy(name, a);
        }
   
        void putname()
        {
            cout << "\n city name: " << name;
        }
};

int main()
{
    city *p[10];
    int n = 1;
    int opt;
   
    do
    {
        p[n] = new city;
        p[n++] -> getname();
        cout << "\n enter 1 for more entry of city name or 0 for exit: ";
        cin >> opt;
    }while(opt);
   
    cout << "\n\n";
    for (int i=1; i<=n; i++)

    {
        p[i] -> putname();

    }
}

Pointer with classes

Pointer with classes:
                           c++ supports dynamic binding which is one of the powerful features of object oriented programming. To achieve dynamic binding we require virtual functions, which is implemented by concept of pointers with classes and object. Here we discuss concept of pointer, after that we explain virtual function.

1.1 Pointer of objects:
                                Car * santro; (is a pointer to an object of class Car)
as it happened with datastructure, in order to refer directly to a member of an object pointed by a pointer we use the arrow operator (->) of indirection. here is an example with some possible combinations:

//Pointer to classes

#include <iostream>
using namespace std;

class CRectangle
{
    int width, height;

    public:
        void set_values (int, int);
        int area(void)
        {
            return (width * height);
        }
};

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

int main()
{
    CRectangle a, *b, *c;
    CRectangle *d = new CRectangle[2];
    b = new CRectangle;
    c = &a;
   
    a.set_values (1, 2);
    b->set_values (3, 4);
    d->set_values (5, 6);
    d[1].set_values (7, 8);
   
    cout << "\n      a area: " << a.area();
    cout << "\n    *b area: " << b->area();
    cout << "\n    *c area: " << c->area();
    cout << "\n d[0] area: " << d[0].area();
    cout << "\n d[1] area: " << d[1].area();
}

Polymorphism

Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.

WHY polymorphism:
1. it makes our code simple. (by giving polymorphic nature)
2. u don't have remember which methode to call.


Diffenrent type of polymorphism:
      1. Static Polymorphism (Early binding) [at compile time]
      2. Dynamic Polymorphism (Late binding) [at runtime]


Polymorphism:
    1.1 compile time polymorphism:
          1.1.1. operator overloading              
          1.1.2. funtion/methode overloading      
 

    1.2. runtime Polymorphism: 
           1.2.1 methode overriding

1. Pointer to classes

2. Array of pointer


3. This pointer


4. Virtual function


5. Abstract class and pure virtual function 1


6. Abstract class and pure virtual function 2


7. dynamic allocation and polymorphism

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.

Saturday, September 1, 2012

Polymorphism in c


operator overloading--  c support;                  c++ also support
function  overloading--  c doesn't support;       c++ support

c support operator_overloading but not Function_overloading
c++ support operator_overloading as well as Function_overloading

What is operator overloading:
                               operator overloading is a specific case of polymorphism, where  operators  have different implementations depending on their arguments. 
(The whole idea in operator overloading is 'same operator' and 'different type argument')

what is Function overloading: 
                            Function overloading or method overloading is a feature in programming language that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. 
(The whole idea in function overloading is 'same function name' and 'different type argument')


As we known 'int' and 'float' are different datatype, instead of using different operator to add 'int' and 'float'; we use a common operator (+), this is known as operator overloading.


Program to shows, C support operator overloading
program to shows, cpp support operator overloading

____________________________________________________________________________
Program to show, c doesn't support Function overloading 
#include <stdio.h>
#include <conio.h>

// volume of a cube
int volume(int s)                         //Name of this function is 'volume'
{
    return(s*s*s);
}

// volume of a cylinder
double volume(double r, int h)      
//Name of this function is also 'volume' 
{
    return(3.14*r*r*h);
}

// volume of a cuboid
long volume(long l, int b, int h)     //Name of this function is also 'volume'
{
    return(l*b*h);
}

int main()
{
    cout << volume(10)        << endl;
    cout << volume(2.5,8)     << endl;
    cout << volume(10,5,15)  << endl;
}
  • when we compile this program it give error, because c doesn't support 'function overloading.'
  • जब c compiler 3 same name (volume) के फंक्शन देखता है तो कंफ्यूज हो जाता है। क्योकि c का compiler Function overloading (polymorphism) नहीं जनता, इसलिए तो  कहते है, c Function overloading support नहीं करती।

_________________________________________________________________________________
But c++ Function overloading support करती है
Program to show, cpp support Function overloading 
#include <iostream>
using namespace std;

// volume of a cube
int volume(int s)                         //Name of this function is 'volume'
{
    return(s*s*s);
}

// volume of a cylinder
double volume(double r, int h)      
//Name of this function is also 'volume' 
{
    return(3.14*r*r*h);
}

// volume of a cuboid
long volume(long l, int b, int h)     //Name of this function is also 'volume'
{
    return(l*b*h);
}

int main()
{
    cout << volume(10)       << endl;
    cout << volume(2.5,8)    << endl;
    cout << volume(10,5,15) << endl;
}
 

This program run and
OUTPUT IS:
1000
157
750 
_________________________________________________________________  

Tuesday, August 14, 2012

virtual inheritance and runtime polymorphism

// Using dot net and C#
using System;

public class a
{
    public void Hockey()
    {
        Console.WriteLine("A play hockey");
    }

    public virtual void education()
    {
        Console.WriteLine("MBBS");
    }

}
public class b:a
{
    public void cricket()
    {
        Console.WriteLine("B play cricket");
    }
    public override void education()
    {
        Console.WriteLine("MCA");
    }
}

class demo
{
    public static void Main()
    {
        a a1=new b();            //run time polymorphism
        a1.education();
        Console.ReadLine();
    }
}


OUTPUT:

To see in c++ CLICK HERE