Inheritance and the keyword SUPER

Oct 3, 2008 at 11:07am
Hi,

I have a class cat that extend class animal. I want cat to be able to call a method in animal that is also defined in cat. The method is feed(). If I wanted to do this in Java I would go super.feed(). Anyone know how to do this in C++?

Also wondering if there is some way to 'subscribe' to messages on this form. How can I find my message after I post?

Thanks in advance.
JS
Oct 3, 2008 at 12:34pm
Presumably you would make feed() a virtual or pure virtual method in animal and then override it in cat.

1
2
3
4
5
6
7
class animal {
    virtual void feed() = 0;   // pure virtual
};

class cat : public animal {
    virtual void feed() { /* do stuff */ }
};


Given an object of type cat, calling feed() on that object would call cat::feed().
If feed() were not pure in the base, then given an object of type animal (and not cat), calling feed() on that object would call animal::feed().

Not sure if this is what you are asking because I don't do java.
Oct 3, 2008 at 2:45pm
To call a method from the base class you use the scope resolution operator ::

So if you have

1
2
3
4
5
6
7
class animal {
    virtual void feed() {/*Do general animal Stuff (not pure virtual) */};
};

class cat : public animal {
    virtual void feed() { /* do cat stuff */}
};

then
1
2
myCat.feed();        //Calls cat.feed
myCat.animal::feed() //Calls animal.feed 


To find your own messages (and any replies), click on user cp in the top right corner. Under Forum Activity select Go To Active Conversations

Oct 4, 2008 at 4:21pm
Thanks Faldrax,

That was exactly what I was looking for!

Jake
Topic archived. No new replies allowed.