C++ multiple classes inheriting from a base class causing issues - c++

so, i have basically designed a "Hello, World!" OOP with c++.
I have 2 classes, chicken and dog that inherit from public animal.
In int main, when i create an instance of each, i get error messages that claims i have created multiple instances of the class Animal.
Animal.h
#ifndef ANIMAL
class Animal
{
int x;
int y;
int z;
public:
void setPosition(int newX, int newY, int newZ);
void setX(int newX);
void setY(int newY);
void setZ(int newZ);
int getPosition();
int getX();
int getY();
int getZ();
};
#endif
Chicken.h
#ifndef ANIMAL_H
#include "../animal.h"
#endif
class Chicken : public Animal
{
int id;
bool isClucking;
bool isEnraged;
public:
void setID(int newID);
void setClucking(bool yn);
void setEnraged(bool yn);
int getID();
bool getClucking();
bool getEnraged();
};
Dog.h
#include "../animal.h"
class Dog : public Animal
{
int id;
public:
void setID(int newID);
int getID();
};
Code here: Source Code

You have the animal.h defined as
#ifndef ANIMAL
class Animal
{
should be
#ifndef ANIMAL
#define ANIMAL
class Animal
{
so that animal.h is not included multiple times.
Also for consistency, have all your headers have a include guard. So dog and chicken need it.
Unless you really need it
#ifndef ANIMAL_H
#include "../animal.h"
#endif
should simply be
#include "../animal.h"
because the former construct requires the define exactly match which in your cause is already not matching. animal.h defines ANIMAL or at least tries to but where you include is you are checking for ANIMAL_H

Related

How to include class which uses base class

The question is hard to ask but I'll try to explain:
I have a class World that import Class Species, and holds list of Species.
I need to have pointer to class World in class Species, but if I import Class World before declaring Species errors occurs.
Example in pseudo code:
import B
Class A
{
list of B
}
Class B
{
Class A* a
}
so I need to import class A to make pointer to it, but when I do Class B is not declared in clas A.
my code:
#pragma once
#include <iostream>
class Species
{
protected:
std::string speciesName;
int strengh;
int effort;
int posX;
int posY;
int specieSymbol;
public:
Species();
Species(std::string speciesName, int strengh, int effort, int posX, int posY);
int getPosX();
int getPosY();
void setPosX(int x);
void setPosY(int y);
int getSpeciesSymbol();
std::string getSpeciesName();
virtual void action() = 0;
virtual void colision() = 0;
//void setWorld(World* w);
//World* getWorld();
~Species();
};
#pragma once
#include <iostream>
#include "Species.h"
#include <list>
#include "Board.h"
class World
{
private:
std::list <Species*> species;
Board* board;
public:
World(Board *board);
void addSpecies(Species* s);
void printSpecies();
void printWorld();
void Update();
~World();
};

Unit test noncopyable object

I have a noncopyable monster base class, I also have a IView class.
I have a hobgoblin class that inherits from both monster an IView ,
I have a controller that takes a pointer to IView as a parameter.
Basically I want to check if hobgoblin exploded.
I'm using gmock / gtest
I keep getting
Actual function call count doesn't match EXPECT_CALL(h, Explode())...
Expected: to be called at least once
Actual: never called - unsatisfied and active
when i use the mock object. What am i missing?
Monster Base
#ifndef MONSTER_H
#define MONSTER_H
#include <string>
// interface for all monsters
class monster {
public:
virtual ~monster();
// forbid copying
monster(monster const &) = delete;
monster & operator=(monster const &) = delete;
void receive_damage(double damage);
void interact_with_chainsaw();
std::string name() const;
protected:
// allow construction for child classes only
monster();
private:
virtual void do_receive_damage(double damage) = 0;
virtual void do_interact_with_chainsaw() = 0;
virtual std::string do_name() const = 0;
};
#endif // MONSTER_H
IView
#ifndef IVIEW_H
#define IVIEW_H
class IView
{
public:
virtual void Explode() = 0;
virtual ~IView(){}
};
#endif // IVIEW_H
Hobgoblin
#ifndef HOBGOBLIN_H
#define HOBGOBLIN_H
#include "monster.h"
#include "iview.h"
class hobgoblin : public monster, public IView
{
public:
hobgoblin();
void Explode();
virtual ~hobgoblin();
private:
void do_receive_damage(double damage) final;
void do_interact_with_chainsaw() final;
std::string do_name() const final;
double health_;
};
#endif // HOBGOBLIN_H
#include "hobgoblin.h"
#include <QDebug>
hobgoblin::hobgoblin() :
health_(100.0)
{
}
hobgoblin::~hobgoblin()
{
}
void hobgoblin::Explode()
{
health_ = 0;
qDebug() << "Health is 0";
}
void hobgoblin::do_receive_damage(double damage)
{
health_ -= damage;
}
void hobgoblin::do_interact_with_chainsaw()
{
// imagine horrible, gory things here such as
// having to deal with a singleton
}
std::string hobgoblin::do_name() const
{
static std::string const name("Furry hobgoblin of nitwittery +5");
return name;
}
Controller
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include "iview.h"
class Controller
{
public:
Controller(IView *view);
void Explode();
~Controller();
private:
IView *m_View;
};
#endif // CONTROLLER_H
#include "controller.h"
#include <QDebug>
Controller::Controller(IView *view):
m_View(view)
{
}
void Controller::Explode()
{
m_View->Explode();
}
Controller::~Controller()
{
}
Unit Test
class mockmonster : public IView
{
public:
MOCK_METHOD0(Explode,void());
virtual ~mockmonster(){}
};
TEST(MockMonster,Explode)
{
// this is not calling explode as expected.
mockmonster h;
Controller c(&h);
c.Explode();
}
TEST(HobGoblin,Explode)
{
// this calls explode fine
hobgoblin h;
Controller c(&h);
c.Explode();
}
Well, shouldn't your Explode function be virtual?
By the looks of it, your mockmonster is shadowing IView's function. Since Controller is taking a pointer to IView, and Explode is non-virtual, it will invoke IView's version.
As a side-note, I doubt if either of your classes being non-copyable matters here. When using gmock, non-copyable classes are problematic when setting up expectations/assertions (i.e. you expect a function to be called with a specific object - this object would have to be copied internally by gmock, and that might fail).

Inheritance (through files) unable to find class?

Im trying to use Inheritance through multiple header and cpp files for a text game that I'm writing.
I have my base class of Weapon. Which is in the file Weapon.h
class Weapon
{
public:
string Name;
int Damage;
float ChanceToHit;
int ExtraDamage;
int Result;
int Array[3];
int Attack(int, int, string);
};
I am then trying to inherit form the base Weapon.h class to a Bow and Sword class. I am sure I am including the file correctly but when I try to compile I get the error "error: expected class name class Blade : public Weapon" The same error for the Bow class.
#include "Weapon.h"
#include "Crossbow.h"
using namespace std;
class Bow : public Weapon
{
public:
string Type = "Ranged";
bool loaded;
protected:
Bow();
};
#include "Weapon.h"
class Blade : public Weapon
{
private:
string Type = "Melee";
protected:
void Draw();
};
Does anyone know why this is happening? Google isn't coming up for anything useful either. Thanks
MCVE (I think)
//In Base.h
class Base
{
public:
int function();
private:
};
//In Base.cpp
int Base::function()
{
randomshit
return 0;
}
//In Inherit.h
#include "Base.h"
class Inherit : public Base
{
public:
int function():
private:
};
Getting error: "expected class name class Bow : public Weapon"
EDIT: Turns out I needed to include "#pragma once" and that solved almost everything. Thanks for the help guys.
You don't use any include guards, so your file Weapon.h is probably included multiple times, leading to the compilation error.
To know more about include guards: https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Include_Guard_Macro
Your header Weapon.h would then become:
#ifndef WEAPON_H_INCLUDED
#define WEAPON_H_INCLUDED
class Weapon
{
public:
string Name;
int Damage;
float ChanceToHit;
int ExtraDamage;
int Result;
int Array[3];
int Attack(int, int, string);
};
#endif // WEAPON_H_INCLUDED
Do the same for all other header files.
Once you did that, remove all unnecessary includes and do a clean rebuild.
This is maybe not an answer but it just is impossible to post it as comment
This compiles (but does not link !!) on my Visual Studio 2013.
#include <string>
using namespace std;
class Weapon
{
public:
string Name;
int Damage;
float ChanceToHit;
int ExtraDamage;
int Result;
int Array[3];
int Attack(int, int, string);
};
class Bow : public Weapon
{
public:
string Type = "Ranged";
bool loaded;
protected:
Bow();
};
class Blade : public Weapon
{
private:
string Type = "Melee";
protected:
void Draw();
};
But it is likely to fail on older compilers because of the initialisation in the declaration as string Type = "Melee";.
Note that using namespace std; comes before the declaration of class Weapon.

Pure Virtual Function error in factory design pattern

studying for a final and decided to build a program which makes use of pure virtual functions and polymorphism. i am stuck on a really weird error maybe i am missing something.
This is the Shape abstract class
#ifndef Shape_hpp
#define Shape_hpp
#include <stdio.h>
#include <string.h>
class Shape{
const char* name;
public:
Shape(const char* abc);
virtual double getPerimeter()=0;
virtual double getArea()=0;
};
#endif /* Shape_hpp */
The Shape .cpp implementation file
#include "Shape.hpp"
Shape::Shape(const char *shape){
name = shape;
}
The Circle Header file
#ifndef Circle_hpp
#define Circle_hpp
#include "Shape.hpp"
#include <stdio.h>
class Circle:public Shape{
double m_radius;
public:
Circle(double rad);
double getRadius();
};
#endif /* Circle_hpp */
The circle .cpp implementation file
#include "Circle.hpp"
#include "Shape.hpp"
Circle::Circle(double rad):Shape("Circle"){
m_radius = rad;
}
double Circle::getRadius(){
return m_radius;
}
double Circle::getPerimeter(){
return (2 * 3.14 * m_radius);
}
double getArea(){
return 0;
}
I declared the two pure virtual functions in the abstract "shape" class and am accessing the public of shape class in circle header file, if i declare the pure virtual functions in the circle class it will make it abstract... the error says "Out-of-line definition of 'getPerimeter' does not match any declaration in 'Circle'"
Am i missing something or am i thinking about this the wrong way..
Help would be appreciated. Thanks!
You need to declare all member functions that you define. So in class Circle you need to add:
virtual double getPerimeter();
Or better in C++11:
double getPerimeter() override;
You're defining Circle::getPerimeter() in your .cpp file but there is no member function getPerimeter() in the Circle class declaration. All pure virtual functions need to be overriden in a derived class in order for the class to become concrete. So yes, virtual double getPerimeter(); and override if you're using C++11.
Also, it's good practice to declare simple getters const.
It should be done this way.
class Shape{
const char* name;
public:
Shape(const char* abc);
virtual ~Shape() {} // you should have virtual destructor here
virtual double getPerimeter()=0;
virtual double getArea()=0;
};
class Circle:public Shape{
double m_radius;
public:
Circle(double rad);
double getRadius();
virtual double getPerimeter(); // we need to re-declare it here
virtual double getArea(); // we need to re-declare it here
};
Here's a suggestion. Since Shape is an abstract class, we cannot create objects of the class; so get rid of its constructor. Since we are interested in area and parameter of shapes, define the functions as virtual.
So, here is a redeclaration of Shape class.
#ifndef __SHAPE__
#define __SHAPE__
namespace shape
{
class Shape
{
public:
virtual float getArea()=0;
virtual float getPerimeter()=0;
};
}
#endif
Now, redeclaration of Circle class
#ifndef __CIRCLE__
#define __CIRCLE__
#include "inc/Shape.hpp"
namespace shape
{
class Circle: public Shape
{
float radius;
public:
Circle(float=0.0);
float getArea();
float getPerimeter();
};
}
#endif
Now redefining Circle class
#include "inc/Circle.hpp"
namespace shape
{
Circle::Circle(float radius)
{
this->radius = radius;
}
float Circle::getArea()
{
return ((22/7) * (this->radius * this->radius));
}
float Circle::getPerimeter()
{
return (2 * (22/7) * this->radius);
}
}
Now, in the main class
#include <iostream>
#include "inc/Circle.hpp"
int main()
{
shape::Shape *circle = new shape::Circle(2.5);
std::cout << "Area: " << circle->getArea() << std::endl;
std::cout << "Perimeter: " << circle->getPerimeter() << std::endl;
return 0;
}
You may redeclare the classes without namespaces.
The point to note is that the type of object created should be of the parent class and the object itself should be a child class.
One last thing; all pure virtual functions in the abstract must be redeclared and redefined (overridden) in the derived classes.

Register class itself to factory

I have a question about the factory pattern. I programmed a factory, that has a static function called registerIt. It accepts a string for the class name and a pointer to the creator function of any class.
static void CharacterFactory::registerit(const std::string& classname, Creator creator)
{
table[classname] = creator;
}
The table is
std::map<std::string, CharacterFactory::Creator> CharacterFactory::table;
Creator
typedef std::auto_ptr<Actor> Type;
typedef Type (*Creator)();
Actor is the Base class
The classes itself have function for registering. For example the class "Player"
static void registerToFactory(){
CharacterFactory::registerit("Player",&create);
std::cout<<"player created"<<std::endl;
}
My Problem is, how can I tell the classes to register itself to the static factory? Everything works, if I call registerToFactory in the main class. But I want to do it more dynamically, so I only have to change code in new classes and not everywhere in my code.
The whole code below:
Factory.h:
#pragma once
#include "Actor.h"
#include <string>
#include<map>
namespace Character{
class Actor;
class CharacterFactory
{
public:
typedef std::auto_ptr<Actor> Type;
typedef Type (*Creator)();
CharacterFactory(void);
~CharacterFactory(void);
Type create(const std::string& classname);
static void registerit(const std::string& classname, Creator creator);
private:
static std::map<std::string, Creator> table;
};
}
Actor:
#pragma once
#include<string>
#include"CharacterFactory.h"
#include<iostream>
namespace Character{
class Actor
{
public:
static Actor* create(){std::cout<<"dummy"<<std::endl;return NULL;};
static Actor* create(int dmg){std::cout<<"dummy"<<std::endl;return NULL;};
Actor(void):damage(0),healthPoints(0),lastUpdate(0){};
Actor(int dmg):damage(dmg){};
~Actor(void);
virtual void update(void)=0;
virtual void update(int deltaMillis)=0;
protected:
int lastUpdate;
//Attribute
int healthPoints;
int damage;
//Amor amor;
//Weapon weapon;
//Ai ai;
//Networking
};
}
Player:
#pragma once
#include "Actor.h"
#include <stdio.h>
#include "CharacterFactory.h"
namespace Character{
#ifndef PLAYER_H
#define PLAYER_H
class Player:public Actor
{
public:
void update(void){};
void update(int deltaMillis){};
static std::auto_ptr<Actor> create(){
return std::auto_ptr<Actor>(new Player);
}
Player(void);
~Player(void);
static void registerToFactory(){
CharacterFactory::registerit("Player",&create);
std::cout<<"player created"<<std::endl;
}
inline int getDamage(void){ return damage;};
};
#endif
}
I hope you can help me :)
You can use either the constructor or dynamic initialisation expression for a static variable, and the compiler will ensure that runs before calling main().