Yes but not like this (one.pages (plus) two.pages (plus) three.pages)/3, What if there is unknown amount of books, and we need to find average of pages.
You have to know how many objects you have if you keep separate variables.
If you don't, you need to keep them in some kind of container ( eg: vector, list, array... )
Please refer to the below code to know how many objects are there in class. In your case you are saying you may not know the number of books (objects in class). You can do so by using static data member (in code below it is index) and set it to zero.
1 2 3
private:
staticint index;
As such this data member will be shared by all the objects. In constructor simply increment this data member. So whenever any object will be initialized this index will increament and will give the number of objects.
#include "stdafx.h"
#include "iostream.h"
class sample
{
private:
staticint index; //static data member declaration. This means that index will be shared between all the object
int count;
public:
sample()
{
index ;
}
~sample()
{
}
void showdata() const;
/* {
count ;
cout<<endl<<"index="<<index<<endl;
}*/
};
void sample::showdata() const //this is how defination of member function is done outside the class
{
cout<<endl<<"index="<<index<<endl<<"count="<<count;
}
int sample::index=0; //defination of static data member is done outside the class
//name of class must be included in defination. Can be used to keep track of how many objects are created for class
int main(int argc, char* argv[])
{
sample s1,s2,s3;
s1.showdata();
s2.showdata();
s3.showdata();
return 0;
}
Well, a container could be (as Bazzy listed above) a vector, a deque, a list, an array... the details on how to use all of them are listed below (in order of most to least recommended). :)