Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

forward declaration of std::ostream

The files are organized as following:

//MyClass.h
#pragma once
namespace std {
    class ostream;
};
class MyClass
{
private:
    int a;
public:
    friend std::ostream& operator<<(std::ostream& o, const MyClass& obj);
};
//MyClass.cpp
#include<iostream>
std::ostream& operator<<(std::ostream& o, const MyClass& obj)
{
    o << obj.a << std::endl;
    return o;
}
//main.cpp
#include"MyClass.h"
#include<iostream>

int main()
{
    MyClass obj;
    std::cout << obj;
}

It failed compiling with errors on overloading operator<<:

Error C2371 ‘std::ostream’: redefinition; different basic types

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What’s the issue here and how to correct it?

>Solution :

As other people noted, ostream is not a class but an alias to a template instantiation, basically ostream = basic_ostream<char>. This is an implementation detail of the standard library; it’s there because it needs to support also wostream (which is basic_ostream<wchar_t>) and possibly other stream types. But other implementations may do it differently (using e.g. source code generation) or very differently (distributing pre-compiled modules). You should not depend on any particular implementation.


You should not declare anything inside the std namespace (except stuff which the C++ Standard explicitly permits). To forward-declare ostream and such, use #include <iosfwd> in your header file.

Alternatively, just do #include <iostream> instead of forward declaration — less technical details to remember vs slightly slower compilation — do your own judgment on what is better.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading