How to forward declare class which is in unnamed namespace

My question is how to declare class which will be defined in unnamed namespace in .cpp file

You cannot. The unnamed namespace is explicitly meant to be privately visible for the current translation unit it appears in, and cannot be used for forward declarations inherently.

You're probably be better off using the pimpl idiom, if you want to hide implementation details.


Another popular approach is using an internal_ namespace, and document it's not meant for public usage:

namespace calculators {
namespace internal_ {
    struct PrevCalc{
        double prevA = -1;
        double prevB = -1;
        double prevC = -1;
    };
}

class Calculator {
public:
    Calculator();
private: // !!!!
    internal_::PrevCalc* prevCalc;
};
}

You could also use a nested class ?

#ifndef CALCULATOR_H
#define CALCULATOR_H

class Calculator {
public:
    Calculator();
    ~Calculator(); // need an explicit destructor to use std::unique_ptr<>
private:
    struct PrevCalc;
    std::unique_ptr<PrevCalc> prevCalc;
};

#endif // CALCULATOR_H

in .cc file

#include "calculator.h"

struct Calculator::PrevCalc{
  double prevA = -1;
  double prevB = -1;
  double prevC = -1;
};

Calculator::Calculator():
  prevCalc(std::make_unique<PrevCalc>())
{}

Calculator::~Calculator(){}

Tags:

C++