C++ : namespace conflicting declaration error - c++

I am unable to run the following code. As namesapces are different, why there are still showing errors as mentioned below?
error: conflicting declaration 'NS2::Base B'
NS2::Base B;
#include<iostream>
using namespace std;
namespace NS1
{
class Base
{
int x=4;
public:
void disp()
{
cout<<x<<endl;
}
};
}
namespace NS2
{
class Base
{
int x=7;
public:
void disp()
{
cout<<x<<endl;
}
};
}
int main()
{
NS1::Base B;
NS1:B.disp();
NS2::Base B;
NS2::B.disp();
}

Namespaces contain only what is declared inside them, in your case the two classes Base. The two objects called B however are not declared in any namespace (but are both scoped to the function main), so you get a conflicting declaration error. It doesn't matter that the associated classes where declared in different namespaces.

Just the class Base is part of namespace NS1,
B1 is just an object of type NS1::Base defined in main() not in NS1. Same goes for B2 and NS2.
Thats why you can't call function using scope resolution operator on B1.
Objects are defined in main() so you have too keep names different too
int main()
{
NS1::Base B1;
B1.disp();
NS2::Base B2;
B2.disp();
}

Related

What happens to a variable of a member function having same name as that of a private data member of the same class?

When i compile the code below i don't get any error and on debugging it initializes the class data member a of class
abc to zero. Can someone just tell me how is the compiler differentiating between the two. I dont see it happening in runtime.
//A function friendly to two classes (finding maximum of objects of 2 classes(one data member in class)
#include <iostream>
#include <conio.h>
using namespace std;
class abc; //Forward Declaration
class xyz
{
int x;
public :
void inivalue(float);
friend float max(xyz,abc);
};
class abc
{
int a;
public :
void inivalue(float);
friend float max(xyz,abc);
};
void xyz::inivalue(float y)
{
x=y;
}
void abc::inivalue(float a)
{
a=a;
}
float max(xyz m,abc n)
{
if(m.x > n.a)
return m.x;
else
return n.a;
}
int main()
{
system("cls");
xyz o1;
abc o2;
o1.inivalue(10);
o2.inivalue(20);
cout<<"The maximum of 2 classes is : "<<max(o1,o2)<<endl;
}
That's called "variable shadowing".
When you do that, the local variable a "shadows" the class variable. The compiler will use the local variable, so in the inivalue function of the class abc you're just setting the parameter value to itself.
The a member of the class is unitialized when it is used in the max and the code will result in Undefined Behaviour.

Access specifier toward scoped base method

In the following complete program:
#include <vector>
class Derived : private std::vector<int> {
public:
void f();
};
void Derived::f() {
Derived d;
d.std::vector<int>::push_back(0);
}
int main() {
Derived d;
d.f();
}
the line
d.std::vector<int>::push_back(0);
can be replaced by
d.vector<int>::push_back(0);
and the compilation would complete w/o warning both in gcc 7 and clang 6.
I don't understand why the std:: part of the scope resolution is optional, since there's no using namespace std declaration.
As others already mentioned:
Do not inherit from STL!
See this and this and read Effective c++ book.
Apart from the derivation from STL, it could be an everyday problem. I think you are searching for how qualified name lookup works.
Consider the following code
#include <iostream>
#include <string>
namespace myNamespace {
namespace nested {
class base {
protected:
std::string print() { return "Fantastic"; };
static const int four= 4;
};
}
}
class derived : private myNamespace::nested::base
{
public:
// no need to extra qualify base class methods, since derived access the scope of the base class
std::string doStuff() { return print() + std::to_string(four); };
};
int main()
{
derived d;
std::cout << d.doStuff();
}
It has the same structure, deriving from something that is a part of a namespace. As you noticed, in the derived there is no need to extra qualify the print method. However, the following is completely legal call in the doStuff method:
print();
base::print();
myNamespace::nested::base::print();
Note that simply nested::base::print(); is not legal - myNamespace should be used.
Ps. I compiled with MSVC 143, and always produced this output:
Fantastic4

Having a class member function call a function outside the class

I have a member function in class B and class D that calls the function 'computeValue' which is not a member function of any class. The 'computeValue' function performs some type of algorithm and returns a value. However it seems like I'm getting a lot of compilation errors and not sure what the underlying reasons are. Is it even possible for member functions of classes to call non-member functions?
#include<iostream>
using namespace std;
int computeValue(vector<A*>ex) //Error - Use of undeclared identifier 'A'
{
//implementation of algorithm
}
class A
{
};
class B
{
int sam2()
{
return computeValue(exampleB); // Error - No matching function for call to 'computeValue
}
vector <A*> exampleB;
};
class D
{
int sam1 ()
{
return computeValue(exampleD);// Error - No matching function for call to 'computeValue
}
vector<A*> exampleD;
};
int main()
{
}
computeValue needs the declaration of class A, so declare A before it:
class A
{
};
int computeValue(vector<A*>ex)
{
//implementation of algorithm
}
Is it even possible for member functions of classes to call non-member functions?
Of cource, yes.
Yes, definitely you can call class non-member function from class.
Here you are getting errors because of mainly two issue:
You are using vector but you haven't declared vector header file in your code.
#include<vector>
You are using class A pointer as a parameter to function "computeValue" which is defined before the class A.
So either define class A before function or use forward declaration concept.
Here is error free modified code:
#include<iostream>
#include<vector>
using namespace std;
**class A; //forward declaration of Class A**
int computeValue(vector<A*> ex) //Error - Use of undeclared identifier 'A'
{
//implementation of algorithm i
return 5;
}
class A
{
};
class B
{
int sam2()
{
return computeValue(exampleB); // Error - No matching function for call to 'computeValue
}
vector <A*> exampleB;
};
class D
{
public:
D()
{
cout<<"D constructor"<<endl;
}
int sam1 ()
{
return computeValue(exampleD);// Error - No matching function for call to 'computeValue
}
vector<A*> exampleD;
};
int main()
{
D d;
}
This code will give you output: "D constructor"
I hope this will help you.

Why is it not possible to define a fully-qualified function within a foreign namespace? May I know what the standard says?

Is this is wrong? Why? May I know what the standard says?
namespace N{
namespace N1{
namespace N2{
struct A{
struct B{
void fun();
};//B
}; //A
} //n2
}//n1
namespace N3{
void N1::N2::A::B::fun(){} //error
}//n3
}//n
int main()
{
return 0;
}
May I know why it is failing?
This is invalid due to ยง9.3/2:
A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition.
The scope of the namespace N3 does not enclose the definition of the class B
Here is a much simpler example, that also fails to compile:
namespace N1 {
void f() ;
}
namespace N2 {
void N1::f() { }
}
To put the answer in plain English, the definition of a function or method which belongs to a class (or struct) needs to be in the same namespace as the class definition. In other words, you can't declare the function in one namespace and then define it in another.

Local Classes in C++

I am reading "Local Classes" concept in Object-oriented programming with C++ By Balagurusamy (http://highered.mcgraw-hill.com/sites/0070593620/information_center_view0/).
The last line says "Enclosing function cannot access the private members of a local class. However, we can achieve this by declaring the enclosing function as a friend."
Now I am wondering how the highlighted part can be done?
Here is the code I was trying but no luck,
#include<iostream>
using namespace std;
class abc;
int pqr(abc t)
{
class abc
{
int x;
public:
int xyz()
{
return x=4;
}
friend int pqr(abc);
};
t.xyz();
return t.x;
}
int main()
{
abc t;
cout<<"Return "<<pqr(t)<<endl;
}
I know the code looks erroneous, any help would be appreciable.
Your friend statement is fine.
int pqr() {
class abc {
int x;
public:
abc() : x(4) { }
friend int pqr();
};
return abc().x;
}
int main() {
cout << "Return " << pqr() << endl;
}
Edit:
IBM offers this explanation for the issue raised in the comments:
If you declare a friend in a local class, and the friend's name is unqualified, the compiler will look for the name only within the innermost enclosing nonclass scope. [...] You do not have to do so with classes.
void a();
void f() {
class A {
// error: friend declaration 'void a()' in local class without prior decl...
friend void a();
};
}
friend void a(): This statement does not consider function a() declared in namespace scope. Since function a() has not been declared in the scope of f(), the compiler would not allow this statement.
Source: IBM - Friend scope (C++ only)
So, you're out of luck. Balagurusamy's tip only works for MSVC and similar compilers. You could try handing off execution to a static method inside your local class as a work-around:
int pqr() {
class abc {
int x;
public:
abc() : x(4) { }
static int pqr() {
return abc().x;
}
};
return abc::pqr();
}
There seems to be a misunderstand about local classes.
Normally there are here to help you within the function... and should NOT escape the function's scope.
Therefore, it is not possible for a function to take as an argument its own local class, the class simply isn't visible from the outside.
Also note that a variety of compilers do not (unfortunately) support these local classes as template parameters (gcc 3.4 for example), which actually prevents their use as predicates in STL algorithms.
Example of use:
int pqr()
{
class foo
{
friend int pqr();
int x;
foo(): x() {}
};
return foo().x;
}
I must admit though that I don't use this much, given the restricted scope I usually use struct instead of class, which means that I don't have to worry about friending ;)
I have no solution for the friend thing yet (don't even know if it can be done), but read this and this to find out some more about local classes. This will tell you that you cannot use local classes outside the function they are defined in (as #In silico points out in his answer.)
EDIT It doesn't seem possible, as this article explains:
The name of a function first introduced in a friend declaration is in the scope of the first nonclass scope that contains the enclosing class.
In other words, local classes can only befriend a function if it was declared within their enclosing function.
The friend int pqr(abc); declaration is fine. It doesn't work because the abc type has not been defined before you used it as a parameter type in the pqr() function. Define it before the function:
#include<iostream>
// By the way, "using namespace std" can cause ambiguities.
// See http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5
using namespace std;
// Class defined outside the pqr() function.
class abc
{
int x;
public:
int xyz()
{
return x=4;
}
friend int pqr(abc);
};
// At this point, the compiler knows what abc is.
int pqr(abc t)
{
t.xyz();
return t.x;
}
int main()
{
abc t;
cout<<"Return "<<pqr(t)<<endl;
}
I know you want to use a local class, but what you have set up will not work. Local classes is visible only inside the function it is defined in. If you want to use an instance of abc outside the pqr() function, you have to define the abc class outside the function.
However, if you know that the abc class will be used only within the pqr() function, then a local class can be used. But you do need to fix the friend declaration a little bit in this case.
#include<iostream>
// By the way, "using namespace std" can cause ambiguities.
// See http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5
using namespace std;
// pqr() function defined at global scope
int pqr()
{
// This class visible only within the pqr() function,
// because it is a local class.
class abc
{
int x;
public:
int xyz()
{
return x=4;
}
// Refer to the pqr() function defined at global scope
friend int ::pqr(); // <-- Note :: operator
} t;
t.xyz();
return t.x;
}
int main()
{
cout<<"Return "<<pqr()<<endl;
}
This compiles without warnings on Visual C++ (version 15.00.30729.01 of the compiler).