Friday 1 February 2013

class declaration in c++

// A prog to print sum and avg of three nos using functions.
#include<iostream.h>
#include<conio.h>

/*usually the data within a class is private and the functions are public. this is a result of the way, classes are used. the data is hidden so it will be safe from
accidental manipulation, while the functions that operate on the data are public so they can be accessed from outside the class. However there is no rule that says
data must be private and functions public; in some circumstances you may find you'll need to use private functions and public data.*/

//Remember that the defination of a class doesn't create any objects. it only describes how they will look when they are created.

//To create an object is called instantiating them. An object is an instance (ie a specific example) of a class. Objects are sometimes called instance variable.

class marks
{
private:
float a,b,c;
public:
void input()
{
cout<<"enter three nos"<<endl;
cin>>a>>b>>c;
}

int sum()       //member function
{
return a+b+c;
}

float avg()
{
return (a+b+c)/3;
}

};

void main()
{marks a;
a.input();           //the dot operator is also called the class member access operator
int x=a.sum();
cout<<"sum is"<<x<<endl;
float z=a.avg();
cout<<"avg is"<<z<<endl;
getch();
}

0 comments:

Post a Comment