I was trying to solve an Exercise which goes as follows:
Demonstrate automatic counting and aggregrate initialization with an array of objects of the class you created in exercise 3(A class named Simple with one int member,a constructor and one destructor).Add a member function to that class that prints a message. Calculate the size of the array and move through it,calling your new member function.
I tried working on this exercise,came up with the following solution:
#include<iostream>
usingnamespace std;
class Simple{
int mem;
public:
Simple(int);
~Simple();
int print();
};
Simple::Simple(int m)
{
mem=m;
cout<<"int member value: "<<mem<<endl;
}
Simple::~Simple()
{
cout<<"Destructor called for object with int value: "
<<mem<<endl;
}
int Simple::print()
{
for(int i=0;i<sizeof(this);i++)
cout<<this[i]<<endl;
return 0;
}
int main()
{
Simple a[]={5,10,9,2};
a[0].print();
return 0;
}
As you can see I am unable to calculate the size of the array inside the print() member function. I tried using sizeof(this) but it only returns the size of pointer this(i.e.,4 bytes), not the size of entire array.
Obviously, I can pass the sizeof(a) as argument to function print() but that would not make sense, as it was asked in the exercise to calculate the size of array inside the new member function.
Read the instructions again. It doesn't say you should calculate the size of the array inside the print function. It would be impossible to do that because it doesn't have access to the array.
@rollie sorry.. it was this... have done corrections... anyways the function is not working... I cant get the size of array a or the number of elements in array a.
@Peter87 it says: Calculate the size of the array and move through it,calling your new member function.
This will yield the size of Simple; 4-bytes (on a 32-bit system)
mahone wrote:
cout<<this[i]<<endl;
Your Simple class doesn't overload the sub-script operator ([...]), so the compiler isn't going to know how to handle the sub-script when applied to a Simple object.
1 2 3
Simple::Simple(int m)
{
mem=m;
Use the constructor's initialisation list:
1 2 3 4
Simple::Simple(int m)
: mem(m)
{
}
It seems you haven't grasped the concept of arrays, and how classes work in general. I recommend reading about both arrays and classes again.