-
Derived vs base class pointer/operator resolution
I have input stream operators defined in a base class and in a derived class.
My program defines a pointer to the base class, loads the pointer with the address of a derived-class object, and executes stream input via the pointer. The base class's operator code runs, not the derived class's, that is, the pointer's type prevails, not the target object's type.
Note that the input stream ">>" operators are friend functions, not members.
Is there a way to get the derived class's operator to run?
Code snippet:
//Operator declarations:
friend istream & operator>> (istream & is, BC & q);
friend istream & operator>> (istream & is, DC & q);
class DC : public BC { // DC is derived from BC
BC * nptr; //Declare pointer to base class
nptr = &DC; //Load pointer with address of derived class
instream >> *nptr; //This runs the base class's ">>" operator
}
-
If this were a member function, then you would simply declare it virtual. That said, I don't think (though I'm not sure) that you can have virtual friend functions. So here's what I would do. Declare a "virtual void read(istream&)" member in your base class and then from your friend function, just call the read function. Hope this helps.
~evlich
-
The problem is that the static type, i.e. the compile time type of nptr is BC. It doesn't matter which objkect is bound to it at runtime (i.e., derived or base) because the overload resolution takes place at compile time, and at that stage, nptr is BC *. Therefore, the >> operator which takes BC & is called.
If you want the derived version to be called you need to define a pointer to DC.
You can also try to eplicitly cast *nptr to DC& but this is quite dangerous and ugly.
Last edited by Danny; 03-16-2006 at 12:27 PM.
Danny Kalev
-
Thanks very much. Your explanantion and corroboration of my suspicion is indeed helpful.
I'm using virtual functions, which run their own class's ">>".
Similar Threads
-
Replies: 5
Last Post: 01-15-2006, 08:10 PM
-
Replies: 1
Last Post: 06-13-2002, 02:52 PM
-
Replies: 1
Last Post: 11-09-2000, 06:38 PM
-
Replies: 1
Last Post: 10-24-2000, 11:38 AM
-
Replies: 0
Last Post: 10-23-2000, 05:49 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|