Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes and namespaces sharing the same name in C++

Let's say I have a class called 'foo' in namespace "abc"...

namespace abc {
     class foo {
         int a;
         int b;
     };
}

...and then say I have another class called "abc" in a different namespace

#include "foo.h"

namespace foo {
    class abc {
        abc::a = 10;
    };
}

abc::a would not be a defined type, because it would be searching class abc, not namespace abc. How would I go about properlly referencing an object in another namespace, wherein that other namespace had the same name as the class I'm in?

like image 785
Monster Avatar asked Nov 01 '10 16:11

Monster


People also ask

Can namespace and class have same name?

Inside a namespace, no two classes can have the same name.

Can a class and a namespace have the same name C++?

To clarify this answer: anything can have the same name as anything else if they are in different namespaces; a class cannot have the same name as a namespace if they are both in the same namespace.

Is namespace and class the same?

Classes are basically extended version of structures. Classes can contain data members and functions as members, but namespaces can contain variables and functions by grouping them into one. The namespaces cannot be created as objects.

Can two namespace have same name?

namespace definitionMultiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.


1 Answers

You can use ::abc::xx, that is, identify the variable or type as its absolute namespace path. If you don't specify an absolute name, relative names start going upwards in the including namespaces/classes.

like image 181
Diego Sevilla Avatar answered Oct 05 '22 12:10

Diego Sevilla