CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 1999
    Posts
    10

    How can I Invoke a const member function in a class?

    When I learn the STL,I find that we can define such a class:
    class A {
    public:
    int a;
    A(int x=0):a(x) {};
    int GetA() { return a++;};
    int GetA() const { return a;};
    };

    But I find when I call the GetA method,the non-const method will be invoked
    always,for example:

    void main()
    {
    A t(10);
    cout<<t.GetA()<<endl; //call non-const method
    cout<<t.GetA()<<endl; //call non-const method
    }

    Can anybody tell me how I invoke the const method without deleting the
    non-const one?


  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: How can I Invoke a const member function in a class?

    You need to call GetA with a const A object. Here are the ways that I have used to do what you want:

    const A* pt = &t;
    cout<< pt->GetA() << endl;

    OR

    cout << ((const A*)(&t))->GetA() << endl;

    Regards,

    Paul McKenzie


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured