accessing classes from a .h file in C++ - c++

Hello I am new to using header files and OPP in my programs and I am wondering why visual studio 2010 is stating that there are errors in my code. The code compiles and runs as desired but there are red lines under all of the objects
here is the header file
//functions.h
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
class vehicle
{
public:
int hp;
int ammo;
void displayHP();
void displayAmmo();
void displayName();
string vesselName;
void setName(string);
void moveUP(int& y);
void moveDown(int& y);
void moveLeft(int &x);
void moveRight(int &x);
private:
};
//implementation section
void vehicle::displayHP(){cout<<hp<<endl;}
void vehicle::displayAmmo(){cout<<ammo<<endl;}
void vehicle::setName(string name){vesselName=name;}
void vehicle::displayName(){cout<<vesselName<<endl;}
void vehicle::moveUP(int& y)
{
y=y-1;//moves boat up
system("cls");
}
void vehicle::moveDown(int& y)
{
y=y+1;//moves boat down
system("cls");
}
void vehicle::moveLeft(int &x)
{
x=x-1;// moves the boat left
system("cls");
}
void vehicle::moveRight(int &x)
{
x=x+1;//moves boat right
system("cls");
}
void moveBoat(int &x,int& y, int a,int b,int s,int turn)
{
here is the header file that contains the boats movements. The program compiles fine and works as designed but I was confused why visual studio is claiming there are so many errors I added line comments to where the errors in the boat.h file
//boat.h
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <string>
#include "functions.h"
using namespace std;
void moveBoat(int &x,int& y, int,int,int,int);
void youScrewedUp(int &x,int& y, int,int,int,int);
int movement=0;
vehicle destroyer;
destroyer.hp=500;//<==== getting a red line under the word destroyer error says "this deceleration has no storage class or type specifier"
destroyer.ammo=500;//<==== getting a red line under the word destroyer error says "this deceleration has no storage class or type specifier"
displayArray(x,y,a,b,s);//<===="this deceleration has no storage class or type specifer"
destroyer.setName("USS YAY I LEARNED CLASSES");//<===="this deceleration has no storage class or type specifer"
destroyer.displayName();//<===="this deceleration has no storage class or type specifer"
destroyer.displayHP();//<===="this deceleration has no storage class or type specifer"
cout<<"Boat Location X "<<x<<" Y "<<y<<endl;
if(s==1)
{
cout<<"ENEMY SHIP SIGHTED"<<endl;//<===="this deceleration has no storage class or type specifer"
}
cout<<"1.move left"<<endl;//<===="this deceleration has no storage class or type specifer"
cout<<"2.move right"<<endl;//<===="this deceleration has no storage class or type specifer"
cout<<"3.move up"<<endl;//<===="this deceleration has no storage class or type specifer"
cout<<"4.move down"<<endl;//<===="this deceleration has no storage class or type specifer"
cin>>movement;<===="this deceleration has no storage class or type specifer"
switch(movement)//<==expected a deceleration
{
case 1:
if(x>0)//does not allow boat to leave grid
{
destroyer.moveLeft(x);
}
else
{
youScrewedUp(x,y,turn,a,b,s);// function that repeats the movement function and displays a message
}
break;
case 2:
if(x<9)//boundary
{
destroyer.moveRight(x);
}
else
{
youScrewedUp(x,y,turn,a,b,s);
}
break;
case 3:
if(y>0)//boundary
{
destroyer.moveUP(y);
}
else
{
youScrewedUp(x,y,turn,a,b,s);
}
break;
case 4:
if(y<9)//boundary
{
destroyer.moveDown(y);
}
else
{
youScrewedUp(x,y,turn,a,b,s);
}
break;
}
turn++;//adds one to the turn counter to cycle to the enemies turn
}
void youScrewedUp(int &x, int &y,int turn, int a, int b,int s)// must pass the x y values by refferance
{
cout<<"where are you going your leaving the battlefield"<<endl;
cout<<"please make another selection"<<endl;
system("pause");
system("cls");
moveBoat(x,y,turn,a,b,s);
}
Here is my main()
// arrayTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "array.h"
#include "boat.h"
#include "enemy.h"
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int turn=1;// turn counter cycles between 1 and 2 during player and enemy turns
int x=7;//x coordinate for destroyer
int y=6;//y coordinate for destroyer
int a=3;//x coordinate for sub
int b=4;//y coordinate for sub
int s=0;//toggle for submerged or not chose not to use a bool because I used a random number generator to allow a 25% chance opposed to a 50% chance
srand (time(NULL));
do{
moveBoat(x,y,turn,a,b,s);//function that moves the boat
moveEnemy(a,b,turn,x,y,s);//function to move the enemy
}while(turn<3);// this is temporary will be replaced when a hp and weapons system is completed
system("pause");
return 0;
}

This goes beyond your base question and adds some other things that will improve your code and hopefully understanding.
You need to put your 'main' function code literally in a main function
int main(int argc, char * argv[])
{
//do stuff here....
return 0;
}
You should include header guards to prevent you from including 'function.h' multiple times. I would also strongly suggest renaming it to Vehicle.h to be emblematic of the class it is providing.
#ifndef __VEHICLE_H__
#define __VEHICLE_H__
//... all the good stuff.
#endif
I would STRONGLY suggest you remove using namespace std from your header file as doing so will trash the namespaces of anyone who wishes to use your header. Instead simply use std:: where needed or if you really don't want to use them everywhere, consider doing a using std::xyz; for the specific features you are using. This way at least you can trace down collisions later. If you want to do this in an implementation file (i.e. *.c) that's up to you; but don't do it in files that are included generally speaking.
Don't include headers you aren't using in your header file. This is a bad habit, leads to code and compiler bloat, and will inevitably cause pain later. You shouldn't be including ctime or stdafx in each of your headers as they don't refer to it.
You need to put the body of 'stuff' that is floating inside boat.h into a function
//somefunct
void somefunction()
{
int movement=0;
vehicle destroyer;
destroyer.hp=500;//<==== getting a red line under the word destroyer error says "this deceleration has no storage class or type specifier"
destroyer.ammo=500;//<==== getting a red line under the word destroyer error says "this deceleration has no storage class or type specifier"
//.... Everything else
}

Related

C++ circular dependency, undeclared identifier

I have to class that use each other but whatever I tried I couldn't achieve to make them work.
I just want them to access each other and after days of struggle, I decided to ask here.
If someone can point out what I am doing wrong and what I should do instead it would be great.
Edit: I decided to implement one of the solutions which are already on stack overflow and changed my code according to that:
I will also share errors this time so maybe we can figure out what's wrong.
I tried to copy this:
Resolve build errors due to circular dependency amongst classes
I used class name "Unit" instead of "A" and "Skill" instead of
"B"
Skill.h
#pragma once
#include <iostream>
#include <vector>
#include "Unit.h"
using namespace std;
class Skill :
public Unit
{
double _val;
Unit* unitPtr;
public:
Skill(double val):_val(val)
{
}
void SetSkill(Unit* unit)
{
unitPtr = unit;
unitPtr->Print();
}
void Print()
{
cout << "Type:B val=" << _val << endl;
}
// Unit* unitPtr;
vector <Skill *> attacks;
vector <Skill *> utilities;
vector <Skill *> movement;
};
Unit.h
#pragma once
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Skill;
class Unit
{
int _val;
Skill* skillPtr;
public:
Unit(int val) :_val(val)
{
stunned = false;
curSpeed = speed + rand() % 8 + 1;
}
void SetSkill(Skill* skill)
{
skillPtr = skill;
skillPtr->Print(); // COMPILER ERROR: C2027: use of undefined type 'B'
}
void Print()
{
cout << "Type:A val=" << _val << endl;
}
int GetDodge()
{
return dodge;
}
void Setup();
string name;
int maxHP;
//... and other variables
};
Unit.cmp
#include "Skill.h"
#include "Unit.h"
void Unit::Setup()
{
heroes.push_back(new Vestal);
heroes.push_back(new Vestal);
heroes.push_back(new Crusader);
heroes.push_back(new Crusader);
monsters.push_back(new BoneSoldier);
monsters.push_back(new BoneDefender);
monsters.push_back(new BoneSoldier);
monsters.push_back(new BoneDefender);
}
Later on the code, I add some stuff to attacks, utilities, and moment and I want to access them from the Unit object, like below:
heroes[0]->skillPtr->attacks[0]
And I want to be able to access the variables in the Unit.h (like maxHP) from Skill.h
Errors:
Error C2512 'Skill': no appropriate default constructor available
Error C2512 'Unit': no appropriate default constructor available
I'm a beginner but maybe I can see a couple of issues that are likely causing you problems here.
First you've got a classic circular dependency here, Unit.h includes Skill.h which includes Unit.h which includes Skill.h and so on.
Secondly not seeing any #pragma once pre-proccessor directives. Which means when you then go on to try and include both Skill.h and Unit.h in your unit CPP file, you will try to include the .h files more than once, as they include each other...
Thirdly you're using namespace std in the global scope. You can do that, but don't do that.
If you're looking for more try this excellent video on the subject
https://www.youtube.com/watch?v=Zbw58vTotok

How to declare a class in C++

I am new to c++ and am stuck on the syntax of declaring classes.
From what I have gathered you should store all declarations in a header file, I'll call it declarations.h;
#pragma once
void incptr(int* value);
void incref(int& value);
class Player
{
public:
int x, y;
int speed;
void Move(int xa, int ya)
{
x += xa * speed;
y += ya * speed;
}
void printinfo()
{
std::cout << x << y << speed << std::endl;
}
};
Now Player is a class which I want to store in a cpp file called functions.cpp
I want to move the above Player class into the below file functions.cpp
#include "common.h"
void incptr(int* value)
{
(*value)++;
}
void incref(int& value)
{
value++;
}
common.h contains;
#pragma once
#include <iostream>
#include <string>
#include "declarations.h"
What I think is happening is when i write the Player class in the header file, its being declared in that file, well, already there. If i move the Player class into functions.cpp I need to leave a declaration. I'm not sure what the compiler expects as a declaration when it comes to classes.
I have tried;
class Player();
functions::Player();
void Player::Move(int xa, int ya);
Also a few other variations but these make the most sense to me.
Sorry if this is a bit messy, still trying to get a hold on the language. Thanks in advance for you help!
Edit: Sorry I missed the main function;
#include "common.h"
int main()
{
Player player = Player();
player.x = 5;
player.y = 6;
player.speed = 2;
player.Move(5, 5);
player.printinfo();
std::cin.get();
}
A declaration for a class is just as simple as
class Player; // Note there are no parentheses here.
This form is most commonly used when you have circular dependencies between two classes. It is more common to define a class in a header file but put the definitions of member functions in a .cpp file. For your purposes a we can make a header file named player.h:
class Player
{
public:
int x, y;
int speed;
void Move(int xa, int ya);
void printinfo();
};
Note that this declaration does not contain the bodies of the member functions because these are really definitions. You can then put the function definitions in another file. Call it player.cpp:
void Player::Move(int xa, int ya)
{
x += xa * speed;
y += ya * speed;
}
void Player::printinfo()
{
std::cout << x << y << speed << std::endl;
}
Note how we have to now specify that each of these functions is a member of the Player class with the Player:: syntax.
Now assuming you also have a main.cpp file with your main() function, you can compile your code like this:
g++ main.cpp player.cpp
For this simple example, you will be fine defining your functions inside of the class declaration. Note that this makes the functions "inline" which is another topic that you should read about.

Getting many errors in C++ header and not sure why

I'm making a car design program. For this program, we are making a class in a header file, and then we will use that header file in our main program by including the file using #include "name of header".
This is my professors header. This is the code in his header. We were instructed to do the header like he is.
/*
Program 14-2
author - Ray Warren, modified from Language Companion
last updated - 19 July 2013
*/
#include <string>
using namespace std;
class CellPhone
{
private:
// Field declarations
string manufacturer;
string modelNumber;
double retailPrice;
public:
// Constructor
CellPhone(string manufact, string modNum, double retail)
{
manufacturer = manufact;
modelNumber = modNum;
retailPrice = retail;
}
// Member functions
void setManufacturer(string manufact)
{
manufacturer = manufact;
}
void setModelNumber(string modNum)
{
modelNumber = modNum;
}
void setRetailPrice(double retail)
{
retailPrice = retail;
}
string getManufacturer()
{
return manufacturer;
}
string getModelNumber()
{
return modelNumber;
}
double getRetailPrice()
{
return retailPrice;
}
}; //end class
This is the program he used the header file in (as you see he included the header file).
/*
Program14-2
author - Ray Warren, modified from Language Companion
last updated - 19 July 2013
*/
#include <iostream>
#include <cstdlib>
#include "CellPhone.hpp"
using namespace std;
int main()
{
// Create a CellPhone object and initialize its
// fields with values passed to the constructor.
CellPhone myPhone("Motorola", "M1000", 199.99);
// Display the values stored in the fields.
cout << "The manufacturer is "
<< myPhone.getManufacturer() << endl;
cout << "The model number is "
<< myPhone.getModelNumber() << endl;
cout << "The retail price is "
<< myPhone.getRetailPrice() << endl;
system("Pause");
return 0;
} //end main
This is my header file containing my class.
#include <string>
using namespace std;
Car(int ym, string mk)
{
yearModel=ym;
make=mk;
speed=0;
}
void setYearModel(int ym)
{
yearModel=ym;
}
void setMake (string mk)
{
make=mk;
}
int returnYearModel()
{
return yearModel;
}
string returnMake()
{
return make;
}
int returnSpeed()
{
return speed;
}
void accelerate()
{
speed += 5;
}
void brake()
{
This is my main program with me attempting to include the header file into my main program. When I tried to compile this, my header file popped up in a new code blocks IDE tab, and gave me this list of errors.
http://prntscr.com/bzu4x5 <--------- list of errors
I have no idea what I'm doing wrong. From what I see, I copied my professor exactly as he told us to, and I'm still getting errors.
Does anyone have any ideas of what's causing this massive list of errors?
#include <string>
#include <iostream>
#include "Car header.h"
int main()
{
}
Your "header file" contains the definitions of the class member functions. It should actually be a .cpp file. What you are missing is a definition of the class itself, and declarations of the member functions.
Note that your professor's sample header file defines the member functions inside the class definition. This is actually poor practise, but he may not have got round to teaching you how do define functions out of line yet.
If you are going to define the functions out of line, you will also need to change the functions to some thing like:
std::string Car::returnMake()
{
return make;
}
Note: "using namespace std" is also poor practise. Professional C++ code tends to be explicit, and use the "std::" prefix. Just get in the habit and save yourself hours of pain.
You did not actually define a class in you header file. Notice that in your teacher's header file, he has:
class Cellphone // -> this is what you do not have
{
private:
// Field declarations
string manufacturer;
string modelNumber;
double retailPrice;
public:
//constructor function
CellPhone(string manufact, string modNum, double retail);
// Member functions
void setManufacturer(string manufact);
void setModelNumber(string modNum);
void setRetailPrice(double retail);
string getManufacturer();
string getModelNumber();
double getRetailPrice();
}
You should have you fields and member functions inside your class. Hope that helps

How can I create a vector of virtual class?

I'm new to C++, so I decided to work on some little project to improve myself. I try to write a simple chess program with class Unit, and class King which is inherited from Unit
#include <list>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stdlib.h> /* abs */
using namespace std;
// Each unit class represent a chess unit
class Unit{
protected:
int currentX;
int currentY;
string side;
public:
Unit();
Unit(string sideplay, int Xpos,int Ypos)
{
currentX=Xpos; currentY= Ypos;side=sideplay;
}
int getX()
{
return currentX;
}
int getY()
{
return currentY;
}
string getside()
{
return side;
}
void setpos(int newX,int newY) //set new position
{
currentX=newX;
currentY=newY;
}
bool validmove(vector<Unit> unitlist ,string sidepick,int Xpos,int Ypos)
{ int i=0;
while(i != 3)
{ int X=unitlist[i].getX();
int Y=unitlist[i].getY();
string sidetemp= unitlist[i].getside();
if ((X==Xpos)&&(Y==Ypos)&&(sidetemp==sidepick))
{
return false;
}
else if ((X==Xpos)&&(Y==Ypos)&&(sidetemp!=sidepick))
{ //unitlist[i]=NULL;
return true;
}
i++;
}
return true;
}
virtual void moveunit(vector<Unit> unitlist ,int nextX,int nextY);
};
class King: public Unit{
public:
King(string sideplay, int Xpos,int Ypos):Unit(sideplay,Xpos,Ypos)
{}
void moveunit(vector<Unit> unitlist ,int nextX,int nextY){
int diffX=abs(nextX-currentX);
int diffY=abs(nextY-currentY);
if ((diffX==1)||(diffY==1))
{ if (validmove(unitlist,side,nextX,nextY))
{
setpos(nextX,nextY);}
}
}
};
and here is my main:
int main()
{
vector<Unit> chessunit;
chessunit.push_back(King("white",3,1));
chessunit.push_back(King("black",3,2));
chessunit.push_back(King("white",4,1));
if (chessunit[0].validmove(chessunit,"white",3,2))
{
cout<<"hehe"<<endl;
}
chessunit[0].moveunit(chessunit,3,2);
int k= chessunit[0].getY();
cout<<k<<endl;
return 0;
}
I keep getting LNK 2001 error: Unresolved external symbol for my virtual method "moveunit". How can I fix that bug ?
The easiest way of fixing your problem is using pointers or smart pointers: Store vector<Unit*>, vector<std::shared_ptr<Unit>> or vector<std::unique_ptr<Unit>> (thanks #rubenvb) instead of vector<Unit> and then add your kings like so:
myVector.push_back(new King...); // or
myVector.push_back(std::shared_ptr<King>(new King...)); // or
myVector.push_back(std::unique_ptr<King>(new King...));
Why?
If you allocate an object of a virtual class (e.g. Unit unit) and you want to assign an object of an implementation of that class to it, e.g.:
Unit unit;
unit = King(...);
Then you will get an error, or at least run into trouble, unless you provide a constructor for Unit that takes King as an argument or provide a sufficient move operator. That is because if you try to assign an object of a type that is not Unit to unit, the compiler and/or run-time (depending on what the back-end of your compiler is) will have a tough time figuring out how compatible the types are and what to do if things "don't fit" memory-wise and how to cope with memory layout issues.
Further Reading
For more on pointers vs. smart pointers, consider this thread. Also here is a related Stackoverflow question and an article on using shared_ptr with STL collections
More information on trying to "squeeze" an object of one type into another (called slicing) can be found in this thread.
The problem you are facing right now is due to slicing: when you add a King to the vector, it gets sliced into an instance of Unit.
One way to fix this is to turn chessunit into a vector of std::shared_ptr<Unit> and allocate units on the heap.
P.S. Since you are not defining Unit::moveunit(), make it pure virtual:
virtual void moveunit(vector<Unit> unitlist ,int nextX,int nextY) = 0;
^^^

function is not a member of global namespace

So I'm attempting to program chess in C++ and I decided to make my move handler its own class (it was a main function before) so I could use it in some of my other classes without having to copy it everywhere.
However, when I finished setting everything up I got this error: 'parseMove' : is not a member of '`global namespace''
I'm using the standard namespace and all public functions and variables, and I know that so please don't bring it up unless it's relevant. My IDE is MS Visual C++ 2012.
Here is the code:
In the main:
void playGame(){
...
MoveParser parser; //declare move handler
...
//example of use
parser.parseMove(current, currentX, currentY);
...
}
MoveParser.h:
#pragma once
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
class MoveParser
{
public:
MoveParser(void);
~MoveParser(void);
void parseMove(string, int &, int &);
};
MoveParser.cpp:
#include "MoveParser.h"
MoveParser::MoveParser(void)
{
}
MoveParser::~MoveParser(void)
{
}
void::parseMove(string str, int &x, int &y){
//random junk
}
And also Visual C++ is giving me some new errors that aren't real...and I know they're not real because the code that it's giving me errors on ran fine before I added the new class and I haven't changed it.
Anyways, very frustrating, hopefully someone can point me in the right direction.
You forgot to specify the class name before the function name in its definition. Change this code
void::parseMove(string str, int &x, int &y){
//random junk
}
to
void MoveParser::parseMove(string str, int &x, int &y){
//random junk
}