Reputation: 1
I wrote the following code, composing of two classes, Item and Integer. Integer is derived from Item and has a value "data". I wrote a printAll method which is meant to print one by one the elements of an array containing pointers but when I try to implement the printAll method in the main function I am getting an error saying it is undefined even though I defined it using the print method in the Integer class above.
#include <iostream>
#include<string>
using namespace std;
class Item
{
public:
// prints data
virtual void print() = 0;
// returns “INTEGER”
virtual string getType() = 0;
// Adds or concatenates the 2 data members.
// Throws an exception in case of a type mismacth
virtual Item* add(Item* item) = 0;
};
class Integer : public Item {
private:
int data;
public:
Integer(int i) { //Constructor
data = i;
}
void print() {
cout << "Integer value is: " << data << endl;
}
string getType() {
return "INTEGER";
}
Item* add(Item* item) {
if (item->getType() == "INTEGER") {
dynamic_cast<Integer*>(item)->data;
}
else {
throw "Type Mismatch";
}
}
void printAll(Item** items, int n) {
for (int i = 0; i < n; i++) {
items[i]->print();
}
}
};
void main()
{
int n = 10;
Item** integers = new Item * [n];
Item** strings = new Item * [n];
// populate lists
for (int i = 0; i < n; i++)
{
integers[i] = new Integer(i);
}
printAll(integers, n); // print integers
Upvotes: 0
Views: 551
Reputation: 87959
The mistake is that you put printAll
in the Integer
class. Change your code like this
class Integer : public Item {
...
};
void printAll(Item** items, int n) {
for (int i = 0; i < n; i++) {
items[i]->print();
}
}
If a method is in a class, then you must (explicitly or implicitly) provide an object to call that method on. You didn't do that which is why you got the error. But in this case printAll
should not be in any class, it should just be a regular function that you can call without supplying an object.
Upvotes: 4