Search code examples
c++constantsinlinemember-functionsconst-cast

Accessing an inline function through a const member variable


I wanted to understand how the inline member variable work while accessing it through a const member variable. Each time I try doing so, I get an error!

This is what I am trying

#include <iostream>
#include <string>
using namespace std;

class A{
    public:
    A()
    {
        _uuid = 0;
    }
    ~A();
    void setUUID(int n) { _uuid = n; }
    inline int getUUID(){  return _uuid;} const
    int getUUID1() const {  return _uuid;} 
    int getUUIDsmart()const 
    { 
        return _uuid; 
    }
    private:
    int _uuid;    
};

class B {
    public:
    B(){}
    ~B();
    void fun1(const A *obj) 
    {
        cout<<obj->getUUIDsmart()<<endl;   //works fine
        cout<<obj->getUUID1()<<endl;       //works fine
        cout<<obj->getUUID()<<endl;        //error

        A *obj1 = const_cast<A *>(obj);
        cout<<obj1->getUUID()<<endl;       //works fine
    }
};

int main()
{
  B *b = new B;
  A *a = new A;
  a->setUUID(12);
  b->fun1(a);
}

I am able to get my code work through

const_cast

But I am interested in knowing why do i get an error in the inline function if I try accessing it through a const member function?

Update: FIX

My bad. I had the placement of const messed up! Thanks to @bruno

inline int getUUID() const { return _uuid; }
//correct syntax. i placed the const at the end

Solution

  • [note : I use the first version of the question]

    you place wrongly your const :

    inline int getUUID(){  return _uuid;} const
    int getUUID1(){  return _uuid;} const
    int getUUIDsmart()const 
    

    is in fact

    inline int getUUID(){  return _uuid;} 
    const int getUUID1(){  return _uuid;} 
    const int getUUIDsmart()const 
    

    I just moved the const on the right line for readability reason

    You wanted

    inline int getUUID() const {  return _uuid;}
    int getUUID1() const{  return _uuid;}
    

    in your version none of getUUID1 nor getUUID are const so you cannot apply them on a const instance

    There is no link at all with the fact your methods are inline or not.


    Note :

    cout<<obj->getUUID1()<<endl;       //works fine
    

    it doesn't