Thursday, April 5, 2012

A simple 'class' program

//class with single object
// using c++

#include <iostream>
using namespace std;

class CRectangle 
//here we define a user-defined-datatype 'CRectangle' using 'class'
{
    private:
        int x, y;


    public:
        void set_values (int,int);


        int area()
        {
            return (x*y);
        }
};

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

int main()
{
    CRectangle rect;    //creating the object (rect) of a class (CRectangle)


    rect.set_values (3,4);
    cout << "area:" << rect.area();
   
    cin.ignore();
    cin.get();
}



Note: we must use the operator scope-resulation (::) to specify that we are defining a function that is a member of the class CRectangle and not a regular global function.
 _________________________________________________________
See also the same program using struct (only difference, we use 'struct' instead of 'class') 

No comments:

Post a Comment