EN VI

C++ - Added a base struct breaks overloading?

2024-03-13 11:30:04
How to C++ - Added a base struct breaks overloading

I'm working on a compiler for a toy language and I created a struct to hold the result of the lexing step. Now I want to create a struct to hold the result from the parser so I thought I would create a base struct since they both hold warnings and error but one has tokens and one has statements. This is what my structs look like.

struct Result {
    std::vector<Warning> warnings;
    std::vector<Error> errors;

    void add(Warning warning) { warnings.push_back(warning); }
    void add(Error error) { errors.push_back(error); }
    
    bool hasWarnings() { return warnings.size() > 0; }
    bool hasErrors() { return errors.size() > 0; }
};

struct LexerResult : public Result {
    std::vector<Token> tokens;
    
    void add(Token token) { tokens.push_back(token); }
};

In the part of the code where I was adding errors it looked like this.

result.add(Error { loc, "Unknown token" });

But after the change to the structs I get this error.

moo_compiler/lexer/lexer.cpp:272:36 No viable conversion from 'Warning' to 'Token'

When I rely on the code autocomplete it wants this.

result.Result::add(Error { loc, "Unknown token" });

but I can't fathom why.

Solution:

If you define a function in a derived class it completely hides any function in the base class with the same name in the derived class's namespace.

That means that the add member function in your LexerResult hides the add member functions from Result.

To bring the functions from the base class back into the namespace of the derived class you can use the using keyword:

struct LexerResult : public Result {
    std::vector<Token> tokens;

    using Result::add;    
    void add(Token token) { tokens.push_back(token); }
};

Demo

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login