Expecting function body despite it being provided

I have a base class called Node which defines two functions: indent and toString. The former will be used by all derived classes without overriding, however the latter will be overridden in the derived classes.

Node.hpp

#ifndef NODE_H
#define NODE_H

#include <string>
#include <vector>
#include <memory>

class Node {
    public:
        virtual std::string toString(int level) const {};
        std::string indent(int level);
};

#endif

Node.cpp

#include "Node.hpp"

std::string Node::indent(int level) {
    std::string indt;
    for(int i = 0; i < level; i++) {
        indt += "\t";
    }
    return indt;
}

I have a derived class FunctionNode which wants to override toString in node.hpp.

FunctionNode.hpp

#ifndef FUNCTION_NODE_H
#define FUNCTION_NODE_H

#include "TypeNode.hpp"
#include "ParamsNode.hpp"
#include "BlockNode.hpp"
#include "DeclarationNode.hpp"

class FunctionNode : public DeclarationNode {
    std::shared_ptr<TypeNode> type;
    std::string name;
    std::shared_ptr<ParamsNode> paramList;
    std::shared_ptr<BlockNode> block;

    public:
        FunctionNode(std::shared_ptr<TypeNode> type,
                const std::string &name,
                std::shared_ptr<ParamsNode> paramList,
                std::shared_ptr<BlockNode> block)
            : type(std::move(type)), name(name),
                paramList(std::move(paramList)), block(std::move(block)) {}
};

#endif

Note that DeclarationNode is derived from Node.

FunctionNode.cpp

#include "FunctionNode.hpp"

std::string FunctionNode::toString(int level) const override {
    std::string indt = indent(level);
    std::string s = indt + "FunctionNode\n"; 
    s += type->toString(level + 1);
    s += indt + "\t" + name + "\n";
    s += paramList->toString(level + 1);
    s += block->toString(level + 1);
    return s;
}

When I try to compile FunctionNode.cpp to an object using the following line in my Makefile.

FunctionNode.o: FunctionNode.cpp FunctionNode.hpp TypeNode.hpp ParamsNode.hpp BlockNode.hpp

I get the following error.

FunctionNode.cpp:3:55: error: expected function body after function declarator
std::string FunctionNode::toString(int level) const override {
                                                      ^

But I have provided the function body. How do I fix this error?

>Solution :

To override a function in a child class, you need to write the declaration in the class definition. The override specifier will only appear in the header file.

Header File

class FunctionNode : public DeclarationNode {
  FunctionNode(...) { ... }
  std::string toString(int level) const override; 
};

Source File

#include "FunctionNode.hpp"

std::string FunctionNode::toString(int level) const {
  ...
}

Leave a Reply