Wednesday, March 18, 2015

Pure virtual function in C++ vs abstract method in C#

C++ Source code :

#include<iostream>
#include<conio.h>


using namespace std;

class Area
{
public:
virtual double GetArea(int length,int breadth) = 0;
};

class Rectangle : Area
{
public:
double  GetArea(int length, int breadth)
{
return length * breadth;
}
};

class Triangle : Area
{

public:
double GetArea(int length, int breadth)
{
return 0.5 * length * breadth;
}
};

void main()
{
Rectangle oRectangle;
Triangle oTriangle;

cout<<"\nArea of Rectangle:"<< oRectangle.GetArea(10, 2);
cout << "\nArea of Triangle:"<<oTriangle.GetArea(10, 2);

_getch();

}

Out Put :
Area of Rectangle: 20
Area of Triangle:10

C# source code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Project2
{
    public abstract class Area
    {
        public abstract double GetArea(int nlenght, int nbreadth);
    }

    public class Rectangle : Area
    {
        public override double GetArea(int nlength, int nbreadth)
        {
            return nlength * nbreadth;
        }
    }

    public class Triangle : Area
    {
        public override double GetArea(int nlength, int nbreadth)
        {
            return 0.5 * nlength * nbreadth;
        }
    }
    public class Class1
    {
     
        static void Main()
        {
            Rectangle oRectangle = new Rectangle();
            Triangle oTriangle = new Triangle();

            Console.WriteLine("Area of Rectangle:{0}",oRectangle.GetArea(10, 2));
            Console.WriteLine("Area of Triangle:{0}",oTriangle.GetArea(10, 2));

            Console.ReadLine();

            return;
        }
    }
}


Out Put :
Area of Rectangle: 20
Area of Triangle:10

No comments:

Post a Comment