7. CPP-Classes & Objects

CPP Functions: Previous                                                   Next: CPP Array of Objects

Classes:
  • A class is a blueprint that doesn't exists and works as template for objects.
  • A class contains member data or member functions together.
  • Generally class contains two concept :
    • Class declaration
    • Definition of functions
  • A class uses keyword “class” before the class name and semicolon is used for terminating the declaration of class.
Syntax:
Class
{
;
};
Access modifiers :
  • Access modifiers provides security to the data members and member function of the class.
  • It doesn’t allow them to move around.
  • It decisides the visibility of data.
  • Three keywords are used:
    1. private
    2. public
    3. protected

  1. private : it is default  access modifier. And these data members are accessible within a class in which it is declared.
  2. public: it is accessible at anywhere in program.
  3. protected: it is accessible within a class in which it is declared or accessible in immediate derived class.
Member function of the class can be declared inside the class or outside the class.
Example:
//example of a class member function declared inside it
#include
class sum
{
int num1,num2;
public :
int result( )
{
int sum1=0;
sum1=num1+num2;
return sum1;
}
};
Example   :
//example of class declaration and member functions are declared outside class using scope resolution
#include
class sum
{
int num1, num2;
public:
int result( );
void display( );

};
int sum::result( )
{
return (num1+num2);

}
void sum ::display( )
{
cout<<”two numbers are = “<
}
Creating an objects :
  • The declared willn’t work until its object is not created.
  • A class works as blueprint or template for objects.
  • A class decides the behavior of an object.
  • More than one object of a same class can be created.and must be declared in main( ).
  • Syntax :
Eg:
sum s1,s2;
to access member functions of class dot operator is used.
For eg:
A class is declared before and after that creation of object
void main()
{
sum s1,s2;
s1.result( );
s1.display( );
s2.result( );
s2.display( );
}
A simple C++ program with class :
#include
Class SimpleInterst
{
public :
intprinc,time,rate;
public:
void input( )
{
cout<<”enter principal, time , rate for calculation”;
cin>>princ>>time>>rate;
}
void calculation( )
{
int result;
result=(princi+time+rate)/100;
cout<<”simple interest is= “<
}
};
void main( )
{
SimpleInterst s1;
s1.input();
s2.calculate();
}
Output:


CPP Functions: Previous                                                   Next: CPP Array of Objects