Search code examples
c++tinyxml

C++ Calling methods with same signature but different scope


I'm working on a project with TinyXML2. I'm trying to call the method XMLAttribute* FindAttribute( const char* name )

This method is defined by the implementation as:

public : 
const XMLAttribute* FindAttribute( const char* name ) const;

private :
XMLAttribute* FindAttribute( const char* name );

I am a bit confused how as to how a method can have the same signature in both public and private scopes. I can only guess that it does not, although I don't really understant the const part at the end of the public definition . However, I need to call the public method but g++ sais "tinyxml2::XMLElement::FindAttribute(const char*) is private"

How can I call the public method, and what does the const part at the end of the method prototype do?


Solution

  • Functions can be overloaded based on their constness alone. This is an important feature of C++.

    // const member function:
    const XMLAttribute* FindAttribute( const char* name ) const;
    
    // non-const member function
    XMLAttribute* FindAttribute( const char* name );
    

    In this case, the const that makes the functions different is the const following the parentheses. The const before the parenthesis does not belong to the method signature whilst the const that follows the parenthesis does. This latter use of const specifies which member functions may be called from const objects and which may not. In other words, it specifies the contract for const objects.

    If you have a const object, the const method will be called:

    const MyObject cObj;
    cObj.FindAttribute("cats");
    // const method will be called
    

    If you have a non-const object, the compiler will look for a non-const method and call it. If it does not exist, it will look for a const method and call that. The compiler works this way because it is legal to call const member functions from non-const objects, but it is illegal to call non-const member functions from const objects.

    MyObject obj;
    obj.FindAttribute("cats");
    // non-const method will be called
    // if it does not exist the compiler will look for a const version