How to avoid access errors while using friend functions in c++? - c++

#include <iostream>
using namespace std;
class boss{
int salary;
public:
boss();
boss(int b){
salary = b;
}
friend void total(boss, employe);
};
class employe{
int salary;
friend void total(boss, employe);
public:
employe();
employe(int e){
salary = e;
}
friend void total(boss, employe);
};
void total(boss b, employe e){
int T;
T = b.salary + e.salary;
cout << T;
}
int main(){
boss bb(200);
employe ee(300);
total(bb,ee);
}
Errors I'm facing
16:31:40 **** Incremental Build of configuration Debug for project Practice ****
make all
'Building file: ../src/Practice.cpp'
'Invoking: Cross G++ Compiler'
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Practice.d" -MT"src/Practice.o" -o "src/Practice.o" "../src/Practice.cpp"
../src/Practice.cpp:20:26: error: 'employe' has not been declared
20 | friend void total(boss, employe);
| ^~~~~~~
../src/Practice.cpp: In function 'void total(boss, employe)':
../src/Practice.cpp:38:8: error: 'int boss::salary' is private within this context
38 | T = b.salary + e.salary;
| ^~~~~~
../src/Practice.cpp:13:6: note: declared private here
13 | int salary = 3000;
| ^~~~~~
make: *** [src/subdir.mk:20: src/Practice.o] Error 1
"make all" terminated with exit code 2. Build might be incomplete.
16:31:40 Build Failed. 3 errors, 0 warnings. (took 655ms)

The friend total(boss, employe) declaration in boss fails because employe hasn't been declared yet.
Add a forward declaration of employe above boss.
class employe; // <--- add this
class boss{
int salary = 3000;
public:
boss();
boss(int b){
salary = b;
}
friend void total(boss, employe);
};

Related

Redefinition error when trying to move class to a separate file

I am trying to implement a class in c++ but I keep getting an error.
My .cpp looks like:
#include "medianfinderheader.h"
MedianFinder::MedianFinder() {
}
void MedianFinder::addNum(int num) {
}
double MedianFinder::findMedian() {
double x=1.0;
return x;
}
while my header file looks like:
class MedianFinder {
public:
MedianFinder() {};
void addNum(int num) {};
double findMedian() {
double x=1.0;
return x;
};
};
However I keep getting the following error :
g++ -I./ -g -Og -std=c++14 main.cpp MedianFinderClass.cpp -o medianEX
MedianFinderClass.cpp:2:5: error: redefinition of 'MedianFinder::MedianFinder()'
2 | MedianFinder::MedianFinder() {
| ^~~~~~~~~~~~
In file included from MedianFinderClass.cpp:1:
medianfinderheader.h:3:5: note: 'MedianFinder::MedianFinder()' previously defined here
3 | MedianFinder() {};
| ^~~~~~~~~~~~
MedianFinderClass.cpp:5:10: error: redefinition of 'void MedianFinder::addNum(int)'
5 | void MedianFinder::addNum(int num) {
| ^~~~~~~~~~~~
In file included from MedianFinderClass.cpp:1:
medianfinderheader.h:4:10: note: 'void MedianFinder::addNum(int)' previously defined here
4 | void addNum(int num) {};
| ^~~~~~
MedianFinderClass.cpp:9:12: error: redefinition of 'double MedianFinder::findMedian()'
9 | double MedianFinder::findMedian() {
| ^~~~~~~~~~~~
In file included from MedianFinderClass.cpp:1:
medianfinderheader.h:6:12: note: 'double MedianFinder::findMedian()' previously defined here
6 | double findMedian() {
I have no idea why this is happening when I've implmented classes like this before any help would be appreciated.
I have implemented classes in c++ in this exact same way, and I'm just really frustrated any help would be greatly appreciated.
this line
void addNum(int num) {};
creates an implementation of addNum with an empty body, you need
void addNum(int num);
same for other functions in that class

C++ why am I getting this strange error for no matching function call

I have the following code segment:
UnaryExpression.h:
#ifndef UNARYEXPRESSION_H_
#define UNARYEXPRESSION_H_
#include "Expression.h"
class UnaryExpression : public Expression {
private:
Token op;
Expression exp;
protected:
std::map<std::string, float> scope;
public:
UnaryExpression(std::map<std::string, float> &scope, Token& op, Expression& exp);
virtual ~UnaryExpression();
void evaluate();
float getReturnValue();
};
#endif /* UNARYEXPRESSION_H_ */
UnaryExpression.cpp:
#include "UnaryExpression.h"
UnaryExpression::UnaryExpression(std::map<std::string, float> &scope, Token& op, Expression& exp) : Expression(scope) {
this->op = op;
this->exp = exp;
}
UnaryExpression::~UnaryExpression() {}
void UnaryExpression::evaluate() {}
float UnaryExpression::getReturnValue() {
return this->returnResult;
}
I am constantly getting an error, but as soon as I remove Expression exp; from the constructor and private variables, the error seems to dissapear and I'm not sure why this is happening:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\UnaryExpression.o" "..\\src\\UnaryExpression.cpp"
..\src\UnaryExpression.cpp: In constructor 'UnaryExpression::UnaryExpression(std::map<std::__cxx11::basic_string<char>, float>&, Token&, Expression&)':
..\src\UnaryExpression.cpp:10:117: error: no matching function for call to 'Expression::Expression()'
10 | UnaryExpression::UnaryExpression(std::map<std::string, float> &scope, Token& op, Expression& exp) : Expression(scope) {
| ^
In file included from ..\src\UnaryExpression.h:11,
from ..\src\UnaryExpression.cpp:8:
..\src\Expression.h:18:2: note: candidate: 'Expression::Expression(std::map<std::__cxx11::basic_string<char>, float>&)'
18 | Expression(std::map<std::string, float> &scope);
| ^~~~~~~~~~
..\src\Expression.h:18:2: note: candidate expects 1 argument, 0 provided
..\src\Expression.h:13:7: note: candidate: 'Expression::Expression(const Expression&)'
13 | class Expression : public Statement {
| ^~~~~~~~~~
..\src\Expression.h:13:7: note: candidate expects 1 argument, 0 provided
Build Failed. 1 errors, 0 warnings. (took 1s.89ms)
For reference, here is the definition of Expression.h:
#ifndef EXPRESSION_H_
#define EXPRESSION_H_
#include "Statement.h"
class Expression : public Statement {
protected:
std::map<std::string, float> scope;
float returnResult;
public:
Expression(std::map<std::string, float> &scope);
virtual ~Expression();
virtual void evaluate();
virtual float getReturnValue();
};
#endif /* EXPRESSION_H_ */
The class Statement is similar to Expression, it has only a virtual method void evaluate() and a scope. When I initialize Expression, of course I pass the scope to the parent Statement class.

function pointers in array (nix c++)

I'm getting a compiler error when I'm trying to initialize my array with function pointers. Without using a class I'm able to run the code fine, but when I incorporate the code in a class I'm getting the error. I suppose this is more of a problem with my understanding of class usage, the scope resolution operator, etc. Any help to get this resolved would be much appreciated.
#include <iostream>
#include <cassert>
using namespace std;
#define F1 0
#define F2 1
#define F3 2
class A
{
private:
bool Func1();
bool Func2();
bool Func3();
public:
bool do_it(int op);
typedef bool (A::*fn)(void);
static fn funcs[3];
protected:
};
A::fn A::funcs[3] = {Func1, Func2, Func3};
int main()
{
A Obj;
cout << "Func1 returns " << Obj.do_it(F1) << endl;
cout << "Func2 returns " << Obj.do_it(F2) << endl;
cout << "Func3 returns " << Obj.do_it(F3) << endl;
return 0;
}
bool A::do_it(int op)
{
assert(op < 3 && op >= 0);
return (this->*(funcs[op]))();
}
bool A::Func1() { return false; }
bool A::Func2() { return true; }
bool A::Func3() { return false; }
The compiler spits out:
15:35:31 **** Build of configuration Debug for project JT ****
make all
make: Warning: File 'objects.mk' has modification time 7.3 s in the future
Building file: ../src/JT.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/JT.d" -MT"src/JT.o" -o "src/JT.o" "../src/JT.cpp"
../src/JT.cpp:141:41: error: cannot convert ‘A::Func1’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
A::fn A::funcs[3] = {Func1, Func2, Func3};
^
../src/JT.cpp:141:41: error: cannot convert ‘A::Func2’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
../src/JT.cpp:141:41: error: cannot convert ‘A::Func3’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
src/subdir.mk:18: recipe for target 'src/JT.o' failed
make: *** [src/JT.o] Error 1
15:35:32 Build Finished (took 1s.64ms)
Use A::fn A::funcs[3] = {&A::Func1, &A::Func2, &A::Func3};

"Variable" was not declared in this scope

I am getting this error when I try to compile my class. I have made sure there is function prototypes and variables are initilized correctly, hopefully someone can help me figure out the problem
g++ -c main.cc
g++ -c BankControl.cc
g++ -c Bank.cc
g++ -c Account.cc
g++ -c View.cc
g++ -c AcctList.cc
g++ -c Customer.cc
g++ -c CustArray.cc
g++ -c Transaction.cc
Transaction.cc: In function ‘int getTransID()’:
Transaction.cc:18:34: error: ‘transID’ was not declared in this scope
int getTransID() { return transID; }
^
Transaction.cc: In function ‘TransType getTType()’:
Transaction.cc:19:34: error: ‘tType’ was not declared in this scope
TransType getTType() { return tType; }
^
Transaction.cc: In function ‘TransState getTState()’:
Transaction.cc:20:34: error: ‘tState’ was not declared in this scope
TransState getTState() { return tState; }
^
Transaction.cc: In function ‘std::__cxx11::string getDate()’:
Transaction.cc:21:34: error: ‘date’ was not declared in this scope
string getDate() { return date; }
^
Transaction.cc: In function ‘int getTAcctNum()’:
Transaction.cc:22:34: error: ‘tAcctNum’ was not declared in this scope
int getTAcctNum() { return tAcctNum; }
^
Transaction.cc: In function ‘float getTAmount()’:
Transaction.cc:23:34: error: ‘tAmount’ was not declared in this scope
float getTAmount() { return tAmount; }
^
Transaction.cc: In function ‘void setDate(std::__cxx11::string)’:
Transaction.cc:28:3: error: ‘date’ was not declared in this scope
date = d;
^
Makefile:31: recipe for target 'Transaction.o' failed
make: *** [Transaction.o] Error 1
Here is my header file
#ifndef TRANSACTION_H
#define TRANSACTION_H
#include <string>
using namespace std;
#include "defs.h"
class Transaction
{
public:
Transaction(TransType = TTERROR, TransState = TSERROR,int = 0 ,float = 0);
int getTransID();
TransType getTType();
TransState getTState();
string getDate();
int getTAcctNum();
void setDate(string);
float getAmount();
private:
static int nextTransID;
int transID;
TransType tType;
TransState tState;
string date;
int tAcctNum;
float tAmount;
};
#endif
Here is my source file
#include "Transaction.h"
#include "defs.h"
#include <string>
using namespace std;
int Transaction::nextTransID = 2001;
Transaction::Transaction(TransType t, TransState s, int acct, float amount)
{
transID = nextTransID++;
tType = t;
tState = s;
tAcctNum = acct;
tAmount = amount;
}
int getTransID() { return transID; }
TransType getTType() { return tType; }
TransState getTState() { return tState; }
string getDate() { return date; }
int getTAcctNum() { return tAcctNum; }
float getTAmount() { return tAmount; }
void setDate(string d)
{
date = d;
}
I am kinda lost on what is the issue
This:
int getTransID() { return transID; }
has nothing to do with your class, it's a global function.
You meant:
int Transaction::getTransID() { return transID; }
Also, that function (and the other getters) should be made const to signal that they don't modify the object.

Getting CppUnit to read application class on netbeans 7.2

I am learning C++ and CppUnit at the same time, using netbeans 7.2.
I create the following file
#include <cstdlib>
using namespace std;
/*
*
*/
class Subtract{
public:
int minus(int a, int b){
return a-b;
}
};
int main(int argc, char** argv) {
return 0;
}
And then I right-click to generate the following cppunit test file
#include "newtestclass.h"
CPPUNIT_TEST_SUITE_REGISTRATION(newtestclass);
newtestclass::newtestclass() {
}
newtestclass::~newtestclass() {
}
void newtestclass::setUp() {
}
void newtestclass::tearDown() {
}
int Subtract::minus(int a, int b);
void newtestclass::testMinus() {
int a=89;
int b=55;
Subtract subtract;
int result = subtract.minus(a, b);
CPPUNIT_ASSERT_EQUAL(34,result);
}
When I try to run the test, it gives the following errors
g++ -c -g -I. -MMD -MP -MF build/Debug/GNU-MacOSX/tests/tests/newtestclass.o.d -o build/Debug/GNU-MacOSX/tests/tests/newtestclass.o tests/newtestclass.cpp
tests/newtestclass.cpp:25: error: 'Subtract' has not been declared
tests/newtestclass.cpp: In member function 'void newtestclass::testMinus()':
tests/newtestclass.cpp:30: error: 'Subtract' was not declared in this scope
tests/newtestclass.cpp:30: error: expected `;' before 'subtract'
tests/newtestclass.cpp:31: error: 'subtract' was not declared in this scope
make[1]: *** [build/Debug/GNU-MacOSX/tests/tests/newtestclass.o] Error 1
make: *** [.build-tests-impl] Error 2
How do I get this to work properly?
In C++, the convention is to declare the classes and functions in a header file (.h file) and implement them in the source file (.cpp file).
Your Subtract.h file (declarations) should have only this:
class Subtract {
public:
int minus(int a, int b);
};
Your Subtract.cpp file (implementation) should have this:
#include "Subtract.h"
int Subtract::minus(int a, int b)
{
return a-b;
}
Then you #include "Subtract.h" in your newtestclass.cpp file.