How can I call Constant Functions?

Hello All;

I have two files:
1. ConstantConcept.cpp
2. ConstantConcept.h

1. ConstantConcept.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <cstdlib>
#include <iostream>
#include "ConstantConcept.h"

using namespace 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 = new char[ 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;
}




2. ConstantConcept.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef ConstantConcepts
#define ConstantConcepts
     class person
     {
      private:
              char *name;
              static int count;
      public:
             void get_name(char *);
             void display();
             void display() const;
     };
#endif 


Problem explanation:

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?

If yes please tell me how?

Last edited on
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.
^^ What he said..
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.
(Huh? And why do I see Disch's and guestgulkan's edits only just now? Hm.. have to have a personal word with my browser's cache settings..)
Additionally, the get_name method could be more suitably named set_name and be sure to have a destructor to delete the memory allocated for name.
Topic archived. No new replies allowed.