Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaring classes in namespaces

I was rather surprised to learn that I couldn't forward declare a class from another scope using the scope resolution operator, i.e.

class someScope::someClass;

Instead, the full declaration has to be used as follows:

namespace
{
    class someClass;
}

Can someone explain why this is the case?

UPDATE: To clarify, I am asking why this is the case.

like image 355
Konrad Avatar asked Jul 19 '10 09:07

Konrad


3 Answers

You can't declare a class outside its namespace, because the compiler could not be aware of the type of someScope.

namespace{ } is required to declare the existence of namespace, and then, declare class someClass into your scope.

like image 79
Doomsday Avatar answered Sep 21 '22 23:09

Doomsday


Seems as though the answer lies in the C++ specification:

3.3.5 "Namespace scope" in the standard.

Entities declared in a namespace-body are said to be members of the namespace, and names introduced by these declarations into the declarative region of the namespace are said to be member names of the namespace.

A namespace member can also be referred to after the :: scope resolution operator (5.1) applied to the name of its namespace or the name of a namespace which nominates the member’s namespace in a using-directive;

like image 27
Konrad Avatar answered Sep 17 '22 23:09

Konrad


I am not sure why. Maybe because, in your first code snippet, someScope is undeclared. It can be a namespace, or a class name. If someScope is a class name, you can't independently forward declare a class member of another class.

like image 42
Cătălin Pitiș Avatar answered Sep 18 '22 23:09

Cătălin Pitiș