C++ header issue involving functions and scope - c++

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;
}

Related

Why am I getting an "error: declaration of 'Coin::Coin()' outside of class is not definition" message?

I am just learning about classes in C++, and I am trying to create this Coin class that simulates a coin flip with a method called toss() that will return either 0 or 1 which represent heads or tails respectively.
#include <iostream>
#include <cstdlib>
using namespace std;
class Coin {
private:
public:
Coin();
int toss();
};
Coin::Coin();
int Coin::toss() {
int num;
num = rand() % 2;
return num;
}
int main() {
Coin C;
cout << C.toss() << endl;
}
I keep getting an error that says: error: declaration of 'Coin::Coin()' outside of class is not definition. I am assuming that I did not declare my constructor correctly, but I am not sure.
The problem is that you're trying to declare the constructor outside the class when you wrote Coin::Coin();.
To solve this replace Coin::Coin(); with Coin::Coin(){} as shown below:
class Coin {
private:
public:
Coin();
int toss();
};
//----------v--->semicolon removed from here
Coin::Coin() //this is a definition now
{
}

Forward variable declaration in 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;    

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.

A class member function calling a class friend function (all same class) Possible?

I have a pretty basic class with member functions and private data, but I want the print function not to be a part of the class member functions. I remove it from the class and declare it as a friend and it works when called directly from main.cpp, but when a class member function calls it internally it is not declared. I know being a friend gives it access to data, but how do I make it available to the member functions? Is it possible?
//HEADER FILE
#include<iostream>
using namespace std;
static const int ArrSize=3;
class TicTacToe
{
//friends
friend void printBoard(char [][ArrSize]);
//member functions
public:
void makeboard();
void isValidMove();
void isWinner();
void getMove();
//data members
private:
int pRow, pCol, player;
bool validMove, winner;
char TTTarray[ArrSize][ArrSize];
};
void TicTacToe::getMove()
{
// some internal code for determining if proper input
// calls printBoard() to show what move was made.
printBoard(0);
void printBoard(char TTTarray[][ArrSize])
{
int i;
for(i=0;i<3;i++)
{
cout << TTTarray[i][0] << " " << TTTarray[i][0] << " " << TTTarray[i][2] << endl;
}
}
// MAIN.CPP FILE
#include <iostream>
#include "TicTacToe.h"
using namespace std;
int main()
{
TicTacToe a;
a.makeBoard();
printBoard(0);
a.getMove();
return 0;
}
At the point where you use printBoard inside getMove, printBoard indeed hasn't been declared. You need to either move the definition of printBoard before getMove (with the definition available, it is also declared) or add at least a declaration
void printBoard(char [][ArrSize]);
outside the class (also before you use it anywhere). In addition, your code does not compile because there is at least one typo (upper case, lower case makeBoard), the definition of makeBoard is missing and the closing brace of getMove is missing. Also, maybe you want to call printBoard with TTTarray instead of 0?
PS: Please post code with proper indentation next time. It is really hard to check whether parentheses balance like this...

Access variable from another class (in C++)

This may be a really easy question but... here it goes. (Thanks in advance!)
I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.
source.ccp
#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply();
system("pause");
exit(1);
}
begin.h
#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
public:
void collectdata();
int test;
};
#endif
begin.cpp
#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
test = 6;
}
calculation.h
#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
public:
void multiply();
};
#endif
calculation.cpp
#include <iostream>
#include "begin.h"
#include "calculation.h"
void calculationclass::multiply()
{
beginclass BEGINOBJECT;
// BEGINOBJECT.collectdata(); // If I uncomment this it works...
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
Simply define member function multiply as
void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
And call it as
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply( BEGINOBJECT );
system("pause");
exit(1);
}
In your code beginclass has no explicit constructor, hence the implicitly defined default constructor will be used, which default constructs all members. Hence, after construction beginclass::test is either 0 or uninitiliased.
What you appear to be wanting is to avoid to call beginclass::collectdata() more than once. For this you would want to set a flag that remembers if beginclass::collectdata() has been called. The member function which returns the data then first checks this flags and, if the flag was not set, calls beginclass::collectdata() first. See also the answer by CashCow.
It looks like you are looking for some kind of lazy evaluation / caching technique whereby a value is calculated the first time it is requested then stored to return it subsequently without having to reevaluate.
In a multi-threaded environment the way to achieve this (using the new standard thread library) is by using std::call_once
If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.
For a "calc_once" example:
class calculation_class
{
std::once_flag flag;
double value;
void do_multiply();
double multiply();
public:
double multiply()
{
std::call_once( flag, do_multiply, this );
return value;
}
};
If you want multiply to be const, you'll need to make do_multiply also const and value and flag mutable.