Separating interface from implementation isn't working c++ - c++

Hey i was trying to use Separating interface from implementation but got error.
Not understanding what's wrong.
Here's my program
here's the error image
#include<iostream>
#include"name.h"
using namespace std;
int main()
{
int x,y;
cin>>x>>y;
name n1(x,y);
n1.getdata(x,y);
n1.showdata();
}
now here's the created header file
#include<iostream>
using namespace std;
class name{
private:
int a,b;
public:
name(int x, int y);
void getdata(int x, int y);
int showdata();
};
& here's the next part of class
#include"name.h"
using namespace std;
name::name(int x, int y)
{
a=0;
b=0;
}
void name::getdata(int x,int y)
{
a=x;
b=y;
}
void name::showdata()
{
cout<<a+b;
}

There are many problems with your code. It looks like the best advice in this situation would be to read a good C++ book.
When this is out of the way, here's the short-list of problems in the severity-descending order:
name::showdata() declaration signature does not match difinitioin: int showdata() vs. void showdata()
header misses an include guard
using namespace in a header is a code smell 99 times out of 100
header does not need to include <iostream>, it would suffice to include it in implementation file, where it's actually used.
By looking at undefined references you are getting, I would also guess that name.cpp is not build.
I fixed some of the mentioned points to just make it build:
Live Demo

Related

way to separate non-class library into header and implementation

Let's say there is a library named test, the header "test.hpp" is like follows:
namespace test
{
int myfun(int a);
}
And as for the implementaion, which style is better?
#include"test.hpp"
int test::myfun(int a){
return a*a;
}
or
#include"test.hpp"
namespace test
{
int myfun(int a){
return a*a;
}
}
Suppose you have multiple namespaces or nested namespaces in your header as :
namespace test{
namespace subtest{
int Foo(int);
//many other functions go here
} //namespace subtest
} //namespace test
And
namespace test1{
int Foo(int);
}
namespace test2{
int Bar(int);
}
In these cases you should always go with Second implementation as it makes your code more readable and easy to debug.
First one :
#include "test.hpp"
int test::subtest::Foo(int x){return x;}
//many other goes here
Look as the nesting increase everytime to define a function, you need to write fully specified name of the function (repeating namespaces again again).
Second one :
#include "test.h"
namespace test{
namespace subtest{
int Foo(int x){return x;}
//other go here
}
}
This solves namespace name repetition also you can easily refactor things. To debug or refactor a namespace's content simply jump to it's first declaration and change the things. You can also collapse the code under single namespace. (With most ide) making you code more beautiful.
Similarly for multiple namespaces
First one :
#include "test.hpp"
int test1::Foo(int x){return x;}
int test2::Bar(int x){return x;}
How difficult it gets to debug things. Moreover if under two namespace same function name occurs you will have good time debugging.
Second one :
#include "test.hpp"
namespace test1{
int Foo(int x){return x;}
}
namespace test2{
int Bar(int x){return x;}
}
All the declaration within a namespace will be together. So debugging and jumping within namespace will be ease.
Also most open source projects use second implementation

making and including header files in c++ on linux machine from terminal

To start, I'm very new to c++ and Linux, so if you could keep that in mind when you respond that would be great :)
I am trying to create a class in one file, that I will implement in the header of another file when I make an instance of that class.
My class file is
#include <iostream>
int main(){
class Box
{
public:
int _width;
int _length;
int _height;
};
}
I saved this as boxclass.h, but I did NOT compile it. I read somewhere that when I add this to my header file, I should just save it as a text file.
My other file, which I tried to include my box class in, is this:
#include <iostream>
#include "/home/cole/cpp/boxclass.h"
using namespace std;
int main()
{
Box outer{3,4,5};
Box inner{1,2,3};
Box newB = outer-inner;
cout << newB << endl;
}
When I try to compile this, I get these errors repeated many times with many different values
/home/cole/cpp/Boxclass.h:442:864: warning: null character(s) ignored
/home/cole/cpp/Boxclass.h:442:1: error: stray ‘\1’ in program
Can anyone explain to me whats going on?
You have two definitions for the main() {} function. That's not compliant for any c++ compiled code.
Further you have a local declaration of your class here:
int main(){
class Box
{
public:
int _width;
int _length;
int _height;
};
}
You don't want this, but an out of scope declaration of class Box appearing in a separate header file.
I'd suppose what yo want is
#include <iostream>
class Box {
public:
int _width;
int _length;
int _height;
};
int main(){
}

Combining C codes in the same R package

Say I have two independent cpp codes in two different R packages:
(please do not take these examples literally, these are meant to be
a minimal version of my question).
#include <algorithm>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
using Eigen::VectorXf;
using Eigen::VectorXi;
using Eigen::RowVectorXf;
float Fmedian(VectorXf& x){
const int n=x.rows();
const int half=(n+1)/2-1;
float med;
std::nth_element(x.data(),x.data()+half,x.data()+x.size());
if((n%2)==1){
med=x(half);
} else {
float tmp0=x(half);
float tmp1=x.segment(half+1,half-1).minCoeff();
med=0.5*(tmp0+tmp1);
}
return med;
}
extern "C"{
void R_Fastmedian(int* n,float* X,int* fMet){
MatrixXf xi=Map<VectorXf>(X,*n);
float Um=Fmedian(xi);
*fMet=Um;
}
}
then, in another file, i have:
#include <algorithm>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
using Eigen::VectorXf;
using Eigen::VectorXi;
using Eigen::RowVectorXf;
float Fmedian(VectorXf& x){
const int n=x.rows();
const int half=(n+1)/2-1;
float med;
std::nth_element(x.data(),x.data()+half,x.data()+x.size());
if((n%2)==1){
med=x(half);
} else {
float tmp0=x(half);
float tmp1=x.segment(half+1,half-1).minCoeff();
med=0.5*(tmp0+tmp1);
}
return med;
}
float Fmad(VectorXf& x,float& med){
const int n=x.rows();
const int half=(n+1)/2-1;
float mad;
x-=med;
x=x.cwiseAbs();
std::nth_element(x.data(),x.data()+half,x.data()+x.size());
if((n%2)==1){
mad=x(half);
} else {
float tmp0=x(half);
float tmp1=x.segment(half+1,half-1).minCoeff();
mad=0.5*(tmp0+tmp1);
}
return(mad*1.4826);
}
extern "C"{
void R_Fastmad(int* n,float* X,int* fMet){
MatrixXf xi=Map<VectorXf>(X,*n);
float U1=Fmedian(xi);
float U2=Fmad(xi,U1);
*fMet=U2;
}
}
Now, i want to combine these two functions in a package. When i will compile
the second code using R CMD, i will get an error for Fmedian to the effect
that this function is already defined in the first file. What is the most
straightforward way to link these two files together?
If I'm reading correctly, your Fmedian implementations are exactly the same in both files. But the compiler doesn't actually know that, for it they may be different and cause ambiguity, hence the error. To fix it, you should unify both implementations into one.
One way to do that would be this:
// the first file
#include <algorithm>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
using Eigen::VectorXf;
using Eigen::VectorXi;
using Eigen::RowVectorXf;
// Forward-declare Fmedian as an external function.
// This means that its definition will be found
// in some other file (C++ translation unit) during compilation.
extern float Fmedian(VectorXf& x);
extern "C" {
void R_Fastmedian(int* n,float* X,int* fMet){
MatrixXf xi=Map<VectorXf>(X,*n);
float Um=Fmedian(xi);
*fMet=Um;
}
}
And your second file remains the same.
See also Externing functions in C++, How does the linker know where is the definition of an extern function?

Error: variable needs stack frame

considering this code i put a bp at the end of roll(int n) and i had data in values array
and i put another one at the end of print and there was no data in the array.Why do I get this error: CXX0069: Error: variable needs stack frame?
die.h
#ifndef DIE_H
#define DIE_H
#include<iostream>
#include<time.h>
using namespace std;
class Die
{
private:
int number;
int values[6][2];
void roll();
public:
Die();
void Roll(int n);
int getNumber()const{return number;}
void printLastValue();
void printApearences();
~Die(){}
};
#endif
die.cpp
#include"die.h"
#include<iostream>
#include<time.h>
using namespace std;
Die::Die()
{
srand(static_cast<int>(time(NULL)));
number=0;
for(int j=0;j<6;j++)
{
values[j][0]=j+1;
values[j][1]=0;
}
}
void Die::roll()
{
number=1+rand()%6;
}
void Die::printLastValue()
{
cout<<number<<endl;
}
void Die::Roll(int n)
{
for(int j=0;j<6;j++)
{
values[j][0]=j+1;
values[j][1]=0;
}
for(int i=0;i<n;i++)
{
roll();
(values[number-1][1])++;
}
}
void Die::printApearences()
{
for(int i=0;i<6;i++)
{
cout<<values[i][0]<<" : "<<cout<<values[i][1]<<endl;
}
}
main.cpp
#include"die.h"
#include<iostream>
using namespace std;
int main()
{
Die d;
d.Roll(5);
d.printApearences();
}
What exactly is this:
cout<<values[i][0]<<" : "<<cout<<values[i][1]<<endl;
Specifically, why are you trying to extract cout to cout? Copy/paste can be a ruthless wench. Pretty sure you want:
cout << values[i][0] <<" : "<< values[i][1] << endl;
Next, your header declarations are quite-convoluted.
Do NOT place using namespace std in any of your header files. For information on why, refer this question and its various discussions. If your fingers tire of typing std:: there are some alternatives, but in-general slurping an entire namespace (especially one as large as std) can cause unintended consequences. The linked question is worth a review.
Do not bring #include's into a header unless the content therein is dependent on it (Die.h needs nothing you're #include'ing, for example).
List your headers ahead of system headers, including in your headers, to ensure you do not code an implicit include that your header by-itself doesn't fulfill.
Include standard library C++ headers if you're compiling in C++ (use <cstdio>, <cstdlib>, <ctime>, etc.
Applying the above your code becomes:
Die.h
#ifndef DIE_H
#define DIE_H
class Die
{
private:
int number;
int values[6][2];
void roll();
public:
Die();
void Roll(int n);
int getNumber()const{return number;}
void printLastValue();
void printApearences();
~Die(){}
};
#endif
Die.cpp (top of file, code eliminated for brevity)
#include "die.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
main.cpp (top of file, code eliminated for brevity)
#include "die.h"
The last one traditionally contains <iostream> as well, but you don't actually need it in your code as it is written.
You're static cast to int for sending time(NULL) as the random seed is not correct. The srand(unsigned int seed); API takes an unsigned int as the seed, not an int. Change your seeding to be
srand(static_cast<unsigned int>(time(NULL)));
I'd start with those, specifically the first two suggestions.
It doesn't recognize rand and srand. Add #include <stdlib.h> to your die.cpp file.
The debugger will display this error when the execution is at a point where the variable in question is out of scope, and therefore cannot be evaluated. Step into your code until you reach the scope of the variable, and the debugger will show you its value.

C++ Does not name to a type

This might be an easy question, but I cannot figure out why the compiler it's giving me this error. I have two classes. Agent and Environment. WHen I try to add an object of type Agent in my Environment class I get Agent does not name to a type error. I am including Agent.h in my Environment.h class
#ifndef AGENT_H_INCLUDED
#define AGENT_H_INCLUDED
#include <vector>
#include <iostream>
#include "Environment.h"
using namespace std;
class Agent{
public:
Agent(bool s);
vector<int> getPercept();
void setPercept(vector<int> p);
void goForward();
void turnRight();
void turnLeft();
void clean();
void paint();
void refuel();
bool needsRefuel();
void turnOn();
void turnOff();
bool isActive();
void move();
int getCurX();
int getCurY();
char getCurDir();
void setCurrentPosition(int x, int y, char d);
private:
vector<int> percept;
int actions;
int performance;
char direction;
bool isOn;
int curX;
int curY;
char curDir;
};
#endif // AGENT_H_INCLUDED
/*************************/
#ifndef ENVIRONMENT_H_INCLUDED
#define ENVIRONMENT_H_INCLUDED
#include <vector>
#include <iostream>
#include "Agent.h"
using namespace std;
class Environment{
public:
Environment(vector<vector<char> > roomData);
Environment(vector<vector<char> > roomData, vector<int> status);
void setRoomData(vector<vector<char> > roomData);
bool isSimulationComplete();
void isAgentHome();
vector<int> sendLocationStatus();
void printEnvironment();
void setAgentHome(int x, int y);
vector<int> getAgentPercept();
void setAgentPercept(vector<int> status);
void setAgentPosition(int x, int y, char p);
vector<int> sendAgentPercept();
void calculateAgentPercept();
private:
vector<vector<char> > room;
vector<int> agentPercept;
bool simulationComplete;
int agentHomeX;
int agentHomeY;
int agentX;
int agentY;
char agentDir;
Agent agent; ////ERROR IS HERE
};
#endif // ENVIRONMENT_H_INCLUDED
Your agent.h includes environment.h. The agent.h file is parsed in order from top to bottom, so when environment.h is parsed, the compiler doesn't know what an Agent is. There appears to be no reason to incude environment.h in agent.h.
Apart from what the comments already said, you can't have two header files include each other. There is no reason for Agent.h to include Environment.h, so if a .cpp file includes Agent.h first, it'll fail (since it will first go through Environment.h, which requires Agent).
IF you have a situation where two header files depend on each other's definitions, use forward declarations where you can, or split your header files up into more header files.