#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
class div
{
int x,y;
public:
class dividebyzero
{
};
class noerror1
{
};
div(){};
div(int a,int b)
{
x=a;
y=b;
}
void error1()
{
if(y==0)
throw dividebyzero();
else
throw noerror1();
}
int divide()
{
return (x/y);
}
};
class naming
{
char name[32];
public:
class nullexception
{
};
class noerror2
{
};
naming(char a[32])
{
strcpy(name,a);
}
void error2()
{
if(strcmp(name,"")==0)
throw nullexception();
else
throw noerror2();
}
void print()
{
cout<<"Name-----"<<name<<endl;
}
};
int main()
{
div d(12,0);
try
{
d.error1();
}
catch(div::dividebyzero)
{
cout<<"\nDivision by Zero-------Not Possible\n";
}
catch(div::noerror1)
{
cout<<"\nResult="<<d.divide()<<endl;
}
naming s("Pankaj");
try
{
s.error2();
}
catch(naming::nullexception)
{
cout<<"\nNull Value in name\n";
}
catch(naming::noerror2)
{
s.print();
}
return 0;
}
On compiling this program I am getting following error
pllab55.cpp: In function ‘int main()’:
pllab55.cpp:61:6: error: expected ‘;’ before ‘d’
pllab55.cpp:64:3: error: ‘d’ was not declared in this scope
pllab55.cpp:72:22: error: ‘d’ was not declared in this scope
pllab55.cpp:74:20: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
Before declaring the class naming everything was running fine.It is after declaration of naming these error started to occur. I am new to C++. Please explain me in details. Thanks in advance.
There is already an std::div in the standard namespace and since you use a using namespace directive instead of declaration it imports all the symbols in std namespace to your current scope. So perhaps renaming the div class shall do the trick for you.
I tried renaming it and it does work indeed.
So either rename your class or wrap it in your own namespace so it does not conflict with std::div
Your class div shares the same name as std::div. When you do #using namespace std, the result is that each class in the std namespace is imported into your current scope, meaning that std::div is now essentially called div. If you see, that means you now have two classes called div in the same scope, your own and the std class.
By the way, you should avoid the using namespace syntax and rather use the full qualifier of the class (e.g. std::cout).
Your div class is conflicting with std::div so either rename yours or put put your div class in a different namespace.
namespace me {
struct div{};
}
me::div d;
I gave (a slight variant of) your code a try in gcc and I got the following error:
/usr/include/stdlib.h:780: error: too few arguments to function 'div_t div(int, int)'
You're trying to override a name from a standard library and experience the conflict of a class and a function having the same name, I'm afraid.
as a general rule of thumb, if you encounter such issues, try to reduce your code as much as possible. For instance, I reduced it down to
#include<stdlib.h>
class div {
public:
div (int a, int b) { }
};
int
main () {
div d (12, 0);
return 0;
}
which still shows your error (at least the first one - the others are followup errors).
This lets you also reduce possible assumptions about the reason for the error - as you see, your new class "naming" does not have to do anything with the error you see.
When I now additionally remove the include, the error does not show up anymore, which lets me suspect some naming clash with some symbol from stdlib.h. After renaming the class "div" to something else (like "CDiv"), it works.
Related
Why am I am getting an "expected identifier" error before .token?
Please provide a solution to understand friend function properly.
At first, I am getting a forward declaration error, but I resolved that one by myself.
#include<iostream>
using namespace std;
class a;
class b
{
public:
void search(a and);
};
class a
{
string name;
friend void b::search(a and);
public:
};
void b::search(a and)
{
cout << and.name;
}
int main()
{
}
For compatibility with old keyboards and encoding schemes where some symbols weren't available, certain keywords can be used in place of symbols. Among them, and is a valid replacement for &&. So your and.name is actually getting parsed as &&.name, which is a syntax error.
The (unfortunate) solution to your problem is: Don't name variables and or any of the other words on that list.
This is a follow-up question from: constructing string from NULL?
The following:
void test(const std::string& s);
int main(){
test(NULL);
}
Fails when run, but is legal c++.
In order to try to catch some of those cases, as an alternative ive considering if std::string can be replaced in the following way:
#include <string>
namespace {
namespace std {
struct string : public ::std::string { //so far everything is good
};
}
}
int main ()
{
std::string hello;//failure: ambiguous symbol
return 0;
}
Gives the following error:
<source>(17): error C2872: 'std': ambiguous symbol
C:/data/msvc/14.22.27905/include\string(19): note: could be 'std'
<source>(7): note: or '`anonymous-namespace'::std'
<source>(17): error C2872: 'std': ambiguous symbol
C:/data/msvc/14.22.27905/include\string(19): note: could be 'std'
<source>(7): note: or '`anonymous-namespace'::std'
Compiler returned: 2
I guess it is not possible to make it resolve without writing a more (fully) qualified name ? but is it possible to write std::string in the global namespace and have it resolve to something else while ::std::string is a valid type.
Background: after some failed attempts with cppcheck and cpp core check im trying to find all cases of std::string str = 0 or NULL or nullptr - since those will fail at runtime. And I thought this might be a way forward.
I ended up modifying the basic_string template ala. basic_string(int) = delete;
basic_string(::std::nullptr_t) = delete; - this won't catch all cases but does indeed seem to catch the direct cases at least
Resolve std::string to something else than ::std::string - is it possible?
[...]
...as an alternative ive considering if std::string can be replaced in the following way...
As far as I know, it is not possible outside of your anonymous namespace scope because you have no way to resolve the ambiguity (not to my knowledge).
As you can see below, since you are inside the scope of the anonymous namespace, it will be fine:
#include <string>
namespace
{
namespace std
{
struct string : public ::std::string
{
};
}
std::string hello; // Fine
}
int main()
{
std::string hello2; // Cannot be something else that ambiguous
return 0;
}
But even worse, the problem is not about std::string itself but about the std namespace.
Indeed, outside of the scope of your anonymous namespace, every call of std becomes ambiguous too.This is the error pointed by the compiler. There are two std namespaces accessible as is from the global scope.
So the following example becomes broken:
#include <string>
#include <vector>
namespace
{
namespace std
{
struct string : public ::std::string
{
};
}
std::string hello; // Fine
}
int main()
{
std::vector<int> a; // FAIL: reference to 'std' is ambiguous
return 0;
}
To fix this ambiguity over accessing the original std namespace, you'll need to write it as follows:
::std::vector<int> a; // Fully qualified name: Only way to refer to the `::std` namespace
As you can see, it still does not solve the issue and even worse, it adds a huge inconvenience.
Therefore the morality is:
Do not hide an already existing type but create a distinct one instead.
In the same way, do not hide a namespace (by defining the same namespace into an anonymous one --> evil).
(I'm open to any improvement proposal of this answer)
Could you use this kind of solution : Rather than working on std::string, you work on the function that will cause the problem
#include <string>
void test(const std::string& s){
}
// add a new function which use a pointer :
void test (const char* _Nonnull s) {
test(std::string(s));
}
int main()
{
test(NULL);
return 0;
}
Then clang will generate a warning :
1 warning generated.
ASM generation compiler returned: 0
<source>:13:14: warning: null passed to a callee that requires a non-null argument [-Wnonnull]
test(NULL);
see https://godbolt.org/z/PujFor
I'm trying to get a reference to my class but it seems to is not declared.
This means it's undeclared:
#include <iostream>
using namespace std;
class time
{
private:
int sec;
int mins;
int hours;
public:
void setSeconds(int x)
{
sec = x;
}
int getSeconds()
{
return sec;
}
};
int main()
{
time to;
to.setSeconds(10000000);
cout << to.getSeconds() << endl;
return 0;
}
The error reads:
main.cpp: In function 'int main()':
main.cpp:29:10: error: expected ';' before 'to'
time to;
^
main.cpp:29:12: warning: statement is a reference, not call, to function 'time' [-Waddress]
time to;
^
main.cpp:29:12: warning: statement has no effect [-Wunused-value]
main.cpp:30:5: error: 'to' was not declared in this scope
to.setSeconds(10000000);
^
std::time is a function in the C++ standard library and, since you're using namespace std, that's being used by default instead of your class.
You can't even write ::time to reference yours, because your compiler's standard library implementation happens to include the old C ::time as well before wrapping it into namespace std.
Use some or all of these suggestions:
give your class a better, more unique name
write class time to reference your class (this ensures the type time is used, but is a poor hack)
use a namespace yourself to avoid all future ambiguities (this is recommended)
You should also stop using namespace std in general to help avoid as much trouble as possible, though it cannot directly aid you in this case.
Clang give a better error message:
time.cpp:29:5: error: must use 'class' tag to refer to type 'time' in this scope
time t;
^
class
/usr/include/time.h:192:15: note: class 'time' is hidden by a non-type declaration of 'time' here
extern time_t time (time_t *__timer) __THROW;
^
It isn't related to using namespace std. Rather the global time function is conflicting.
Is there any difference between wrapping both header and cpp file contents in a namespace or wrapping just the header contents and then doing using namespace in the cpp file?
By difference I mean any sort performance penalty or slightly different semantics that can cause problems or anything I need to be aware of.
Example:
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
namespace X
{
void Foo::TheFunc()
{
return;
}
}
VS
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
using namespace X;
{
void Foo::TheFunc()
{
return;
}
}
If there is no difference what is the preferred form and why?
The difference in "namespace X" to "using namespace X" is in the first one any new declarations will be under the name space while in the second one it won't.
In your example there are no new declaration - so no difference hence no preferred way.
Namespace is just a way to mangle function signature so that they will not conflict. Some prefer the first way and other prefer the second version. Both versions do not have any effect on compile time performance. Note that namespaces are just a compile time entity.
The only problem that arises with using namespace is when we have same nested namespace names (i.e) X::X::Foo. Doing that creates more confusion with or without using keyword.
There's no performance penalties, since the resulting could would be the same, but putting your Foo into namespace implicitly introduces ambiguity in case you have Foos in different namespaces. You can get your code fubar, indeed. I'd recommend avoiding using using for this purpose.
And you have a stray { after using namespace ;-)
If you're attempting to use variables from one to the other, then I'd recommend externalizing them, then initializing them in the source file like so:
// [.hh]
namespace example
{
extern int a, b, c;
}
// [.cc]
// Include your header, then init the vars:
namespace example
{
int a, b, c;
}
// Then in the function below, you can init them as what you want:
void reference
{
example::a = 0;
}
If the second one compiles as well, there should be no differences. Namespaces are processed in compile-time and should not affect the runtime actions.
But for design issues, second is horrible. Even if it compiles (not sure), it makes no sense at all.
The Foo::TheFunc() is not in the correct namespacein the VS-case. Use 'void X::Foo::TheFunc() {}' to implement the function in the correct namespace (X).
In case if you do wrap only the .h content you have to write using namespace ... in cpp file otherwise you every time working on the valid namespace. Normally you wrap both .cpp and .h files otherwise you are in risk to use objects from another namespace which may generate a lot of problems.
I think right thing to do here is to use namespace for scoping.
namespace catagory
{
enum status
{
none,
active,
paused
}
};
void func()
{
catagory::status status;
status = category::active;
}
Or you can do the following:
// asdf.h
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
Then
// asdf.cpp
#include "asdf.h"
void X::Foo::TheFunc()
{
return;
}
I'm learning C++ now. What are the complete legal entities that can be put in a namespace?
Legal entities here means valid members of a namespace
Oh, this is a real question. I'm coming from .net and I have the .net mindset.
Any code can be put inside namespace.
However main() function must be at global namespace. It cannot be put inside user-defined namespace.
namespace userns
{
int main()
{
return 0;
}
}
This program wouldn't compile link : http://www.ideone.com/k6SPc
Its because userns::main() will not be considered entry-point of the program; it became just like any other user function, not the standard main(). To compile it successfull, you've to add main() at global namespace:
namespace userns
{
int main()
{
return 0;
}
}
int main()
{
return 0;
}
This will compile link now : http://www.ideone.com/76Ynu
Anything can be put in a namespace (which is legal for C++, of course).
Actually, everything is in some namespace - the global namespace, if not specified.
Everything can be put in namespace except few "entities", which will not compile.
(1) Globally overloaded operator new and operator delete
namespace N
{
void* operator new (size_t size) // error
{ ... }
}
(2) Definition of the constructs which are declared in outer scope of the namespace; for example you have a class A declared globally then you cannot define its method inside your namespace N. In the same way, if you have method declared in a namespace N then you cannot put its definition inside namespace N::Nested (i.e. Nested is a namespace inside N).
//file
struct A {
void foo ();
static int i;
};
namespace N
{
int A::i = 0; // error
void A::foo() // error
{}
}
Demo: this is not allowed.
I remember at least these 2 restrictions from my experience. Don't know about specs.