user7144983 user7144983 - 16 days ago 5
C++ Question

C++ Dynamic Constructor

I'm getting the error:


no operator "[]" matches these operands


For the line:

cout << A[j].display(n)


But when I take out the
[j]
, I'm getting the error:


class "list" has no member "display"


Here is my code:

class list
{
protected:
int *p; // pointer to a list
int size; // dimension
public:
list(int x)
{
size = x;
p = new int[size];
}
void get(int i, int val)
{
p[i] = val;
}
};

class dlist : public list
{
public:
int display(int i)
{
return p[i];
}
};

int main()
{
int n;
cout << "Enter elements in a row\n";
cin >> n;

list A(n);

int j, val;
for (j = 0; j < n; j++)
{
cin >> val;
A.get(j, val);
}
cout << "\n";
cout << "List of elements are :\n";
cout << "----------------------\n";
for (j = 0; j < n; j++)
cout << A[j].display(j) << "\t";
cout << "\n";
return 0;
}


Please help!

Answer

The class list indeed has no member function display. It is the class dlist declared like

class dlist : public list
//...

has such a member function. However the object A was defined in main like an object of class list

list A(n);

Moreover you can not create an object of the type dlist because you have to define explicitly a constructor of the type.

If you want to use polymorphism then introduce virtual functions making for example the member function display like virtual.

Also this syntax

cout << A[j].display(j) << "\t";
        ^^^^^^^^^^^^^^

is incorrect because the object A is a scalar object. It is not an array of objects and the class has no overloaded operator [].

You should start by defining explicitly a virtual destructor (otherwise there can be a memory leak in your program) that delete dynamically allocated memory in the constructor with parameter, copy constructor and the copy assignment operator in the class list. Then you can define the subscript operator and so on.

Comments