How to make it work, problem with 2 classes - c++

i have problem with my small project. I have two classes in it.
Problem:
error: 'Display' was not declared in this scope
Display is a class. Here is code:
//main.cpp
#include <iostream>
#include "Display.h"
#include "Polynomial.h"
using namespace std;
int main()
{
Polynomial prr;
prr.show();
cout<<endl;
cout<<"Enter x= ";
int x;
cin>>x;
cout<<endl;
cout<<"value for x="<<x<<endl<<"y="<<prr.value(x);
Display aa; // this doesn't work
//abc.show();
return 0;
}
//Display.h
#ifndef DISPLAY_H
#define DISPLAY_H
class Display
{
std::vector <vector <char> > graph;
public:
Display(int a, int b);
//friend void lay(Polynomial abc,Display cba);
//void show();
};
#endif // DISPLAY_H
I was thinking that maybe vectors are doing problems. I tested it without vectors, but it didn't change anthing.
//Display.cpp
#include "Display.h"
#include <iostream>
using namespace std;
Display::Display(int a, int b)
{
//ctor
if(a%2==0)
a++;
if(b%2==0)
b++;
vector <char> help;
vector <char> mid;
for(int i=0; i<b; i++)
{
mid.push_back('-');
if(i==(b+1)/2)
help.push_back('|');
else
help.push_back(' ');
}
for(int i=0; i<a; i++)
{
if(i==(a+1)/2)
graph.push_back(mid);
else
graph.push_back(help);
}
}
Now it's Polynomial class it's working fine, but Display class no, and i don't know why.
//Polynomial.h
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <vector>
//class Display;
class Polynomial
{...}
#endif // POLYNOMIAL_H
//Polynomial.cpp
#include "Polynomial.h"
#include <iostream>
#include <windows.h>
#include <cmath>
using namespace std;
// constructors and methods here
// everything here working fine
Edit:
After few tries i am one step back,
Now in Display.h
i have error :
error: 'vector' does not name a type
So i included vector lib.
But it didn't help.

Error Number 1:
You defined a constructor with 2 parameters
Display(int a, int b);
But when you call
Display aa;
Compiler try to instantiate a Display object with a default constructor, that you disabled defining a custom costructor;
you have 2 possibilities:
Adding a default constructor like
Display() = default;
or
Display() { /* do whatever you want to init with default parameter */}
Instantiate your variable using the constructor you defined
Display aa{0,0};
Error number 2:
std::vector < std::vector <char> > graph;
You declared vector<char> instead of std::vector<char>
See a Live Example

One reason is that your Display class has no default constructor, considering you're creating object like Display aa; . A default constructor is the constructor that has no arguments. Default constructors are provided implicitly by compiler as synthesized default constructor only if you don't provide any constructors to your class. If you provide your own constructors to your class, you must also explicitly provide a default constructor. So in your case, you should actually create Display object like this Display aa(argument, argument); by providing arguments. However, If you want to create object like Display aa; then add either Display () { } or Display() = default; in your Display.h file.
Considering you created object like the way I described but still getting an error, another reason could be that you're not compiling the source file that contains the Display (int,int); constructor definition (not just declaration as you did in your header file) along with the source file that contains the main function. If you did that but still getting an error in compilation, then I would assume it is a compiler issue and try adding a forward declaration class Display; which should compile the code. But the definition of Display has to be within the visible range of main function otherwise a forward declaration would do nothing.
In any case, you have to make sure the definition of your class is within the visible range of the main function that creates the class object. A class type with only declaration without a definition is called incomplete type and you cannot create an object of incomplete type. So the declaration of your Display (int,int); constructor in the Display.h is not enough. You also need a definition of that within the visible range of main function. You can either do that in the same file as main, same file as header, or a separate source file (which is the best practice) that has the complete definition of Display class, its data members, and member functions. However, you must make sure to compile that source file along with the source file containing main.

Related

How is it possible that I can make an instance from a class in which some member methods aren't defined yet? (C++)

I'm comparatively new to C++ so I tested some things out in Xcode, and found a really weird thing.
This is my 'Testing.h' file
#ifndef Testing_h
#define Testing_h
class Testing{
private:
int a;
public:
Testing(int a=3);
void hey(int b);
};
#endif
This is my 'Testing.cpp' file
#include "Testing.h"
Testing::Testing(int a){
a = 4;
}
And finally, this is the 'main.cpp' file
#include <iostream>
#include "Testing.h"
using namespace std;
int main(){
Testing a;
//Apparently not completing the definitions of every abstract methods in the class is not a problem
}
I only declared 'void hey(int b)' in 'Testing.h' but have not defined it in 'Testing.cpp'. So I was wondering how it is possible for the compiler to successfully compile the 'main.cpp' without having enough information of 'void hey(int b)'. Thanks in advance!
Because you never require there to be a definition for hey().
You can require a definition by calling it, for example :
a.hey(42);
And you'll see that the linker isn't too happy because hey is an undefined reference.
Testing a;//Apparently not completing the definitions of every abstract methods in the class is not a problem
You defined constructor with default value a=3 but calling both constructor argument and class parameter the same name is bad practice.
Instead you can write this:
//Testing.h
#ifndef Testing_h
#define Testing_h
using namespace std;
class Testing{
private:
int number;
public:
Testing(int a=3): number(a = 4){}//it's the same as your implementation in cpp file
void hey(int b);
int getNumber() {return number;}
};
#endif
//main.cpp
#include <iostream>
#include "Testing.h"
int main()
{
Testing object;
cout<<object.getNumber();// returns 4
return 0;
}
And why hey compiles?
During building your project compiler translates your source code into object code by verifying the syntax. After that process linker checks the definitions marked by whole phrases. Source code is compiled from each file provided. Linker doesn't care for the implementation presence, it only looks it up if a method is used by the program. So even without implementation of hey your program compiles.
Last remark
It's discouraged to include .cpp files use headers instead. Sometimes you can get yourself into multiple definitions of the same functions causing compiler errors.

Getting error: expected constructor, destructor, or type conversion before ‘(’ token

I am trying to make functions repository. I have created four files:
Function.hpp, Function.cpp, FunctionsRepository.hpp, FunctionsRepository.cpp
I want to keep pointers to functions in vector of pointers.
//FunctionsRepository.hpp
#ifndef FUNCTIONSREPOSITORY_HPP
#define FUNCTIONSREPOSITORY_HPP
#include <vector>
using namespace std;
class FunctionsRepository {
private:
static vector<double *> pointerToFunctions;
public:
static void addFunction(double * wsk);
};
#endif
//FunctionRepository.cpp
#include "FunctionsRepository.hpp"
void FunctionsRepository::addFunction(double * wsk) {
pointerToFunctions.push_back(wsk);
}
//Functions.hpp
#ifndef FUNCTIONS_HPP
#define FUNCTOINS_HPP
#include "FunctionsRepository.hpp"
int constFunction(int numberOfVehicles);
void linearFunction();
void stepFunction();
#endif
//Funcctions.cpp
#include "Functions.hpp"
double constFunction(double numberOfVehicles){
return numberOfVehicles/2;
}
double (*funcConstant)(double) = constFunction;
//ERROR HERE
FunctionsRepository::addFunction(funcConstant);
I want to add new functions to program as easily as its possible and use it leater in other parts of program.
But I dont get it. Why i am getting this error. The addFunction() method is static, that means I can use it in other classes or parts of program. Vector is static to make sure that is the only one copy for whole program.
Use function wrapper. std::function can stores callable objects. So, your code will contain something like this:
class FunctionsRepository {
private:
// void() - function prototype
static std::vector<std::function<void()>> pointerToFunctions;
public:
static void addFunction(std::function<void()> wsk)
{
pointerToFunctions.push_back(wsk);
}
};
for more information consult official documentation: http://en.cppreference.com/w/cpp/utility/functional/function
I solved It. I received an error because I was calling the FunctionsRepository::addFunction(funcConstant); expression out of any scope. I just created new function to execute this command and thats all.

This declaration has no storage class or type specifier in C++

I have multiple classes in my program.
A) When I create an object of a class in another class I am getting no error but when I use the object to call a function I get the above error.
B)Also if I create an object of another class and call a function using that in the constructor of my class then I get no error like this.
C) Cout function does not work in the body of the class except when I put it any function
D) The main class is able to do all of these and I am not getting any error.
It would be great to hear back soon. Thank you in advance.
Following is the code : These are two classes in my cpp. I am facing no problems except using object after creating it. the code is too huge too be posted. Everything can be done in main but not in other classes why?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <vector>
#include <map>
using namespace std;
class Message
{
public:
void check(string side)
{
if(side!="B"&&side!="S")
{
cout<<"Side should be either Buy (B) or Sell (S)"<<endl;;
}
}
};
class Orderbook
{
public:
string side;
Orderbook() //No Error if I define inside constructor
Message m; //No Error while declaring
m.check(side); //Error when I write m. or m->
};
This is a mistake:
m.check(side);
That code has to go inside a function.
Your class definition can only contain declarations and functions.
Classes don't "run", they provide a blueprint for how to make an object.
The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables.
In C++, code can only appear inside function bodies or in variable initializes.
You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :-->
(inside main)
Orderbook o1;
o1.m.check(side)
but that would be unnecessary. Keeping things short :-
You can't call functions inside a Class

C++ Constructor won't pass string - no constructor defined

I am trying to create an object of "Player" inside "PlayerManager" and I am getting the error in VS2010:
Error 1 error C2512: 'Player::Player' : no appropriate default constructor available c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory 631 1 Server
Player.h:
#ifndef _PLAYER_H
#define _PLAYER_H
#include <iostream>
#include <string>
using namespace std;
class Player
{
public:
Player(const string &name);
~Player(void);
private:
string name_;
};
#endif
Here is the constructor in Player.cpp:
Player::Player(const string &name)
{
}
PlayerManager.h:
'#ifndef _PLAYERMANAGER_H
#define _PLAYERMANAGER_H
#include <string>
#include <vector>
#include <iostream>
#include "Player.h"
using namespace std;
class PlayerManager
{
public:
PlayerManager(void);
~PlayerManager(void);
private:
vector<Player> players;
};
#endif'
Here is where I create the object in PlayerManager.cpp:
PlayerManager::PlayerManager(void)
{
Player test("Hello");
players.resize(1000);
for(int i=0; i < 960; i++){
players.push_back(test);
}
}
I don't understand why it is ignoring the string "Hello", I have tried creating a string object but gives same error.
I have also tried without adding the const & in the constructor but gives same error.
Any help would be appreciated, spend hours searching for an answer. Apologies if the layout is incorrect as this is my first time asking a question.
The class std::vector requires that the class you use it with has a default constructor1. You'll need to provide one for your class.
If you really don't want to provide one, you can give an instance of your class to vector in it's constructor call, so that it will use that instance instead of trying to default-construct one:
vector v(initialsize, Player("")); // or you can pass whatever string you want the default item to have
If the vector that you are using to store Players is a member variable, you'll need to pass it the default Player to use in the initialiser list:
PlayerManager::PlayerManager() : players(initialsize, Player("")) { // assuming the vector is named players
....
}
1 As R. Martinho Fernandes and Kerrek SB have pointed out in the comments, a default constructor is only required for this particular constructor of vector (the one that takes an initial size and when you don't give it a default instance) and the member function resize when called with a single argument. If you use the constructor that takes iterators or a const Allocator&, or if you use resize with the second argument, then you don't need a DC.

C++ classes - how to pass vector of custom type to function

I am attempting to develop a class with a function that can take a vector of items as it's argument.
I can get it to work fine if I use a vector of type int, or other primitive, but I can't get it to work with a vector of objects.
eg:
In my header file:
int influenceParticles(vector<Particle> particles);
This is what I am after, but won't compile (error stated is "'Particle' was not declared in this scope").
The particle.h file has been included at the top of this header file.
Clarification
Here is the .h file that gives me the error
#ifndef _PARTICLE_ATTRACTOR
#define _PARTICLE_ATTRACTOR
#include "ofMain.h"
#include "particle.h"
class ParticleAttractor {
//private
public:
ParticleAttractor(int posX, int posY); //constructor (void)
int influenceParticles(vector<Particle> particles);
};
#endif
Maybe you have cyclic includes, ie. if the ParticleAttractor.h also includes the Particle.h. To solve this, you should make a forward declaration of Particle in ParticleAttractor.h:
class Particle;
You should also consider passing the vector by reference to avoid copying:
int influenceParticles(vector<Particle>& particles);
First Particle must be a defined type. This definition should work:
int influenceParticles(vector<vector<int> > particles);
For practice, it is better to use the by reference parameter type rather than by value. So it is better to define it as:
int influenceParticles(vector<vector<int> >& particles);