overriding with difference access specification c++ -
i came across question while taking ikm test. there base class 2 abstract methods private access specifier. there derived class overriding these abstract methods protected/public access specifier.
i never came across such thing overridden methods in derived class had different access specification. allowed ? if yes, comply "is a" relation between base , derived (i.e. safely substitutable).
could point me references can provide more details on such usages of classes ?
thank you.
as many of guys pointed out legal.
however, "is-a" part not simple. when comes "dynamic polymorphism" "is-a" relation holds, i.e. can super can derived instance.
however, in c++ have referred static polymorphism (templates, of time). consider following example:
class { public: virtual int m() { return 1; } }; class b : public { private: virtual int m() { return 2; } }; template<typename t> int fun(t* obj) { return obj->m(); }
now, when try use "dynamic polymorphism" seems ok:
a* = new a(); b* b = new b(); // dynamic polymorphism std::cout << a->m(); // ok std::cout << dynamic_cast<a*>(b)->m(); // ok - b instance conforms interface // std::cout << b->m(); fails compile due overriden visibility - expected since technically not violate is-a relationship
... when use "static polymorphism" can "is-a" relation no longer holds:
a* = new a(); b* b = new b(); // static polymorphism std::cout << fun(a); // ok //std::cout << fun(b); // fails compile - b instance not conform interface @ compile time
so, in end, changing visibility method "rather legal" that's 1 of ugly things in c++ may lead pitfall.
Comments
Post a Comment