+ 1
Can we inherit c++ defined class?
Hi I was given a problem statement to implement a subscript operator[] for list. Does this mean I have to implement my own list ? can I inherit list class to new class called mylist or is it possible to only provide overloaded [] for c++ list?
6 Réponses
+ 2
Ketan Lalcheta
you need to rely on the public methods of std::list as you have no way to know the protected memebers on the class.
Here, I am getting the iterator to the first element of the list using std::list::begin() and then I am incrementing the iterator `index` times to get the iterator to the desired position. Then I am returning the data at that position. Hop the code is clear
https://code.sololearn.com/cDhiiN86VsZH/?ref=app
+ 2
There is no way overload the operator[] from outside the class. You can however, inherit from std::list and define the operator[] method there.
+ 2
Coder Kitten yes std::advance is very ideal👍. I didn't metion it as I was trying to keep it simple to understand.
+ 1
Thanks... I tried and could compile code also as below:
https://code.sololearn.com/c8a8a23a23a2
However, in user defined implementation of list, we have data member for actual data stored in list. Here in this example, how can I get access to data inside [] method?
+ 1
Thanks a lot guys Coder Kitten and XXX