-->

8. CPP-Array of objects

CPP Classes and Objects: Previous                                           Next: CPP Constructors

  • Array of an object can be declared.
  • In previous example we made or calculate two objects. In some situation when we have to create more than two or three objects of same class, then array can be declared.
Syntax :
[size];
e.g.
#include
Class Sum
{
int num1, num2;
public:
void input( )
{
cout<<”enter number= “;
cin>>num1>>num2;
}
void output()
{
int sum1=0;
sum1=num1+num2;
cout<<”the result is= “<
}
};
void main( )
{
Sum s1[5];
inti;
for(i=0;i<5 i="" span="">
{
cout<<”entered numbers are :”;
s1[i].input();
}
cout<<”result is : “;
for(i=0;i<5 i="" span="">
{
s1[i].output();
}
}
Static members :
  • In C++, both data member and member functions can be static.
  • Static data member :
  • Static data members are initialized to zero when object of a class created.
  • Only one copy of static data members is created and all objects share that single copy means single value.
  • These are accessible to entire program.
  • Syntax :
static ;
e.g.
static int sum;
Static member functions :
  • Member functions of class can be declared static. But they are only accessed by classname not by using object name.
  • Syntax :
Classname :: (arguments);
Eg.:
#include
Class Abc
{
public:
static int sum;
Abc()
{
sum++;
}
static int sum()
{
return sum;
}
};
intAbc::sum;
void main()
{
sum s1;
cout<
}

Returning an object :
  • Member functions takes objects as an argument. Objects can be return through member functions of a class.
Eg:
#include
Class Abc
{
                inta,b;
                public :
                                void input(int x, int y)
                                {
                                                a=x;
                                                b=y;
                                }
                                Abc sum(int,int);
                                void output(Abc);
};
Abc sum(Abc x1, Abc x2)
{
                Abc x3;
                x3.a=x1.a+x2.b;
                x3.b=x1.a+x2.b;
                return (x3);              //returning an object
}

CPP Classes and Objects: Previous                                           Next: CPP Constructors