A couple of basic questions regarding "Hello World" - c++

So I just started teaching myself C++ and I have two newbie questions regarding the Hello World exercise.
#include <iostream>
using namespace std; [1]
int main()
{
cout << "Hello, World" << endl; [2]
return 0;
}
[1] Is this line of code necessary? If not, why? It worked without it but I found a source that used it and was wondering why was this used.
[2] On my first try I forgot to add endl and the code worked. When I went to check I realised this was missing so why did it still work anyway?
Really basic questions but I want to understand the basics well.
Many thanks in advance.

Is this line of code necessary? If not, why? It worked without it but I found a source that used it and was wondering why was this used.
Namespace
First of all you should have to understand what a namespace is.
That's an argument reference:
Namespace.
Pratically a namespace is like a container. You can keep different
symbol's names. In that way, in very large project, it is possible define two different symbols (e.g two functions) with the same name.
I try to give you a little example:
I can define two different functions foo with the same name. It possibile because I put them inside two different namespaces.
namespace my_ns1 {
void foo(int a) {
return a;
}
}
namespace my_ns2 {
void foo(int a) {
return a + 2;
}
}
When I want to call the first foo function the proper invokation
will be:
my_ns1::foo(10); // return 10
If i want to call the second foo function, then:
my_ns2::foo(10); // return 12
In a specific block I can specify the intent to use always a namespace
with the code:
using namespace my_ns1;
In that way there is no more need to specify the "full name" of the function.
The standard library keeps all its function in a proper namespace: std.
So when you want to use a function in the standard library you have to invoke it with something like:
std::function(...)
If you use the code
using namespace std;
At the begin of your file, you're just saying to "open" that namespace
and you can call all function without std::
The namespace is usefull in order to prevent name conflict.
[2] On my first try I forgot to add endl and the code worked. When I went to check I realised this was missing so why did it still work anyway?
Simply
std::endl
is a proper way to insert the '\n' character which means "an end of line".

Related

Is there a way to reference cout without using namespace std or prefixing with std::?

I'm pretty new to C++, and I'm using std::cout for debugging purposes.
Though, I'd really like to be able to just use cout rather than the whole std::cout thing. I know i could import the std namespace, but I've been explained it was a bad thing due to name clashing that can occur because of this.
Is there anyway to do this?
I tried
std::ostream cout = std::cout;
But I get
function "std::basic_ostream<_CharT, _Traits>::basic_ostream(const std::basic_ostream<_CharT, _Traits> &) [with _CharT=char, _Traits=std::char_traits<char>]" (declared at line 391 of "/usr/include/c++/5/ostream") cannot be referenced -- it is a deleted function
Please suggest.
Sure, with a using declaration:
using std::cout;
Usual health warnings about not doing this in header files, and limiting it to small scopes apply.
You can't copy streams (think about it, it just doesn't make sense), but you can get a reference to them:
std::ostream& my_cout = std::cout;
However, I would strongly advice you not to do so. If you see in some code std::cout you can be almost 100% certain that you know what it is. On the other hand a cout alone you should already look suspicious to you and a my_cout could really be anything. I know it is hard, but get used to type std::, on the long run it will help you more than you need time to type those 5 letters.
Your way would be:
auto& cout = std::cout;
but you might simply do
using std::cout;
(with similar restriction than using namespace: not in namespace scope in header, ideally limiting the scope of using directive as much as possible)
Sorry, too low rating to comment, but why don't you just type
using std::cout;
at the top of the file and then just use cout.
P.S. also answered at this post
One way is using-declaration, which introduces only std::cout instead of all names in std:::
using std::cout;
The way you tried won't work - it's an attempt to copy std::cout to another object - and std::cout is not copyable.
Alternative is to use a reference:
std::ostream& cout = std::cout;
Now, cout points to std::cout instead of being its copy.
The second way can be useful, if you want to, for example, write a function without deciding whether it should output to cout, file or something else:
void func(std::ostream& output) {
output << "works with cout, files, etc.";
}
If you're looking to abbreviate std::cout, it could be that what you are really looking for is dependency injection.
Remember that std::cout is a reference to a model of a std::ostream.
We can use that in our favour to make code more re-usable, testable and loosely coupled.
example:
#include <iostream>
#include <sstream>
std::ostream& do_something(std::ostream& os)
{
os << "Hello, World!\n";
return os;
}
int main()
{
// inject std::cout
do_something(std::cout);
// inject a stringstream
std::ostringstream ss;
do_something(ss);
std::cout << ss.str();
}

Linkage between files - how exactly does it work?

So I've been reading about this but couldn't find anything that'd explain the behavior of this code below to me:
header.hpp:
class TESTING{
private:
int num;
public:
TESTING(int);
};
void testing(int, int);
def.cpp:
#include "header.hpp"
#include <iostream>
using namespace std;
TESTING::TESTING(int num = 100){
this->num = num;
cout << "init with: " << this->num << endl;
}
void testing(int a = 500, int b = 200){
cout << "a: " << a << ", b: " << b << endl;
}
int main(){
TESTING test1;
TESTING test2(5);
testing();
testing(1);
testing(1, 2);
}
So far so good and working as intended, the output then is:
init with: 100
init with: 5
a: 500, b: 200
a: 1, b: 200
a: 1, b: 2
But then when I cut the "int main" function and paste it into the following Main.cpp below
Main.cpp:
#include "header.hpp"
int main(){
//TESTING test1;//error: assumed to be default constructor
TESTING test2(5);
//testing();//error: too few arguments
//testing(1);//error: too few arguments
testing(1, 2);
}
I'd get the errors mentioned in the comments above but still the output:
init with: 5
a: 1, b: 2
Which then means that it does link itself to def.cpp but with some sort of minimum visibility(?).
Why's this happening?
The purpose of this Main.cpp file is to have the main function that'll run all the other c++ files in that project, is there a general better way to achieve that than the way I tried? If so, does that way apply to the code mentioned here? Or is my code just written badly?
P.S: I'm new to c++, please be gentle :d
Default arguments don't magically transfer across source files. Think about it - how is the compiler processing main.cpp supposed to know that, in a different source file, you gave default arguments to some parameters?
Formally, default arguments are specific to any given scope:
8.3.6/4 For non-template functions, default arguments can be added in later declarations of a function in the same scope. Declarations in
different scopes have completely distinct sets of default arguments...
Even in the same source file, you can declare the same function to have different default arguments in different scopes. The compiler would happily substitute whatever default arguments, if any, are specified by the declaration visible in the current scope.
On an unrelated note, the word "linkage" is a term of art - it has a very specific meaning in C++. This notion of linkage is largely irrelevant to your question, at least insofar as it relates to default arguments (I just point it out for the benefit of readers who might be confused by the question's title). The set of default arguments is not part of the function name or signature, and doesn't affect its linkage, its ability to be used across scopes and translation units.

not1 was not declared in this scope

I was following some information from this: How to find the first character in a C++ string
When I tried to implement it into my code, I got the error not1 was not declared in this scope.
void ASTree::indent(int ind, int inc) {
std::string theText;
for (std::vector<ASTree*>::const_iterator i = child.begin(); i != child.end(); ++i) {
switch ((*i)->nodeType) {
case category:
(*i)->indent(ind + inc, inc);
break;
case token:
{
//out << std::setw(indent) << " ";
theText = (*i)->text; // << std::endl;
std::string::iterator firstChar = std::find_if(theText.begin(), theText.end(), std::not1(std::isspace));
theText.erase(theText.begin(), firstChar);
(*i)->text = theText;
}
break;
case whitespace:
//out << (*i)->text;
break;
}
}
}
I'm somewhat new to C++ and working on these projects for in class.
Have you included this header:
#include <functional>
Also, use std::not1, not just not1, for it is defined in std namespace.
I hope you've not written using namespace std in your code, which is a bad idea anyway.
Alright after reading this comment by you:
get yet another error. :) no matching function for call to ânot1(<unresolved overloaded function type>)â I also updated the code above to show you my current
I guess there is another function with name isspace is present in std namespace, which is causing the problem while resolving the names.
So here are two solutions. Try one by one:
Use just ::isspace. Without using std. Just ::isspace. See if it works!
Or, cast explicitly to help the compiler in selecting the desired overload, as
std::not1(((int)(*)(int))(std::isspace));
Since the casting looks very clumsy, you can use typedef also, as:
//define this inside the function, or outside the function!
typedef int (*fun)(int);
//then do this:
std::not1((fun)(std::isspace))
I hope this should help you.
A similar problem has been seen before, see this:
"Unresolved overloaded function type" while trying to use for_each with iterators and function in C++
To use std::not1 you need to #include <functional>, also you need to prefix it with the namespace properly (if you don't have a using directive):
std::string::iterator firstChar = std::find_if(
theText.begin(),
theText.end(),
std::not1(isspace));

Namespaces and scope visibility issue

I made a header file sampleheader.h with following code:
namespace sample_namespace
{
int add(int n1,int n2)
{
return (n1 + n2);
}
}
Now my main.cpp file is:
#include <iostream>
#include "sampleheader.h"
using namespace std;
int add(int n1, int n2)
{
return (n1 + n2);
}
int main(void)
{
using namespace sample_namespace;
//cout<<add(5,7);
}
The project is built with no warning if i leave that line commented.It is understandable because the local add() function is defined in the global scope and add() function is made visible in the scope of main(). So no name conflict happens.
However, if I remove the comments, I get the following error:
"Ambiguous call to overloaded function"
First of all there should be no name conflict at all as explained by me above (if I'm right). But, if at all there is a name conflict why is it that it is notified by compiler only when I call the function. Such type of error should be shown as soon as a name conflicts (if at all).
Any help is appreciated.
Well, you explained it yourself.
When you have both int add() and int sample_namespace::add() in scope, the call is ambiguous. The statement add() could mean either of them.
There is no conflict in the functions co-existing because one is int add() and the other is int sample_namespace::add(). This is the entire purpose of namespaces.
You just have to be clear when you write code that uses them. If you get rid of your using namespace directives and always write explicit code, then you won't run into a problem:
#include <iostream>
namespace sample_namespace {
int add(int n1, int n2) {
return (n1 + n2);
}
}
int add(int n1, int n2) {
return (n1 + n2);
}
int main() {
std::cout << sample_namespace::add(5,7);
}
(Also, defining non-inline functions in headers is A Bad Idea™.)
"using namespace" does not hide other implementations. What it does in this case is make it ambiguous.
You have both sample_namespace::add and ::add with the same signature. Since you don't explicitly say which one to use, the compiler can't tell.
Declaring both functions is legal and unambiguous (which is why the compiler only complains when you use the function).
The reason why it's legal to declare both functions like that is because you can call both unambiguously, by qualifying them. That's why you get an error only when you make an unqualified call. Up to that point, there is not even a theoretical problem.
Intentionally, using namespace X; shouldn't introduce ambiguity errors by itself. That would very much defeat the purpose of namespaces. The common using namespace std; introduces many names that you'd reasonbly define yourself as well.
You cannot shadow symbols like that, only variable names (which is a warning on most compilers, i.e. a bad idea). using directives aren't precise in any sense, which I think is the assumption that most people make.
using directives will import a symbol into the scope. for instance, you can do things like this:
namespace foo {
using namespace std;
}
foo::string val;
This sort of practice leads to some very annoying compiler errors to track down. Your simple example is clear where the error is. If you try doing it in a few hundred thousand lines of code, you will be much less pleased.
I would advise you not to acquire the habit of relying on the using directive. If you must, just do one type at a time.
using std::string;
Basically, this keeps you honest. And if there is a naming conflict, grep will take 30 seconds to uncover where the problem is.
If you just spend a couple weeks typing std:: in front of your types, you will get used to it. I promise that the amount of time you think you are saving is greatly exaggerated.
I think this is because of compiler-optimisation. When your string is commented - he saw, that there are some function, but you don't use it, so he discard it. And when he saw that function useful - he want to insert function call, but can't chose which one you want.

C++ function prototypes?

Here goes newbie question number 5, but I don't have a teacher.. so.. anyhow here we go:
I'm wondering if is necessary to have function prototypes at the top of the file, instead of putting the main function to the end of the file and create all the function at the top of the file. As far as I can tell, VC++ and G++ both are not complaining. Is there standards that disallows me to do so?
It seems rather annoying to have to change the prototype when you change a function parameters and return types.
Example:
#include <iostream>
void say_hi(){
std::cout << "hi" << std::endl;
}
int main(){
say_hi();
return 0;
}
This declares but does not define the function say_hi:
void say_hi();
This both declares and defines the function say_hi:
void say_hi(){
std::cout << "hi" << std::endl;
}
You can declare a function many times; you can only define it once.
A function must be declared in the file before you can call it. A function must be defined somewhere--in the same file before or after you call it or maybe even in a different file.
So, yes, this is perfectly fine.
You are correct; if you define all your functions above where they are called, you don't need function prototypes. The actual function definition serves the same purpose as a separate declaration.
This works when you have tiny functions. It works less well when they get long. Or when you have more than one file of code. As a matter of style, many teachers demand that even tiny applications be written with the structure that serves large applications well.