lm2s
lm2s

Reputation: 388

Curiosity about namespace and function parameters

one.h:

namespace one {
    class X : public IZ {
        public:
            void function(); // virtual function (=0) in IZ
    }
}

two.h

namespace one {
    class Y {
        public:
            void functionY(class X& x); // or one::X& x
    }
}

I have several classes distributed by several files, all sharing the same namespace. From what I've understood, if I have the same namespace for all classes, they all can access each other without the need to put NAMESPACE::class_x since they all belong to the same namespace.

What I'd like to understand is why in the special case above described there's the need to use the keyword class or namespace:: before X& x.

Is it related to X inheritance of IZ which as a virtual function then "overwritten" in X?

Upvotes: 0

Views: 130

Answers (3)

lm2s
lm2s

Reputation: 388

To close the question: the problem was caused by circular referencing.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477494

Namespace or not, you need to declare a class which you want to refer to later.

You can either #include "one.h" in your file two.h to make the entire definition of one::X known, or you can just add a declare X without defining it:

// two.h

namespace one
{
    class X;

    class Y
    {
        void f(X const & x);
        // ...
    };
}

In either case, you don't need to restate the namespace since you're already inside it.

Upvotes: 1

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

In this case the X type is resolved in compile time. The linker needs to understand what X is and it is a class or it is scoped in a namespace.

  1. If you scope it to be in the same namespace namespace::x then you would get a compile error if the class is not defined in the namespace.
  2. If you define it to be a class and the same class exists in the namespace the definition belongs to, then that definition would be resolved.

Upvotes: 1

Related Questions