Inheritance variables not accessible - c++

I want to access the variables from inherited classes. However, the compiler gives the error:furniture.cpp:55:9: error: 'int stool::n_StoolLegs' is private within this context one.n_StoolLegs -1;.
This is a homework assignment however, the assignment says that I need to use 4 variables of type stool. So I inherited the class. Is there maybe another option to modify to modify the inherited variables?
furniture .hpp
#include <ostream>
#include <string>
#ifndef FURNIURE_HPP
#define FURNITURE_HPP
class stool{
private:
int n_StoolLegs;
int n_seats;
public:
void setStoolLegs(int);
int getStoolLegs();
void setSeats(int);
int getSeats();
};
class table {};//not relevant
class furniture: public stool, public table
{
private:
stool one;
stool two;
stool three;
stool four;
table first;
public:
furniture(){
one.setStoolLegs(4);
one.setSeats(1);
void makeMoreHipster();
};
#endif
furniture.ccp:
#include <iostream>
#include "furniture.hpp"
//begin stool
void stool::setStoolLegs (int nLegs){
n_StoolLegs = nLegs;
};
int stool::getStoolLegs(){
return n_StoolLegs;
};
void stool::setSeats (int nSeats){
n_seats = nSeats;
};
int stool::getSeats(){
return n_seats;
};
//end stool//
// begin table
//not relevant
// end table
//start furniture
void furniture::makeMoreHipster(){
one.n_StoolLegs -1;
};
// end furniture//

With inheritance, private variables are not accessible.
Use protected.

Related

Friending class while there's an object of friending class inside friended class

the title might seem a little bit confusing but I'll try to explain that.
I've got a class CGameMode:
#pragma once
#include <string>
#include <iostream>
#include "../Hero/Hero.h"
#include "../Weapon/Weapon.h"
#include "../Armor/Armor.h"
class CGameMode
{
private:
CHero Hero;
CWeapon Weapon;
CArmor Armor;
std::string FileName = "save.txt";
protected:
public:
void InitializeGame();
void CreateGame();
void LoadGame();
void SaveGame();
CGameMode* GetGameMode() { return this; }
};
As you can see, the class contains objects of classes: CHero, CWeapon and CArmor. Let's take a look on one of these classes:
#pragma once
#include "../Enemy/Enemy.h"
#include "../GameMode/GameMode.h"
class CHero : public CEnemy
{
private:
int Energy = 0;
int ExperiencePoints = 0;
int Level = 0;
friend class CGameMode;
protected:
public:
CHero();
CHero(std::string Name, int Health, int Energy, int ExperiencePoints, int Level);
};
The most important is this line of code:
friend class CGameMode;
(CArmor and CWeapon also friend the CGameMode class).
The problem is the program does not compile. But if I remove Hero, Weapon and Armor members from CGameMode class, the program compiles and everything works just fine.
So the question is: How can I make the CGameMode class friended with CWeapon, CArmor and CHero and in the same time, the objects of these classes can be contained by CGameMode?

How do I access data inside an array initialized by constructors in a derived class?

Say I make a class collection
#ifndef COLLECTION_H
#define COLLECTION_H
#include <array>
class collection
{
protected:
std::array<std::shared_ptr<items>, 4> m_item;
public:
collection(std::array<std::shared_ptr<items>, 4> item)
: m_item(item)
{}
auto operator[] (size_t index) { return m_item(index); };
};
#endif //COLLECTION_H
and I create a child class items that initializes the data members inside the parent class
#include "collection.h"
#include "items.h"
class variation_1 : public collection
{
public:
variation_1() : Base( {std::make_shared<item_1>(),
std::make_shared<item_2>(),
std::make_shared<item_3>(),
std::make_shared<item_4>()}) {}
};
I used shared pointers inside the array because I have another class with its own set of functions that initialize the data members of an item class.
//items.h file
#ifndef ITEMS_H
#define ITEMS_H
#include <string>
class items
{
protected:
std::string m_ItemName;
int m_Cost;
public:
items(const std::string& name, int cost)
: m_ItemName(name), m_Cost(cost)
{}
virtual std::string getItemName() const { return this->m_ItemName; };
virtual int getItemCost() const { return this->m_Cost; };
};
#endif //ITEMS_H
#include "items.h"
class item_1 : public items
{
public:
item_1() : items("Item 1", 40)
{}
};
//and so on and so forth..
My question is, how do I access and print the different values inside the item array every time a new object of data type collection is created? Also, I'm still very new to this, so I'm not entirely sure if I am using the shared_ptr correctly. If there are better ways to go about this, I'd appreciate it if you'd point me (pun not intended) in the right direction.

chess game - error in abstract class

#pragma once
#include <string>
#include <iostream>
using namespace std;
class Chess_tool
{
public:
Chess_tool(string color, char name);
virtual bool legal_movement(int source[], int dest[]) const = 0;
private:
string _color;
char _name;
};
Im trying to create chess game, so I create abstract class for chess tool (queen, king, rook...)
I also created king tool to check my code:
#pragma once
#include "Chess_tool.h"
class King : Chess_tool
{
public:
King(string color, char name);
virtual bool legal_movement(int source[], int dest[]);
};
and I create game_board class:
#pragma once
#include "Game_board.h"
#include "Chess_tool.h"
#include <iostream>
#define BOARD_SIZE 8
using namespace std;
class Chess_tool;
class Game_board
{
public:
Game_board();
~Game_board();
void move(string panel);
protected:
Chess_tool* _board[BOARD_SIZE][BOARD_SIZE];
};
the problem is here, when i try to add object to the matrix its show me error :
1 IntelliSense: object of abstract class type "King" is not allowed:
pure virtual function "Chess_tool::legal_movement" has no overrider
#pragma once
#include "Chess_tool.h"
#include "Game_board.h"
#include "King.h"
using namespace std;
enum Turn { WIHTE, BLACK };
class Manager : Game_board
{
public:
Manager();
~Manager();
virtual bool legal_movement(int source[], int dest[]) const = 0;
};
....
#include "Manager.h"
Manager::Manager()
{
_board[0][0] = new King();
}
The member function in the base class is const-qualified, not in the derived class.
So these are not the same functions through inheritance. You've declared a new virtual function, not overriden the first one.
Add const to the second one so that it actually override the base class function.
Remember that for virtual function overriding to kick in, there are a few condition to actually satisfy. They must have:
the same name
the same return type
the same parameters count and type
the same const-qualification (our case here)
a few other minor things (for example, compatible exceptions specifications)
If any condition isn't satisfied, you create a very similar, but different, function for the compiler.
With C++11, you should use override for the functions you want to override, so the compiler knows your intention and tells you that you've made a mistake. E.g.:
virtual bool legal_movement(int source[], int dest[]) override;
// ^^^^^^^^

Singleton pattern used on another class

So I am trying to implement a program that has a scoreboard and two players, I am trying to make it so that the two players share a scoreboard using the singleton pattern. However when I try to use methods on the global scoreboard defined in the player classes I always get a "run failed" message.
These are my two header files, I can provide the full implementation if it's necessary.
#ifndef PLAYER_H
#define PLAYER_H
#include "scoreboard.h"
#include <string>
#include <fstream>
class Player{
private:
std::ifstream file1;
std::ifstream file2;
static Scoreboard* _game;
public:
static Scoreboard* Game();
void makeMove(const char,const std::string);
};
#endif
#ifndef SCOREBOARD_H
#define SCOREBOARD_H
class Scoreboard{
private:
int aWin;
int bWin;
int LIMIT;
int curCounter;
public:
void resetWins();
void addWin(char);
void makeMove(const int, char);
void startGame(const int, const int);
int getWin(char);
int getTotal();
int getLimit();
};
#endif /* SCOREBOARD_H */
in player.cc
Scoreboard* Player::_game = 0;
Scoreboard* Player::Game(){
if (_game = 0)
{
_game = new Scoreboard;
_game->resetWins();
}
return _game;
}
Along with the makeMove method
Your Scoreboard instance does not need to be a pointer:
static Scoreboard _game;
// ...
static Scoreboard& Game() { return _game; }
Or alternatively, just leave out the class declaration of _game:
// you can either make this function static or non-static
Scoreboard& Game()
{
static Scoreboard game; // but this variable MUST be static
return game;
}
That will do the same thing without the memory management issues.
This will create a single instance of Scoreboard for all Players. If you only ever wanted to have a single instance of Scoreboard (e.g. if you had a Referees class that needed to see the scoreboard as well), you would modify your scoreboard class:
class Scoreboard
{
private:
// all your data members
Scoreboard() {} // your default constructor - note that it is private!
public:
// other methods
Scoreboard& getInstance()
{
static Scoreboard instance;
return instance;
}
};
Then, to access it in your other classes, you would include the scoreboard header and use it as:
#include "Scoreboard.h"
void my_func()
{
Scoreboard& scoreboard = Scoreboard::getInstance();
scoreboard.DoSomething();
}
In Player::Game, you have written
if (_game = 0)
that is setting _game = 0 and evaluating to false, so that you don't actually create the scoreboard. Change it for:
if (_game == 0)

C++ Event handler with derived classes through a base class array

I have been trying to make a game engine for some time, and for the most part it has been turning out quite well, considering it's the first one i've made. But when I started to make an event send/recieve system with derived classes contained in a base class pointer vector array, I had some trouble making the reciever get the class type and use the proper function; here's what I have:
This is my base class Object:
object.h:
#include "all.h" //Contains '#include "SDL/SDL.h"' and constant variables.
#include <vector>
#include "mask.h" //An unimportant class used for collision checking
class Body;
class Room;
class Object//Objects that belong here are those without step events.
{
public:
vector<vector<Room> > *world_map;//Should hold the address of the world map.
Room *room;//The room holding this object.
unsigned int x;
unsigned int y;
unsigned int pos;//Position of the object in the room's list.
int depth;//The deeper it is, the later it will be drawn.
virtual void draw(SDL_Surface *buffer,int viewx, int viewy){}
virtual void interact(Body *body);//Sends a pointer of this object to the
//the obj_event function of the body calling it.
Object(unsigned int xx=0, unsigned int yy=0,int d=0):x(xx),y(yy),depth(d){}
};
#endif // INSTANCE_H_INCLUDED
object.cpp:
#include "object.h"
#include "body.h"
void Object::interact(Body *body)
{
body->obj_event(this);
}
This is my derived class Body:
body.h:
#ifndef BODY_H_INCLUDED
#define BODY_H_INCLUDED
#include "all.h"
#include "object.h"
class Entity;
class Enemy;
class Player;
class Body : public Object//Objects that belong here are those with step events.
{
public:
int priority;//Decides which body will perform their step event first.
virtual void step()=0;
Body(int xx=0, int yy=0, int d=0, int p=0):Object(xx,yy,d),priority(p){}
//These scripts are for handling objects and bodies it has called through
//interact()
virtual void obj_event(Object *object){}
virtual void obj_event(Entity *entity){}
virtual void obj_event(Enemy *enemy){}
virtual void obj_event(Player *player){}
};
#endif // BODY_H_INCLUDED
there is no body.cpp
This is my derived class of Body, Entity:
entity.h:
#ifndef ENTITY_H_INCLUDED
#define ENTITY_H_INCLUDED
#include "all.h"
#include "body.h"
#include "items.h"
#include <vector>
#include "mask.h"
class Entity : public Body
{
public:
vector<Item> inv;
unsigned int width;
unsigned int height;
Mask mask;
Entity(int xx,int yy,int w,int h,int d=0,int p=0);
void step();
void collide_action(Entity *entity);
virtual void obj_event(Player *player);
virtual void obj_event(Enemy *enemy);
};
#endif // ENTITY_H_INCLUDED
entity.cpp:
#include "entity.h"
#include "room.h"
#include "player.h"
#include "enemy.h"
Entity::Entity(int xx,int yy,int w,int h,int d,int p):Body(xx,yy,d,p),width(w),height(h),mask(xx,yy,w,h,m_rectangle)
{}
void Entity::step()
{
for(int iii=0;iii<room->inv.size();iii++)//Iterates through objects
{
room->inv[iii]->interact(this);
mask.update(x,y,width,height);
}
for(int iii=0;iii<room->index.size();iii++)//Iterates through bodies
{
room->index[iii]->interact(this);
mask.update(x,y,width,height);
}
}
void Entity::collide_action(Entity *entity)
{
if(entity!=this)
{
if (mask_collide(mask,entity->mask))
{
short xchange;
short ychange;
if (entity->x<x)
{
xchange=width-(x-entity->x);
}
else
{
xchange=(entity->x-x)-width;
}
if (entity->y<y)
{
ychange=height-(y-entity->y);
}
else
{
ychange=(entity->y-y)-height;
}
if(abs(xchange)<abs(ychange))
x+=xchange;
else
y+=ychange;
}
}
}
void Entity::obj_event(Player *player)
{
collide_action(player);
}
void Entity::obj_event(Enemy *enemy)
{
collide_action(enemy);
}
This is my derived class of Entity, Player:
player.h:
#ifndef PLAYER_H_INCLUDED
#define PLAYER_H_INCLUDED
#include "all.h"
#include "body.h"
#include "items.h"
#include <vector>
#include "mask.h"
#include "entity.h"
enum keylist
{
kl_left=0,
kl_up=1,
kl_right=2,
kl_down=3,
};
class Player : public Entity
{
public:
SDLKey keys[4]; //List of action's corresponding keys.
Player(int xx,int yy,int w,int h,int d=0,int p=0);
void step();
void draw(SDL_Surface *buffer,int viewx,int viewy);
void interact(Body *body);
};
#endif // PLAYER_H_INCLUDED
player.cpp:
#include "player.h"
#include "room.h"
Player::Player(int xx,int yy,int ww,int hh,int dd,int pp):Entity(xx,yy,ww,hh,dd,pp)
{
//Default keys, can be changed.
keys[kl_left]=SDLK_LEFT;
keys[kl_up]=SDLK_UP;
keys[kl_right]=SDLK_RIGHT;
keys[kl_down]=SDLK_DOWN;
}
void Player::step()
{
Uint8 *key=SDL_GetKeyState(NULL);
if (key[keys[kl_left]])
x-=1;
if (key[keys[kl_right]])
x+=1;
if (key[keys[kl_up]])
y-=1;
if (key[keys[kl_down]])
y+=1;
mask.update(x,y,width,height);
Entity::step();
}
void Player::draw(SDL_Surface *buffer,int viewx,int viewy)
{
FillRect(buffer,x-viewx,y-viewy,width,height,0xFF0000);
}
void Player::interact(Body *body){body->obj_event(this);}
I have another class Enemy, but it's pretty much exactly like player (without the keyboard controls).
Now here's my problem (not error), for every object I want any body to perform an event for, I need to make virtual functions of ALL of them in this base class, that way if any object calls body->obj_event(this), it will pick the proper function with the most derived argument.
For example, if Player called object->interact(this) of an enemy, the enemy would first use it's base class Object's virtual function interact(Body*), which would then check the derived classes if they have an identical function (which enemy does), and then enemy calls body->obj_event(this) of the player body through it's base class, Body. The player body would then first use it's base class Body's virtual function obj_event(Enemy*), which would then check the derived classes if they have an identical function (which Entity does), and then Entity executes obj_event(Enemy*). At least that's how I understand it.
What I'd like to have is a way for any derived class to call interact of any other derived class through it's base function, and would then have it call it's obj_event function for the derived class, without having to have any of the Base classes know about their derived classes.
As I mentioned, this is my first time making an engine, and I'm probably using methods that are completely hectic and error-prone. I was thinking that templates might be able to help out in this situation, but don't know how to implement them.