can achieve polymorphism through const function? mean function a() , function a()const behave polymorphically?
void func(int a){} void func(int a)const {}
answer . can overload !!
#include<iostream> using namespace std; class test { protected: int x; public: test (int i):x(i) { } void fun() const { cout << "fun() const called " << endl; } void fun() { cout << "fun() called " << endl; } }; int main() { test t1 (10); const test t2 (20); t1.fun(); t2.fun(); return 0; }
output: above program compiles , runs fine, , produces following output.
fun() called fun() const called
the 2 methods ‘void fun() const’ , ‘void fun()’ have same signature except 1 const , other not. also, if take closer @ output, observe that, ‘const void fun()’ called on const object , ‘void fun()’ called on non-const object. c++ allows member methods overloaded on basis of const type. overloading on basis of const type can useful when function return reference or pointer. can make 1 function const, returns const reference or const pointer, other non-const function, returns non-const reference or pointer.
Comments
Post a Comment