Forward variable declaration in C++ - c++

I know what "forward function declaration" means, but I want get the same with variables.
I have this code snippet:
#include <iostream>
int x;
int main()
{
std::cout << x << std::endl; // I want get printed "2" but I get compile error
return 0;
}
**x = 2;**
In the std::cout I want print "2" value, but trying to compile this I get this compile error: error: 'x' does not name a type.
While this doesn't appear somthing of programmatically impossible, I can't compile successfully.
So what is the right form to write this and obtain a forward variable declaration?

Variable declarations need extern. Variable definitions need the type, like declarations. Example:
#include <iostream>
extern int x;
int main()
{
std::cout << x << '\n';
}
int x = 2;
Normally you'd use extern to access a variable from a different translation unit (i.e. from a different .cpp file), so this is mostly an artifical example.

You can declare
extern int x;
in this file, and in some other file
int x = 2;

You could use Class and declare variable inside. Also, anonymous namespace is needed as Vlad said. Example:
#include<iostream>
namespace
{
class MyClass
{
public:
static int x;
};
}
int main()
{
std::cout << MyClass::x;
}
int MyClass::x = 2;    

Related

C++ does not recognize string as keyword

I tried the following code:
#include <iostream>
using namespace std;
int main()
{
char string[4]='xyz';
return 0;
}
Since string is a keyword the compiler should give error but it runs fine. Can anyone explain why it compiles successfully.
string is not a keyword.
It's the name of a type declared in the standard library.
When you give it a name, you're doing something called shadowing. This is more clear in the following example:
{
int x = 0;
{
int x = 5;
std::cout << x << std::endl;
}
std::cout << x << std::endl;
}
What gets printed?
Well, 5 first then 0.
This is because the x in the second scope overrides the x from the first. It "shadows" the first declaration.
This works with typenames as well:
struct MyStruct {
int x;
};
...
{
...
int MyStruct = 10;
...
}
Here, MyStruct gets overridden within that scope.
That same thing happens in your example with std::string

I compiled this seemingly incorrect code, but I don’t understand why

I am learning C++ on a linux machine. I just tried “int i();” to declare a function but I forgot to define it. But to my surprise, this code can be compiled and output 1. I feel very confused. I tried “int I{};”, it still compiled with no errors. Please help to explain. Thanks in advance.
//test1.cpp
#include <iostream>
int main(void)
{
int i{};
std::cout << i << std::endl;
return 0;
}
g++ test1.cpp
./a.out
Output is: 0
//test2.cpp
#include <iostream>
int main(void)
{
int i();
std::cout << i << std::endl;
return 0;
}
g++ test2.cpp
./a.out
Output is : 1
In your first example, you define a variable named i, and value-initialise it, which for int means zero-initialisation.
int i{}; // defines i, initialised to zero
In your second example, you declare a function named i, which takes no parameters, and return int:
int i(); // declares a function
When you print this:
std::cout << i << std::endl;
i first get converted to bool (i decays to a function non-nullptr pointer, then it becomes true), and then printed as an integer, that's why you get 1. The compiler can make this conversion without the definition of i (as the result is always true), that's why you got no linker error.
If your intent was to call this function, and print the result, you'll need to use i():
std::cout << i() << std::endl;
This, of course, needs i's definition.
In your code:
//test1.cpp
#include <iostream>
int main(void)
{
int i{};
std::cout << i << std::endl;
return 0;
}
You are not actually declaring a function without defining it. The line of code int i{}; within the main() function here is a variable of type int named i and you are using a brace initializer list to initialize the variable i with out any values and in most cases could be 0 but can vary by compiler.
//test2.cpp
#include <iostream>
int main(void)
{
int i();
std::cout << i << std::endl;
return 0;
}
In this situation it is basically the same thing. You are within main() and by the rules of the language "you can not declare-define a function within a function", so this results in a declaration - definition of a variable. The only difference here is you are not using a brace initializer list here you are using it's ctor constructor called value initialization. Again you are not passing any values to it and in your case it's assigning an arbitrary value of 1.
Now if your code looked like this:
#include <iostream>
int i();
int main() {
std::cout << i() << '\n';
return 0;
}
This would fail to compile because the function i is declared but not defined. However if you did this:
#include <iostream>
// The text in quotes is not meant to be a string literal. It
// is the message of the text that represents any integer X.
int i() { return /*"some int value"*/ 1; }
int main() {
std::cout << i() << '\n';
return 0;
}
This would compile and run perfectly fine because the function i is both declared and defined.

Calling a function via the main using a class

I'm trying to add 2 to a class variable using a function, but it gives me this undefined reference to addTwo(int) even though I already have it declared.
#include <stdio.h>
#include <iostream>
using namespace std;
class Test {
public:
int addTwo(int test);
int test = 1;
};
int addTwo(int test);
int main() {
Test test;
cout << test.test << "\n";
addTwo(test.test);
cout << test.test;
}
int Test::addTwo(int test) {
test = test + 2;
return test;
}
The defined member function int Test::addTwo(int test) do differ from the declared global function int addTwo(int test);, which the compiler searches for.
To eliminate the error, define the global function or change the call of the global function to call of the member function.
In order to "add 2 to a class variable using a function", you should stop shadowing the member variable by the argument. (You can use this->test for using member variable, but this won't be needed in this case)
Try this:
#include <iostream>
using namespace std;
class Test {
public:
int addTwo();
int test = 1;
};
int main() {
Test test;
cout << test.test << "\n";
test.addTwo();
cout << test.test;
}
int Test::addTwo() {
test = test + 2;
return test;
}
Since it is a member function of the instance test you have to call it as
test.addTwo(test.test);
Instead, you're calling it as
addTwo(test.test);
and it doesn't know what that function is. As far as the compiler is concerned, addTest(int) doesn't exist because you haven't defined it outside of the class definition.

C++ header issue involving functions and scope

My problem is in the following C++ code. On the line with the 'cout' I get the error:
"'number' was not declared in this scope".
.h
using namespace std;
class a{
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
int main(){
cout << "Your number is: " << number() << endl;
return 0;
}
number(){
int x = 1;
return x;
}
Note: I'm aware this isn't the cleanest code. I just wanted to get the function working and refresh my memory on how to use headers.
For minimal fix, three basic changes are necessary.
Proper implementation of the number() method
int a::number() {
int x = 1;
return x;
}
Proper invocation of the number() method
a aObject;
cout << "Your number is: " << aObject.number() << endl;
There are many other enhancements possible though.
Addition, as pointed out by #CPlusPlus, usable scope of number() method, for example declaring it public
class a{
public:
int number();
};
Try this in your cpp file
using namespace std;
#include <iostream>
#include "header.h"
void a::number()
{
int x = 1;
return x;
}
int main()
{
cout << "Your number is: " << a().number() << endl;
return 0;
}
As for your header file replace class with a struct. The reason you are getting this error is because the compiler cant find the variable number. It is actually a method of a class.The reason you are replacing the class with a struct is because by default everything in a struct is public. So your header file called header.h should look like this
using namespace std;
struct a
{
int number();
};
There are three issues with your code.
The definition of the function number().
As you declared, it is a member function of the class "a". In your .cpp, the class name should be used as a prefix to the function. I mean,
a::number(){
int x = 1;
return x;
}
As the function is a member of the class "a", there are only two ways of accessing it,
If the function is a static function in the class, you can access it with :: operator. Like a::number().
If the function is not a static function, that is true in your case, you should instantiate the object out of the class "a" and they use "." operator with the reference. I mean,
a obj;
obj.number().
Your function number() is declared in private scope. You may recall that by default the scope is a class is private unless you specify public or protected. So the private function number() cannot be used outside the declared class unless there is a friend to it.
Below the code that I fixed,
.h
using namespace std;
class a{
public:
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
a::number(){
int x = 1;
return x;
}
int main(){
a obj;
cout << "Your number is: " << obj.number() << endl;
return 0;
}

How to declare a global variable that could be used in the entire program

I have a variable that I would like to use in all my classes without needing to pass it to the class constructor every time I would like to use it. How would I accomplish this in C++?
Thanks.
global.h
extern int myVar;
global.cpp
#include "global.h"
int myVar = 0; // initialize
class1.cpp
#include "global.h"
...
class2.cpp
#include "global.h"
...
class3.cpp
#include "global.h"
...
MyVar will be known and usable in every module as a global variable. You do not have to have global.cpp. You could initialize myVar in any of the class .cpp's but I think this is cleaner for larger programs.
While I would like to avoid global variables like the plague as our software cannot be multithreaded effectively due to the high reliance on global variables, I do have some suggestions:
Use a Singleton. It will allow you to keep the code and access clean. Part of the problem with a global variable is you don't know what code has modified it. You could set the value of global somewhere in your function relying on the hope that no one else will change it, but function your code calls, fooA, changes it and now your code is a) broken, and b) hard to debug.
If you have to use a global variable without touching the singleton pattern, look at fupsduck's response.
If you're not going to use the Singleton pattern as Lyndsey suggests, then at least use a global function (inside a namespace) to access the variable. This will give you more flexibily in how you manage that global entity.
// mymodule.h
namespace mynamespace // prevents polluting the global namespace
{
extern int getGlobalVariable();
}
// mymodule.cpp
namespace mynamespace
{
int myGlobalVariable = 42;
int getGlobalVariable()
{
return myGlobalVariable;
}
}
Just declare it outside the class:
Header file:
extern int x;
class A {
int z;
public:
A() : z(x++) {}
};
One source file:
int x = 0;
keyword extern
//file1.cpp
int x = 0;
//file1 continues and ends.
//file2.cpp
extern int x; //this gets tied into file1.cpp's x at link time.
//file2.cpp goes on and ends
Declare the variable as extern in a common header.
Define it in any source file.
// L.hpp
struct L { static int a; };
// L.cpp
int L::a(0);
The below solution should be simple enough as per the title "How to declare a global variable that could be used in the entire program
" .
If you want to use it in a different file then make use of extern keyword.
Please let me know if there is any issue with the solution
#include<iostream>
using namespace std;
int global = 5;
class base {
public:
int a;
float b;
base (int x) {
a = global;
cout << "base class value =" << a << endl;
}
};
class derived : public base {
public:
int c;
float d;
derived (float x, int y) : base (y)
{
d = global;
cout << "derived class value =" << d << endl;
}
};
int main ()
{
derived d(0,0);
cout << "main finished" << endl;
return 0;
}
if you want to declare it in different header files/cpp files, just declare it extern outside of other files
//file1.c
int x=1;
int f(){}
//file2.c
extern int x;