User loginNavigation |
Covariance and typingC++ supports covariant return types -- that is, class A can have function foo that returns a BaseClass pointer, and B can derive from A and override foo to have a return type of DerivedClass pointer. Why couldn't this be extended to covariant members? class Base { }; class Derived : public Base { }; class A { protected: Base x; }; class B : public A { protected: Derived x; }; With covariant members, this would make it so in instances of A, x is a Base, but in instances of B, x is a Derived. In vanilla C++, B's x would simply hide A's. All of A's code that B inherits using x should still work because Derived inherits from Base. Currently to do this you need boilerplate to take advantage of covariant returns: class A { protected: virtual Base& GetX() { return x; } Base x; }; class B { protected: virtual Derived& GetX() { return myX; } Derived myX; }; Further boilerplate has to be written if you don't want x and myX to both be allocated in B, and you'll need to call GetX() everytime you want that member in your code rather than accessing it directly. Covariant parameters would follow the same pattern although I'm not sure of a good use case for them other than for getting around C++ not having virtual operators (you may want to define an Assign member function to use in place of the assignment operator because it could be virtual and have it take a covariant parameter for what to assign to). I'm curious if there are any OOP languages out there have tried to more strongly support the covariance relationship between classes. I've seen some variation in how classes inherit (whether for interface or code reuse) between languages but no difference as regards this behavior. By dataangel at 2006-08-02 05:13 | LtU Forum | previous forum topic | next forum topic | other blogs | 13931 reads
|
Browse archives
Active forum topics |
Recent comments
12 weeks 1 day ago
12 weeks 1 day ago
12 weeks 1 day ago
34 weeks 2 days ago
38 weeks 4 days ago
40 weeks 2 days ago
40 weeks 2 days ago
42 weeks 6 days ago
47 weeks 4 days ago
47 weeks 4 days ago