Can we achieve polymorphism through const function? I mean does a function a() and another function a()const behave polymorphically?
void func(int a){}
void func(int a)const {}
Can we achieve polymorphism through const function? I mean does a function a() and another function a()const behave polymorphically?
void func(int a){}
void func(int a)const {}
Answer is . you can overload it !!
#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: The above program compiles and runs fine, and produces following output.
fun() called
fun() const called
The two methods ‘void fun() const’ and ‘void fun()’ have same signature except that one is const and other is not. Also, if we take a closer look at the output, we observe that, ‘const void fun()’ is called on const object and ‘void fun()’ is called on non-const object. C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function return reference or pointer. We can make one function const, that returns a const reference or const pointer, other non-const function, that returns non-const reference or pointer.
This is not polymorphism. This is function overloading.
You might be confusing overloading with overriding.
Function overloads are two functions that have the same name, but different signatures. The code you've posted is an example. The parts of a function that make up the signature include the parameter list and the const
qualification of the method. Notably, the function's return type is not part of the function's signature.
Function overrides are created using the keyword virtual
. The have the same name and the same* signature. The basic idea behind overrides is to be able to call a derived class' special functions if all you have is the pointer to the base class. Here's an example:
class Foo
{
public:
virtual std::string GetIt() const { return "FOO" }
};
class Bar : public Foo
{
public:
std::string GetIt() const { return "BAR"; }
};
int main()
{
Foo* that = new Bar;
cout << that->GetIt();
}
The program will output "BAR", even though the pointer is a pointer to a Foo
.
*"the same signature": Actually, co-variant signatures.
Yes we can achieve polymorphic behavior.
As we can able to call those functions, one(const function) with constant object and the other(non constant function) with non constant object. Both the functions have same name but they are of different usage nd polymorphism also refers to same name but different forms.