private data member is accessed and no error
Apr 24, 2014 at 5:56pm UTC
Here in below code, the private data member is accessed directly using dot operator IN COPY CONSTRUCTOR and the program runs without error.
Please explain....
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <cstdlib>
#include <iostream>
using namespace std;
class array {
int *p;
int size;
public :
array(int sz)
{
p = new int [sz];
size = sz;
}
~array() { delete [] p; }
// copy constructor
array(const array &a);
void put(int i, int j)
{
if (i>=0 && i<size) p[i] = j;
}
int get(int i)
{
return p[i];
}
};
// Copy Constructor
array::array(const array &a) {
int i;
p = new int [a.size];
for (i=0; i<a.size; i++) p[i] = a.p[i];
}
int main()
{
array num(10);
int i;
for (i=0; i<10; i++)
num.put(i, i);
for (i=9; i>=0; i--)
cout << num.get(i);
cout << "\n" ;
array x(num); // invokes copy constructor
for (i=0; i<10; i++)
cout << x.get(i);
return 0;
}
Apr 24, 2014 at 6:18pm UTC
The copy constructor is a member of the class. Therefore, it has access to the private members of the class.
Topic archived. No new replies allowed.