Constructor can't make object from abstract class - c++

I'm programming a chessboard, and I've a base class chesspiece (schaakstuk in my language) and all the pieces like king, queen, are derived from that base class.
Now I wanted to create an object and fill a array with objects to start the game. Visual studio is giving me some errors on this line:
bord[1][kolom] = new Schaakstuk(Schaakstuk::WIT);
bord[6][kolom] = new Pion(Schaakstuk::ZWART);
that it is impossible to create from a abstract class. I don't see the error, first I thought it was that I was using a pure virutal function in my derived class but that isn't it, I'm only using a pure virtual function in my base class.
Constructor
for( int kolom = 0; kolom < SIZE; kolom++ )
{
bord[1][kolom] = new Pion(Schaakstuk::WIT);
bord[6][kolom] = new Pion(Schaakstuk::ZWART);
}
Pion.h
#include "Schaakstuk.h"
#include "Exceptions.h"
#ifndef PION
#define PION
class Pion: public Schaakstuk
{
public:
Pion(void);
~Pion(void);
bool ZetIsLegaal( int rij1, int kolom1, int rij2, int kolom2 ) const;
void PrintStuk( void ) const;
void GeefCor( int tabel [8][2], int rij, int kolom, int rij1, int kolom1) const;
bool IsPion( void ) const { return true; };
private:
bool ControleerZet( int rij1, int kolom1, int rij2, int kolom2 ) const;
};
#endif
Schaakstuk.h
#ifndef SCHAAKSTUK
#define SCHAAKSTUK
static const int SIZE1 = 8;
class Schaakstuk
{
public:
enum kleurType { WIT, ZWART };
Schaakstuk(kleurType kleur = WIT)
{
this->kleur = kleur;
};
virtual bool ZetIsLegaal( int rij1, int kolom1, int rij2, int kolom2 ) = 0;
virtual void PrintStuk( void ) = 0;
virtual void GeefCor( int tabel [8][2], int rij, int kolom, int rij1, int kolom1) = 0;
kleurType GeefKleur( void ) const { return kleur; };
virtual bool IsPion( void ) = 0;
protected:
bool static NietOutOfBounds( int rij, int kolom );
private:
kleurType kleur;
};
#endif
is my dropbox with the code files. Can someone help me?
this are the errors:
http://pastebin.com/82j08rry
and here is the full code
http://ideone.com/sWjxS

If the error is along the lines of "Can't instantiate abstract class" then the next line should tell you which method is abstract.
Most likely is you have declared a pure virtual in the base class but didn't override it (or override it properly; see below) in the derived class.
First check to make sure you have an override in Schaakstuk and Pion, and then check to make sure you haven't changed the signature at all. This could be a different const/volatile qualification, or different method parameters.

The word 'abstract' is the give away. You need to create from a concrete class - i.e. the compiler needs to know everything about the ins and outs of that object.

Related

How to implement Nested Class Constructor in Source file

I have a nested class called cell in my main class something.
I c
class Something{
class Cell
{
public:
int get_row_Number();
void set_row_Number(int set);
char get_position_Letter();
static void set_position_Letter(char set);
void set_whohasit(char set);
char get_whohasit();
Cell(int row,char letter,char whohasit);
private:
char position_Letter;
int row_Number;
char whohasit;
};
};
I wanna implement nested class constructor in .cpp file
Something::Cell Cell(int row,char letter,char whohasit){
Something::Cell::set_position_Letter(letter);
Something::Cell::set_row_Number(row);
Something::Cell::set_whohasit(whohasit);
}
But it is wrong. I assumed correct would be Something::Cell::Something::Cell at first but i don't think thats true either.
You are almost there. It's as simple as:
Something::Cell::Cell(int row,char letter,char whohasit){
Something::Cell::set_position_Letter(letter);
Something::Cell::set_row_Number(row);
Something::Cell::set_whohasit(whohasit);
}
But actually, I would strongly recommend you use initializers, rather than constructing the members uninitialized, and then assigning to them:
Something::Cell::Cell(int row, char letter, char whohasit)
:position_Letter(letter)
,row_Number(row)
,whohasit(whohasit)
{}
You need to make your inner class public, and the method set_Position_Letter cannot be static, because char position_Letter is not static (here is the header):
class Something
{
public:
class Cell {
public:
int get_row_Number();
void set_row_Number(int set);
char get_position_Letter();
void set_position_Letter(char set);
void set_whohasit(char set);
char get_whohasit();
Cell(int row,char letter,char whohasit);
private:
char position_Letter;
int row_Number;
char whohasit;
};
};
This is the cpp:
Something::Cell::Cell(int row, char letter, char whohasit) {
set_position_Letter(letter);
set_row_Number(row);
set_whohasit(whohasit);
}
void Something::Cell::set_position_Letter(char set) {
this->position_Letter = set;
}
void Something::Cell::set_whohasit(char set) {
this->whohasit = set;
}
void Something::Cell::set_row_Number(int set) {
this->row_Number = set;
}

invalid use of non-static data member 'Board::N'

This is the header:
class Board {
public:
friend class Game;
Board() = default;
Board(int n) : N(n) { }
Board& SetType(int, int, char);
void GetType(int, int);
Board& CreateEmptyBoard();
void BoardDisplay();
private:
int N = 0;// dimension
char Maze[15][15];
const static int MaxSize = 15;
};
class Game {
public:
Game() = default;
Game(int x, int y) : PosX(x), PosY(y) { }
void BuildGame();
void GameDisplay();
void MoveUp();
void MoveDown();
void MoveLeft();
void MoveRight();
private:
int PosX = 0;
int PosY = 0;
};
void Game::BuildGame() {
srand(time(NULL));
for (int i = 0; i < Board::N; i++) {
for (int j = 0; j < Board::N; j++) {
if (i == rand() % (Board::N) && j == rand() % (Board::N))
Board::Board& SetType(i, j, 'W');
}
}
}
In class Game's member function void BuildGame,I want to call member functionBoard& SetType(int,int,char) in class Board.I define this function in a header file and not show here. Then I build the project, I got invalid use of non-static data member 'Board::N' and 'SetType' was not declared in this scope. Like this
Where I wrong? I can't find it.
The compiler is letting you know that you are using an instance variable as a static. A static variable is associated with an entire class and not a single object, so it is called through the class name and not an object of the class. but it would need to be marked as static like so
class Board
{
public:
static Board& setType(int, int, char);
...
private:
static int N;
...
}
my instinct however tells me that you want to use it at an instance level, so you would write your void Game::buildGame() method using a Board that it creates (possibly making it an attribute of the Game class:
void Game::BuildGame() {
//make your board here. alternatively make an instance of the game
Board myBoard();
srand(time(NULL));
//in the following, use myBoard as the instance of a board.
for (int i = 0; i < myBoard.N; i++) {
for (int j = 0; j < myBoard.N; j++) {
if (i == rand() % (myBoard.N) && j == rand() % (Board::N))
myBoard.setType(i, j, 'W');
}
}
}
And a Board class that looks something like this. You will probably want your setType method to modify the instance and return void instead of returning another board reference.
class Board
{
public:
//this one will change this particular Board instance.
void setType(int, int, char);
//this one may make sense to be static if it is a factory method
//but why not use a constructor instead?
static Board& createEmptyBoard();
//maybe you meant something to reset the board to empty state.
void resetBoardToEmpty();
...
private:
int N;
...
}
while you're at it you might make it a struct (which has members public by default) as it seems to be a "hidden" holder class for the game, and this would alleviate the need to use a friend class (these are to be used judiciously as they can get messy really fast). using a struct would also allow you to make a ChessGame class that reuses the Board struct.
N isn't a static member of class Board, hence you'll need an instance of board to access it.
Your Game class actually needs to have a Board member variable to achieve that above mentioned instance.

Call member function on object pointer

I am trying to write a simple game in C++ and currently have my Game_Window class holding an array of pointers to game objects as follows:
class Game_Window {
private:
int width;
int height;
int num_objects;
public:
char** objects;
/* The rest of the class goes here */
}
Inside my Game_Window class I want to define a function that calls the "print()" function on all objects held in the game window "objects" array as follows.
void Game_Window::print_objects() {
for (int i = 0; i < num_objects; i++) {
(objects[i])->print(); /* THE PROBLEM IS HERE */
}
}
When I compile I get the following error:
game_window.cpp:29:15: error: member reference base type 'char' is not a structure or union
(objects[i])->print();
~~~~~~~~~~~~^ ~~~~~
1 error generated.
All objects in my game have a "print()" function so I know that's not the issue. Any help would be much appreciated.
I think I figured it out. I created a class called Game_Object that all my game objects will inherit, and gave it a print() method.
class Game_Object {
private:
Location location;
public:
Game_Object();
Location *get_location() { return &location; }
void print();
};
class Diver : public Game_Object {
public:
explicit Diver(int x, int y);
};
class Game_Window {
private:
int width;
int height;
int num_objects;
public:
Game_Object** objects;
explicit Game_Window(int width, int height);
~Game_Window();
int get_width() { return width; }
int get_height() { return height; }
int get_object_count() { return num_objects; }
bool add_object(Game_Object object);
void print_objects();
};
The invocation of print() is now:
void Game_Window::print_objects() {
for (int i = 0; i < num_objects; i++) {
objects[i]->print();
}
}
I ran it and it game me no errors.
The type of Game_Window::objects is char** (pointer to pointer to char). Hence objects[i] is the ith pointer, and pointers don't have print() methods, which is why (objects[i])->print(); fails with the described error.
Perhaps you meant to use print(objects[i]); instead?

Virtual function implementation C++ not working

I'm new to C++, and I'm trying to write a simple code to compare two objects of subclasses of a parent class called Comparable. I want each subclass to have its own implementation of a method to compare objects based on the data they hold, so I used the virtual keyword:
class Comparable {
public:
virtual int compare(Comparable *other);
};
For example, my subclass HighScoreElement would have its own implementation of compare that would compare the score of the object to the score of another HighScoreElement.
Here is my subclass HighScoreElement:
class HighScoreElement: public Comparable {
public:
virtual int compare(Comparable *other);
HighScoreElement(string user_name, int user_score); // A constructor
private:
int score;
string name;
};
But in my compare implementation in HighScoreElement, I first try to check if the current object's data is the same as other's data. But since the pointer to other is of class Comparable and not HighScoreElement, I can't reference other->score at all in my code, even though HighScoreElement is a subclass of Comparable.
Here is the full code so far:
#include <iostream>
using namespace std;
class Comparable {
public:
virtual int compare(Comparable *other);
};
class HighScoreElement: public Comparable {
public:
virtual int compare(Comparable *other);
HighScoreElement(int user_score, string user_name);
private:
string name;
int score;
};
HighScoreElement::HighScoreElement(int user_score, string user_name) {
name = user_name;
score = user_score;
}
int HighScoreElement::compare(Comparable *other) {
if (this->score == other->score) { // Compiler error right here, other->score is invalid.
// Code to do the comparing if two scores are equal...
}
}
I get a compiler error immediately when I write this code:
if (this->score == other->score)
because other doesn't have data called score, but its subclass, HighScoreElement, does. How can I fix my function implementation so that I can reference the data of "other?" I know my question may sound vague, but any help would be appreciated!
You could implement a virtual function GetScore(), possibly pure virtual in the base class, and use that instead of accessing the field score in your compare function. Make it a const method. On the other hand, Compare could be a method implemented in the base class, that uses this->GetScore() and other->GetScore()
Code stub:
class A {
virtual int getScore() const = 0;
inline bool compare(const A* in) {return (in && this->getScore() == in->getScore());}
//return false also if "in" is set to NULL
}
class B : public A {
int score;
inline int getScore() const {return score;}
}
You can cast the pointer passed to HighScoreElement::compare using "dynamic_cast" (it throws a bad_cast exception on failure).
int HighScoreElement::compare(Comparable *other) {
HighScoreElement *h = NULL;
try
{
ptr = dynamic_cast<HighScoreElement *>(other);
}
catch(std::bad_cast const &)
{
// Handle the bad cast...
}
if (this->score == ptr->score) {
// Code to do the comparing if two scores are equal...
}
}
If you are prepared to accept null pointers, you can use dynamic casts. You can have an overload for the case when you are comparing a HighScoreElement pointer to avoid an unnecessary cast.
#include <iostream>
using namespace std;
class Comparable {
public:
virtual int compare(Comparable *other) = 0; // made pure virtual to compile without definition
};
class HighScoreElement: public Comparable {
public:
virtual int compare(Comparable *other);
int compare(HighScoreElement *other); // comparing to a HighScoreElement ptr, no need to dynamic cast
HighScoreElement(int user_score, string user_name);
private:
string name;
int score;
};
HighScoreElement::HighScoreElement(int user_score, string user_name) {
name = user_name;
score = user_score;
}
int HighScoreElement::compare(Comparable *other) {
HighScoreElement * pHSE = dynamic_cast<HighScoreElement*>(other);
if (pHSE) {
return compare(pHSE);
} else {
return -1; // or however you want to handle compare to non HighScoreElement
}
}
int HighScoreElement::compare(HighScoreElement *other) {
if (this->score == other->score) {
;
}
}
Are you sure it's not
compare( Comparable other )
If (this->score == other.score)

C++ Pointer to Object as Class member

I'm trying to get two different classes to interact with eachother, for that I have in one class a pointer to an object of an other class, which is specified in the constructor.
Interaction works so far, I can change the paramters of the pointed-to object and I can see the changes, as I'm printing it on a terminal. BUT when I try to get a parameter from this object and try to print it to the terminal through the class which points to it I only get a zero value for an Int from which I know, cause of debug outputs, that it isn't zero, if called directly.
I will give you an example of the code:
Class A:
class Spieler
{
private:
int score;
Schlaeger *schlaeger;
int adc_wert;
int channel;
public:
Spieler(int x, Schlaeger &schl, int adc_wert_c=0, int channel_c=0 )
{
score=x;
schlaeger=&schl;
adc_wert=adc_wert_c;
channel=channel_c;
}
//....
void set_schl(Schlaeger &schl){ schlaeger=&schl;}
int getPosY(){ schlaeger->getSchlaeger_pos_y();}
int getPosX(){ schlaeger->getSchlaeger_pos_x();}
void setPosY(int y){ schlaeger->set_pos_y(y);}
void schlaeger_zeichen(){
schlaeger->schlaeger_zeichen();
}
void schlaeger_bewegen(){
schlaeger->schlaeger_bewegen(getADC());
}
//...
};
Class B:
class Schlaeger
{
private:
int schlaeger_pos_x;
int schlaeger_hoehe;
int schlaeger_pos_y;
public:
Schlaeger(int x=0, int h=5, int pos_y=15)
{
schlaeger_pos_x=x;
schlaeger_hoehe=h;
schlaeger_pos_y=pos_y;
}
int getSchlaeger_pos_x()
{
return schlaeger_pos_x;
}
int getSchlaeger_pos_y()
{
return schlaeger_pos_y;
}
int getSchlaeger_hoehe()
{
return schlaeger_hoehe;
}
void set_pos_y(int new_y)
{
schlaeger_pos_y=new_y;
}
};
The calls to the changing methods work, I can see the changes and I can see it in a debug output.
You're not returning the value in the getter
int getPosY(){ schlaeger->getSchlaeger_pos_y();}
should be
int getPosY(){ return schlaeger->getSchlaeger_pos_y();}