Too few arguments inheritance c++ -
i'm working on learning inheritance making generic list class. list can unordered list, ordered list, stack, or queue.
my list class looks this:
class list { public: class node { public: int data; node * next; node(int data); }; int sizeoflist = 0; node * head = nullptr; list::list(); virtual void get(int pos); virtual void insert(int data); virtual void remove(int pos); virtual void list(); virtual int size(); }; my unordered list class looks this:
class unorderedlist : public list { public: unorderedlist(); void get(); void insert(int data); virtual void remove(); //takes no parameters because first item removed }; in main(), create array of lists this;
list * lists[8]; and make unordered list this:
lists[0] = new unorderedlist(); my question: lists[listnum]->get(); gives error
"too few arguments in function call"
because thinks trying call get() in listclass, want call unordered list's function get().
i feel must improve upon sam varshachik's answer - though totally correct.
class list { public: virtual void get(int pos); }; class unorderedlist : public list { public: void get(); }; note there 2 problems here - not one.
firstly signature of get(int) different get() - these two different methods, , compiler treat them such.
further have declared method list::get(int) virtual, have not done-so unorderedlist::get() - remember list object has no knowledge it's children - list * cannot understand details of unorderedlist.
consider example:
class list { public: virtual void get(int pos); }; class unorderedlist : public list { public: virtual void get(); //still error! }; in case, have made unorderedlist::get() virtual - won't help. list still has no knowledge of method.
the correct snippet follows:
class list { public: virtual void get(int pos); virtual void get(); }; class unorderedlist : public list { public: virtual void get(); //we can use now! virtual void get(int pos); //this needed if intend override method }; in example list::get() virtual method - such call communicated correct-child intended.
possible because the parent class has been informed such method exists, , can over-ridden child classes.
[edit /]
as jonathanpotter stated in comments, pay attention fact virtual keyword needed if wish method called parent-pointer routed actual child object. , incur overhead.
Comments
Post a Comment