How to overload Subscript operator

P

pasa_1

The following code results in Segmentation fault

=========================
#include <iostream>


using namespace std;


class abc{
public:
int a;
int b;
int c;


abc() {
a = 0;
b = 0;
c = 0;
}
};
int main()
{
for (int i = 0; i < 10; i++)
{
abc a;
abc *pa = &a;


pa->a = 10*i;
pa->b = 10*i;
pa->c = 10*i;


cout << "pa->a[" << i << "]: " << pa->a << endl;
cout << "pa->b[" << i << "]: " << pa->b << endl;
cout << "pa->c[" << i << "]: " << pa->c << endl;
}


return 0;
}
=========================

I know I need to overload subscript operator?
1. I am not sure how to do that. can some one suggest a way?
2. Is there anything else missing, all I want to do is read data, and
later display it?
 
P

pookiebearbottom

pasa_1 said:
The following code results in Segmentation fault

=========================
#include <iostream>


using namespace std;


class abc{
public:
int a;
int b;
int c;


abc() {
a = 0;
b = 0;
c = 0;
}
};
int main()
{
for (int i = 0; i < 10; i++)
{
abc a;
abc *pa = &a;


pa->a = 10*i;
pa->b = 10*i;
pa->c = 10*i;


cout << "pa->a[" << i << "]: " << pa->a << endl;
cout << "pa->b[" << i << "]: " << pa->b << endl;
cout << "pa->c[" << i << "]: " << pa->c << endl;
}


return 0;
}
=========================

I know I need to overload subscript operator?
1. I am not sure how to do that. can some one suggest a way?
2. Is there anything else missing, all I want to do is read data, and
later display it?


you probably want the
abc a;
outside the for loop as
abc a[10];
 
T

Thomas J. Gritzan

pasa_1 said:
I know I need to overload subscript operator?

You don't. See below.
class abc{
public:
int a;
int b;
int c;


abc() {
a = 0;
b = 0;
c = 0;

In general case, prefer initialization over assignment:

abc() : a(0), b(0), c(0)
{
}
int main()
{
for (int i = 0; i < 10; i++)
{
abc a;


The size of an array has to be constant. This shouldn't compile unless
your compiler has variable length Arrays as extension (gcc has).
You would want this to be outside the for-loop with size equal to the
maximum subcript you use plus 1:

abc a[10];
abc *pa = &a;

[snip]

Here you make a pointer to one past the last element of the array. Using
this pointer is undefined behaviour, giving you a segmentation fault.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
VetaMcRae
Top