Basic error of seperate class in polymorphism. C++ - c++

Aaand im back again with my second question and im kinda not sure about wether i should have posted all the seperate classes cuz it looks somewhat long. And im sure the solution is pretty small.
Anyways, i am at polymorphism tutorial vid that i am following and everything works fine if i follow it and put all classes in "main.cpp". But when i tried to do the same program with seperate classes (seen below) i am getting error "
E:\Codeblocks\Poly\main.cpp|11|error: cannot convert 'Ninja' to 'Enemy*' in initialization|".*
I kinda understand what the error is saying..i think.. but dont know what i did wrong since the same code was working when Enemy and Ninja class wasnt seperate but now as seperate classes its not working. I think i included those classes properly in main.cpp.
main.cpp
#include <iostream>
#include "Enemy.h"
#include "Ninja.h"
#include "Monster.h"
int main()
{
Ninja n;
Monster m;
Enemy *enemy1=&n;
Enemy *enemy2=&m;
enemy1->setAttackPower(20);
enemy2->setAttackPower(50);
n.attack();
m.attack();
return 0;
}
Enemy.h
#ifndef ENEMY_H
#define ENEMY_H
class Enemy
{
public:
Enemy();
void setAttackPower(int a);
protected:
int attackPower;
private:
};
#endif // ENEMY_H
Enemy.cpp
#include "Enemy.h"
Enemy::Enemy()
{
//ctor
}
void Enemy::setAttackPower(int a)
{
attackPower=a;
};
Ninja.h
#ifndef NINJA_H
#define NINJA_H
class Ninja
{
public:
Ninja();
void attack();
protected:
private:
};
#endif // NINJA_H
Ninja.cpp
#include "Ninja.h"
#include <iostream>
Ninja::Ninja()
{
//ctor
}
void Ninja::attack(){
std::cout<<" I am a ninja. Ninja chop! -"<<attackPower<<"\n";}

This is because your Ninja class is not inhereted from Enemy class. You must define Ninja class like this:
#include "Enemy.h"
class Ninja : public Enemy
{
public:
Ninja();
void attack();
protected:
private:
};
EDIT: I added #include directive. Without it compiler won't know, where to find Enemy class declaration.

Related

Problem with includes, base class undefined C2504

This is my EngineIncludes.h file:
#include <stdafx.h>
//Engine Includes
namespace Engine
{
//Classes: 23
class BaseObject;
class Console;
class Engine;
class Node;
template <class T> class Transform;
}
#include "core/BaseObject.h"
#include "core/Console.h"
#include "core/Engine.h"
#include "math/Transform.h"
#include "scene/Node.h"
//Global Objects
extern Engine::Console* CONSOLE;
extern Engine::Engine* CORE_ENGINE;
In stdafx.h I have regular stuff like OpenGL, std::map, boost... and I'm building a precompiled header as standard.
This is the Node.h file:
#ifndef _NODE_H
#define _NODE_H
#include <stdafx.h>
#include <EngineIncludes.h>
namespace Engine
{
class Node : public BaseObject
{
public:
Node();
~Node();
void SetParent(Node* parent);
Node* GetParent();
void SetTransform(const Transform<double> &transform);
Transform<double> GetTransform();
Transform<double> GetDerivedTransform();
Transform<double> GetInheritedTransform();
void Update();
private:
Transform<float> transform;
Transform<float> derived;
Node* parent;
};
}
#endif _NODE_H
I get 3 errors here. One C2504 that Engine::BaseObject is not defined. And two C2079 that both Transform transform and Transform use undefined class. Now this is the BaseObject.h:
#ifndef _BASE_OBJECT_H
#define _BASE_OBJECT_H
#include "stdafx.h"
#include "EngineIncludes.h"
namespace Engine
{
class BaseObject
{
public:
BaseObject()
{
id = CORE_ENGINE->GenerateID();
}
~BaseObject()
{
}
long GetID()
{
return id;
}
private:
long id;
};
}
#endif _BASE_OBJECT_H
Now I specifically fully defined BaseObject inside header file with no luck. Still the same error. But if I comment out forward declarations in EngineIncludes.h, the compiler freaks out with
extern Engine::Console* CONSOLE;
It literally ignores all #includes for whatever reason. I've never had an issue like this before. And I tried everything. I even created EngineIncludes.cpp file. I moved the contents of EngineIncludes.h into stdafx.h with no luck. It somehow just ignores #includes. Even if I put #include "BaseObject.h" inside "Node.h" nothing changes. When it compiles Node it has both Transform which is a template class and BaseObject undefined, even though both objects are clearly defined before Node with forward declarations and #includes.
I'm using Visual Studio 2010, but never had an issue like this. I looked into my previous projects and all is written the same fashion and works without problem.

Swarmed with identifier errors

I've been programming a Monopoly game for a final project. So I thought I was on a roll, and that I had everything figured out with my psuedocode. But, it seems I forgot how to deal with includes properly, I know that is the issue since I was able to refine it to that point, but I'm not sure how to fix it.
In this super stripped down version of my code I have three .h files "Space.h" which is an abstract/virtual class which has to be inherited by a variety of different spaces that can appear on a typical Monopoly board: properties, jail, taxes, Chance, Community Chest, etc. The function that has to be inherited is run(Player&) which is what is "run" when you land on that particular space on the board, all functions that use run use a player passed by argument.
#pragma once
#include <string>
#include "Player.h"
class Space
{
public:
virtual void run(Player&) = 0;
};
My second .h file is the "Property.h" this inherits from Space
#pragma once
#include "Space.h"
class Property : Space
{
public:
void run(Player&) override;
int i{ 0 };
};
Lastly I have the "Player.h" which has two variables a name and a vector of properties it owns.
#pragma once
#include <string>
#include <vector>
#include "Property.h"
class Player
{
public:
std::string name{ "foo" };
void addProperty(Property p);
private:
std::vector <Property> ownedProperties;
};
Here's a very basic Property implementation
#include "Property.h"
#include <iostream>
void Property::run(Player & p)
{
std::cout << p.name;
}
Player implementation
#include "Player.h"
#include <iostream>
void Player::addProperty(Property p)
{
ownedProperties.push_back(p);
}
And finally main
#include "Player.h"
#include "Space.h"
#include "Property.h"
int main()
{
Player p{};
Property prop{};
prop.run(p);
system("pause");
}
Every time this is run I get a slew of errors, I'm sure it's got to do something with the circular include logic, with player including property, and property including space, which includes player. But, I don't see a workaround considering #include is needed to know how everything is defined isn't? Or are these errors referring to something else?
You have a circular include problem. Player includes Property which includes Space which includes Player again.
You can break the circle by not including Player.h in Space.h and only forward declare the class
#pragma once
class Player;
class Space
{
public:
virtual void run(Player&) = 0;
};

C++ Incomplete Type Error

(I have read all the threads posted here and google, I was not able to fix from that)
I am having toruble with a incomplete type error when compiling. The way I am designing the project, the game pointer is unavoidable.
main.cpp
#include "game.h"
// I actually declare game as a global, and hand itself its pointer (had trouble doing it with "this")
Game game;
Game* gamePtr = &game;
game.init(gamePtr);
game.gamePtr->map->test(); // error here, I also tested the basic test in all other parts of code, always incomplete type.
game.h
#include "map.h"
class Map;
class Game {
private:
Map *map;
Game* gamePtr;
public:
void init(Game* ownPtr);
int getTestInt();
};
game.cpp
#include "game.h"
void Game::init(Game* ownPtr) {
gamePtr = ownPtr;
map = new Map(gamePtr); // acts as "parent" to refer back (is needed.)
}
int Game::getTestInt() {
return 5;
}
map.h
class Game;
class Map {
private:
Game* gamePtr;
public:
int test();
};
map.cpp
#include "map.h"
int Map::test() {
return gamePtr->getTestInt();
}
// returns that class Game is an incomplete type, and cannot figure out how to fix.
Let's go over the errors:
1) In main, this is an error:
game.gamePtr->map->test();
The gamePtr and map are a private members of Game, therefore they cannot be accessed.
2) The Map is missing a constructor that takes a Game* in Game.cpp.
map = new Map(gamePtr);
Here is a full working example that compiles. You have to provide the functions that are missing bodies, such as Map(Game*).
game.h
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
class Map;
class Game {
private:
Map *map;
public:
Game* gamePtr;
void init(Game* ownPtr);
int getTestInt();
};
#endif
game.cpp
#include "game.h"
#include "map.h"
void Game::init(Game* ownPtr) {
gamePtr = ownPtr;
map = new Map(gamePtr); // acts as "parent" to refer back (is needed.)
}
int Game::getTestInt() {
return 5;
}
map.h
#ifndef MAP_H_INCLUDED
#define MAP_H_INCLUDED
class Game;
class Map {
private:
Game* gamePtr;
public:
int test();
Map(Game*);
};
#endif
map.cpp
#include "game.h"
#include "map.h"
int Map::test() {
return gamePtr->getTestInt();
}
main.cpp
#include "game.h"
#include "map.h"
int main()
{
Game game;
Game* gamePtr = &game;
game.init(gamePtr);
game.gamePtr->map->test();
}
After doing this and creating a project in Visual Studio, I do not get any errors building the application.
Note the usage of #include guards, which your original posted code did not have. I also placed the members that were private and moved them to public in the Game class, so that main() can compile successfully.
You need to use forward declaration. Place declaration of Map class before definition of class Game:
game.h
class Map; // this is forward declaration of class Map. Now you may have pointers of that type
class Game {
private:
Map *map;
Game* gamePtr;
public:
void init(Game* ownPtr);
int getTestInt();
};
Every place where you use Map and Game class by creating instance of it or dereferencing pointer to it either through -> or * you have to make that type "complete". It means that main.cpp must include map.h and map.cpp must include game.h directly or indirectly.
Note you forward declare class Game to avoid game.h to be included by map.h, and that is fine and proper, but map.cpp must have game.h included as you dereference pointer to class Game there.

putting some class methods in different .cc file

I have a bit of code of the following format contained in a single .h and .cc file:
myClass.h:
#ifndef MYCLASS_H
#define MYCLASS_H
class myClass
{
public:
myClass(); // constructor
~myClass(); // destructor
void classMethod1 ();
void classMethod2 ();
int memberVarable1;
int memberVariable2;
};
#endif
and myClass.cc:
#include "myClass.h"
myClass::myClass(){
// stuff
}
myClass::~myClass(){
// stuff
}
void myClass::classMethod1 (){
// stuff
}
void myClass::classMethod2 (){
// stuff
}
All of this is working fine. However my project is getting quite large and I'm about to add a set of new functionality. Instead of clogging up myClass.h and myClass.cc I want to put some new methods in another .cc file. I don't seem to be able to get this to work though.
myClass.h:
#ifndef MYCLASS_H
#define MYCLASS_H
#include "secondFile.h"
class myClass
{
public:
myClass(); // constructor
~myClass(); // destructor
void classMethod1 ();
void classMethod2 ();
int memberVarable1;
int memberVariable2;
};
#endif
and myClass.cc:
#include "myClass.h"
#include "secondFile.h"
myClass::myClass(){
// stuff
}
myClass::~myClass(){
// stuff
}
void myClass::classMethod1 (){
// stuff
}
void myClass::classMethod2 (){
// stuff
}
secondFile.h:
#ifndef SECONDFILE_H
#define SECONDFILE_H
void someNewMethod();
#endif
secondFile.cc
#include "secondFile.h"
void someNewMethod(){
// can't see classMethod1()
}
In every source file, you need to include every header file that declares functions, etc. you want to use.
So in your case, it seems like you want secondFile.cc to contain
#include "myClass.h"
#include "secondFile.h"
void someNewMethod(){
// can't see classMethod1()
}
Btw, what you are doing is quite common to do in practice. Sometimes, I go even further than what you suggest, and implement the various methods of a single class in multiple source files. For large, complicated classes, this helps speed up the development cycle because I only have to recompile a fraction of the class implementation if I only made a small change. Example:
myclass.h
#pragma once
class MyClass
{
...
void complicatedMethod0();
void complicatedMethod1();
...
};
myclass_impl0.cpp
#include "myclass.h"
void MyClass::complicatedMethod0()
{
...
}
myclass_impl1.cpp
#include "myclass.h"
void MyCLass::complicatedMethod1()
{
...
}
If you are intending to add methods to myClass, you can't do that - the class methods have to be contained in one definition.
You can extend myClass, however, by inheriting from it:
secondFile.h:
#ifndef SECONDFILE_H
#define SECONDFILE_H
#include "myClass.h"
class mySecondClass : public myClass
{
public:
void someNewMethod();
}
#endif
secondFile.cc
#include "secondFile.h"
void mySecondClass::someNewMethod(){
this.classMethod1();
}
#include "secondFile.h"
#include "myClass.h"
//if you want the class methods,
//you need to tell the compiler where to look
void someNewMethod(){
// can't see classMethod1()
}
it seems you've forgotten to include "myClass.h".

sharing an object with multiple classes

I have 3 classes namely Board, Game, and AI
i want to have the object chessBoard of Board class to be use by Game and AI, and also by the Board Class. I want them to access that single chessBoard object (sharing)
problem is, it gives me the infamous fatal error LNK1169: one or more multiply defined symbols found. Also, there are Board.h,Game.h and AI.h (only declarations in them), and i also have their corresponding .cpp files. Each .h files have guards included (#ifndef _XXXXXX_H_)
I tried to include Board chessBoard inside Board.h file (just below the class), and it seems guards are not working.
Error 7 error LNK2005: "class Board chessBoard" (?chessBoard##3VBoard##A) already defined in AI.obj C:\Users\xxxx\Documents\Visual Studio 2010\Projects\CHESSv3\CHESSv3\Board.obj CHESSv3
Error 8 error LNK2005: "class Board chessBoard" (?chessBoard##3VBoard##A) already defined in AI.obj C:\Users\xxxxx\Documents\Visual Studio 2010\Projects\CHESSv3\CHESSv3\Game.obj CHESSv3
Error 9 error LNK2005: "class Board chessBoard" (?chessBoard##3VBoard##A) already defined in AI.obj C:\Users\xxxxx\Documents\Visual Studio 2010\Projects\CHESSv3\CHESSv3\ProgramEntryPoint.obj CHESSv3
AI.h
#ifndef _AI_H_
#define _AI_H_
#include <iostream>
#include <string>
using namespace std;
struct node {
string position;
string nextPosition;
float score;
int level;
float totalscore;
node* up;
node* right;
node* left;
bool approved;
string move;
};
class AI {
private:
//string board;
//string board[8][8];
int score1;
int maxscore;
int totalscore;
public:
void GetBoard(string[][8]);
void AnalyzeMyPositions();
void ExecuteAdvanceHeuristicMove();
};
#endif
Game.h
#ifndef _GAME_H_
#define _GAME_H_
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
class Game {
public:
char WhosTurn();
bool Playable();
bool GetMoveFromPlayer();
void TurnOver();
Game();
private:
char turn;
};
#endif
Board.h
#ifndef _BOARD_H_
#define _BOARD_H_
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
class Board {
public:
bool SquareChecker(string);
bool MoveChecker(string);
Board();
void PrintBoard();
int Execute(string);
void UnExecute();
string CB[8][8];
private:
char turn;
vector<string> BoardRecord;
stack<string> CBR;
//string CB[8][8];
};
Board chessBoard;
#endif
If you really want to do this, you need to make the declaration of the object extern in the header Board.h:
extern Board chessBoard;
You then provide a declaration in Board.cpp:
Board chessBoard;
Much better, though would be to create it in enclosing code and pass it (by reference) to the constructors of the other classes.
What you are looking for is the Singleton design pattern which can achieved in the following way:
// Board.h
class Board {
private:
static instance_;
public:
static Board *instance();
}
// Board.cpp
Board *Board::instance_ = NULL;
Board *Board::instance() {
if (!instance_)
instance_ = new Board();
return instance_;
}
Mind that this pattern can either be seen as good or bad, if you don't like using it you should consider passing the reference of an instantiated Board class to all the requiring ones and keep it stored in each object as an instance variable. Something like:
Game::Game() {
this->board = new Board();
this->ai = new AI(board);
// or better this->ai = new AI(this) so AI can access all game methods
}
Your problem could be that there could be 3 different chessBoard definitions because you might be adding 3 different #include "Board.h". Please make only a single object at a place where you have more control rather than creating it globally inside Board.h
Did you try it like this? Include the necessary include declarations only in the .cpp files.
//Board.h
class Board {};
//Game.h
class Board;
class Game {
Board* myBoard;
public:
void setBoard(Board*);
};
//AI.h
class Board;
class AI {
Board* myBoard;
public:
void setBoard(Board*);
};
void main() {
Board chessBoard;
Game g;
g.setBoard(&chessBoard);
AI ai;
ai.setBoard(&chessBoard);
}