#include <cstdlib>
#include <iostream>
#include "ConstantConcept.h"
usingnamespace std;
int main(int argc, char *argv[])
{
person P1,P2,;
P1.get_name("Bob");
P1.display(); //Trying to call constant display function
P2.get_name("Jack");
P2.display(); //Trying to call constant display function
P1.display(); //Trying to call non-constant function
system("PAUSE");
return EXIT_SUCCESS;
}
int person :: count = 0;
void person :: get_name(char *FName)
{
name = newchar[ strlen(FName) + 1];
strcpy( name, FName);
count++;
}
void person :: display() const
{
cout<<"I am "<<name<< " at "<<count<<endl;
}
void person :: display()
{
count++;
cout<<"I am in without constant Display function and count = "<<count<<endl;
}
You all can see here I am deliberately wants to call constant display function but all the time compiler calling non-constant display function as both the function has similar attribute so my question is can we call the constant function which has similar attribute as of another function?
You should not have const and non-const versions of functions when they do two entirely different things. From a practical standpoint, it shouldn't matter whether the compiler calls the const version or not.
If you need to select one or the other, give them different names.
Otherwise the only way to explicitly call the const version is to cast the person to a const person.
Can you quickly edit your post (the small edit-icon next to the headline) and put "[code]" and "[ /code]" around your code? It makes reading it soooooo much easier.