+ 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?

15th Mar 2021, 12:22 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
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
15th Mar 2021, 4:07 PM
XXX
XXX - avatar
+ 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.
15th Mar 2021, 1:45 PM
XXX
XXX - avatar
+ 2
Coder Kitten yes std::advance is very ideal👍. I didn't metion it as I was trying to keep it simple to understand.
15th Mar 2021, 4:24 PM
XXX
XXX - avatar
+ 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?
15th Mar 2021, 3:06 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Thanks a lot guys Coder Kitten and XXX
15th Mar 2021, 5:49 PM
Ketan Lalcheta
Ketan Lalcheta - avatar