inheritance class beginner

generates the following errors:

'class comparable' has no member named 'score'.

i know class comparable has no member named score but high_score_element inherits from 'comparable', and high_score_element has memeber 'score' and i want to compare with that. how do i do that?
(just partial code below)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream>
using namespace std;

class comparable
{
    public:
    virtual int compare(comparable& other)=0;
};
class high_score_element:public comparable
{
    public:
    virtual int compare(comparable& other);
    int score;
};

int high_score_element::compare(comparable& other)
{
    if(this->score<other.score)
    {
        return -1;
    }
    else if(score>other.score)
    {
        return 1;
    }
    else if(score==other.score)
    {
        return 0;
    }
}

int main()
{

}
it works the other way around. score must be in the base class.
You need dynamic_cast for that:

http://www.cplusplus.com/doc/tutorial/typecasting/

Note that casting a reference this way will throw if it fails
quite confused. suppose, in addition to above code, we have the following code:

1
2
vector<comparable*> vector_to_comparable;///vector to hold comparable ///class
vector_to_comparable.push_back(new high_score_element());


now does accessing the pointer by vector_to_comparable[0] takes us to comparable class or high_score_element class?
also this way can or can't we access the data field stored in high_score_element class.


edit: @coder777 am using jumping into c++. haven't yet come across dynamic_cast. just basics of inheritance.can u suggest to solve without using dynamic_cast for now?
Last edited on
now does accessing the pointer by vector_to_comparable[0] takes us to comparable class or high_score_element class?
Well, a type does not change and hence it will always be comparable

also this way can or can't we access the data field stored in high_score_element class.
without cast: can't


If you don't want to cast do what mutexe suggested: Put everything you need for the comparison into the base class.
Last edited on
how about maintaining an internal score inside the implementation of your high_score_element.compare() method?
after all, I see your comparable class is an interface, so everything deriving this should implement it's own compare() method.
Last edited on
Topic archived. No new replies allowed.