Search code examples
c++access-violation

Read Access Violation when trying to return member string from () operator


I have a class with the member variable wchar_t m_var[MAX_PATH];

I am trying to return it using the overloaded operator wchar_t* operator()(). Also tried const wchar_t* just in case. Inside there is simply a return m_var;, but unfortunately I always get a read access violation.

When I simply write MyClass.m_var, it works perfectly.

I am getting that error trough the code printf("%ws", MyClass);, but not printf("%ws", MyClass.m_var);

#include <cstdio>

class MyClass {
public:
    MyClass() { random_op(); }
    ~MyClass() {}
    void random_op() {
        for(int i = 0; i <= 11; i++) {
            m_var[i] = 'A';
        }
        m_var[12] = '\0';
    }
    wchar_t* operator()() { return m_var; }
    wchar_t m_var[255];
};

int main() {
    MyClass c;
    printf("%ws", c);
}

Why is this happening?


Solution

  • I think there's two mistakes here.

    First I think you are trying to write a conversion operator. The correct syntax for that is

    operator wchar_t *() {
    

    not

    wchar_t * operator()() {
    

    Second mistake is that normal type conversions don't apply when calling printf (and similar) beccause there is no way for the compiler to know what types are expected.

    So this code would work (but untested).

    #include <iostream>
    
    class MyClass {
    public:
        MyClass() { random_op(); }
        ~MyClass() {}
        void random_op() {
            for(int i = 0; i <= 11; i++) {
                m_var[i] = 'A';
            }
            m_var[12] = '\0';
        }
        operator wchar_t* () { return m_var; }
        wchar_t m_var[255];
    };
    
    int main() {
        MyClass c;
        std::wcout << c;
    }