C++ Static Class Member and Non-default Constructor - c++

I have this class:
class Object
{
public:
private:
float _positionX, _positionY, _positionZ;
}
I need to do check and do some math every time a new value is assigned to them, and I also use these values in various places.
I'm looking for an easier way to assign and check values than having these methods:
class Object
{
public:
float GetPositionX();
void SetPositionX(float value);
//etc
private:
float _positionX, _positionY, _positionZ;
}
So I'm trying to do something like this:
static class Vector3
{
public:
Vector3(float *valueX, float *valueY, float *valueZ)
{
_valueX = valueX;
_valueY = valueY;
_valueZ = valueZ;
}
private:
float *_valueX, *_valueY, *_valueZ;
}
class Object
{
public:
Vector3 Position;
//Position = Vector3(&_positionX, &_positionY, &_positionZ);
private:
float _positionX, _positionY, _positionZ;
}
Just so I can call it like this anywhere else in the code:
Object *myObj = new Object();
myObj->Position.x = 1; //assign, checks are done here
float myValue = myObj->Position.x; //receive, no checks needed
But the compiler complains that Vector3 doesn't have a default constructor.
I also have a bunch of Object, and I'm not sure if I'm using the static Vector3 the right way (if it won't conflict with other object's values).
How can I get this working?

Add a default constructor to Vector:
Vector3()
{
_valueX = NULL;
_valueY = NULL;
_valueZ = NULL;
}

Related

Constructor setting all values to 0

So from an assignment I have from school, I have to make a default constructor that is supposed to set all floats and ints to 0 and all strings to "NA".
Earlier it was pretty easy I had to just do a constructor to set volume to 0, calories to 0 and etc.
My question is,
How does the syntax for setting all floats, and ints to 0 and trying to get strings to all say "NA"?
This is what I had so far
class Candy {
private:
float sweetness;
protected:
string color;
//CONSTRUCTOR//
void setName(string n);
void setFloat(float f);
void setInt(int i);
This is on another cpp file we have to do.
Candy::Candy() {
Candy(string n) {
setName(n);
}
Candy bo("NA");
}
Am I in the right direction? I am really new to this, and I am not very good with syntax. Thanks!
Use the constructors initialization list:
class Candy {
private:
float sweetness;
protected:
string color;
public:
Candy() : sweetness(0.0f), color("NA") { }
};
Or (in C++11 or later), use in-class initializers:
class Candy {
private:
float sweetness = 0.0f;
protected:
string color = "NA";
public:
Candy() = default;
};
Ok lets see your header file:
class Candy {
public:
Candy();
private:
float sweetness;
protected:
string color;
void setName(string n);
void setFloat(float f);
void setInt(int i);
};
You need to declare the constructor in the public section, so you can call it from outside. It has no return type and takes no parameters (it should set everything to 0 on its own and not values you provide it).
In the cpp-file you implement the constructor and the other methods you declared before:
#include "Candy.h" // Or whatever the filename is
Candy::Candy() {
sweetness = 0.0f;
color = "NA";
}
// Implement the other methods, I don't know what they should do
// Example:
void Candy::setName(string n) {
// Do what you want
}
Note you have to implement every method otherwise you will get errors.

Setting x or y of a POINT2f/VECTOR2f variable in a class using a member function

I have the following classes:
//----------------------------------------------------------------------
// CHARACTER CLASS
//----------------------------------------------------------------------
class Character
{
private:
POINT2f char_position;
public:
VECTOR2f char_velocity;
Character();
~Character();
// Mutators
void SetChar_Position(POINT2f p);
void SetChar_Velocity(VECTOR2f v);
// Accessors
POINT2f GetChar_Position();
VECTOR2f GetChar_Velocity();
};
//----------------------------------------------------------------------
// PLAYER CLASS - INHERITED FROM "CHARACTER" CLASS
//----------------------------------------------------------------------
class Player : public Character
{
private:
public:
int health;
Player();
~Player();
void SetPlayer_Health(int h);
int GetPlayer_Health();
};
So essentially the player class inherits from the character class.
The Character class has member function which lets you set the characters position and velocity, which take in a POINT2f and VECTOR2f.
Within my main bit of code I create a player character Player Player1 and than set the balls velocity and position if a button is pressed:
if (ui.isActive('A')) // Check to see if "A" key is pressed
{
// Player Ball
Player1.SetChar_Velocity.x = -12.0;
Player1.SetChar_Position.x += (Player1.GetChar_Velocity.x*dt);
Player1.SetChar_Velocity.x += (acceleration*dt);
}
I'm currently getting errors that say left of .x must have class/struct/union, so I change Player1.SetChar_Velocity.x = -12.0; to Player1.SetChar_Velocity().x = -12.0; which than brings up the error expression must have class type and to few arguments in function call.
Does anyone know of a method that will allow my to only manipulate the x number of the char_velocity only. also I understand that my code to Set the .x velocity isn't correct because I'm not passing in a VECTOR2f value.
In order to achieve what you want to do, you will want the return type of you Get_ methods to be a reference (wiki). Your code will then look like
class Character
{
private:
POINT2f char_position;
public:
VECTOR2f char_velocity;
// Accessors
POINT2f& GetChar_Position() { return char_position; }
VECTOR2f& GetChar_Velocity() { return char_velocity; }
};
Also, it is often advised or required to be able to preserve const-correctness in your code, so you might want to add
const POINT2f& GetChar_Position() const { return char_position; }
const VECTOR2f& GetChar_Velocity() const { return char_velocity; }
This will allow you to do some calls like
POINT2f current_pos = a_char.GetChar_Position(); // const
a_char.GetChar_Velocity().x += 2; // non-const
Please note that it is often advised to pass the structures as const references instead of copies (although this might not hold true depending on your c++ version and your types, you can see this question for clarification), hence change your
void SetChar_Position(POINT2f pos) { char_position = pos; }
void SetChar_Velocity(VECTOR2f vel) { char_velocity = vel; }
to
void SetChar_Position(const POINT2f& pos) { char_position = pos; }
void SetChar_Velocity(const VECTOR2f& vel) { char_velocity = vel; }

Seg fault when accessing a struct

I put the whole code on github: https://github.com/marianatuma/CG
I have a struct called point, declared in line.h, and a class line that has two points, start and end. EDIT: I didn't add it before, but Line inherits from GraphObj. graphObj.h:
class GraphObj {
private:
type t;
std::string name;
public:
GraphObj(type t, std::string name);
type getType();
std::string getName();
};
line.h:
#ifndef LINE_H
#define LINE_H
struct point {
double x;
double y;
};
class Line {
private:
point start;
point end;
public:
Line(type t, std::string name) : GraphObj(t, name) {};
void setStart(double x, double y);
void setEnd(double x, double y);
point getStart();
point getEnd();
};
#endif
line.cpp:
#include "line.h"
void Line::setStart(double x, double y) {
this->start.x = x;
this->start.y = y;
}
void Line::setEnd(double x, double y) {
this->end.x = x;
this->end.y = y;
}
point Line::getStart() {
return start;
}
point Line::getEnd() {
return end;
}
I always get a segmentation fault when I try accessing any of these points. I tried making them public, didn't work. I also tried using getters and it also didn't work. Here's how I'm initializing them:
The line is in a list of lines, called a display file, which will be used with cairo to draw them.
displayFile.h:
#ifndef DISPLAYFILE_H
#define DISPLAYFILE_H
#include <list>
#include "graphObj.h"
class DisplayFile {
private:
std::list<GraphObj*>* objectList;
std::list<GraphObj*>::iterator it;
int size;
public:
DisplayFile();
void add(GraphObj* g);
GraphObj* getNextObject();
void resetIterator();
int getSize();
};
#endif
displayFile.cpp:
#include "displayFile.h"
DisplayFile::DisplayFile() {
this->objectList = new std::list<GraphObj*>();
this->it = objectList->begin();
this->size = 0;
}
void DisplayFile::add(GraphObj* g) {
std::list<GraphObj*>::iterator tempIt;
tempIt = objectList->begin();
this->objectList->insert(tempIt, g);
this->size++;
}
GraphObj* DisplayFile::getNextObject() {
return *++it;
}
void DisplayFile::resetIterator() {
it = objectList->begin();
}
int DisplayFile::getSize() {
return size;
}
DisplayFile returns a GraphObj instead of the objectList, so it has to iterate through objectList by itself, hence the resetIterator (so when the main code is done traversing the list it will reset the iterator to the start of the list, but I'm not calling this method anywhere so far). The code in main.cpp where an instance of Line is used is below:
static void do_drawing(cairo_t *cr)
{
/* not using these right now
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_set_line_width(cr, 0.5);
*/
int size = df->getSize(); //df is the list
for(int i = 0; i < size; i++) {
Line* g = df->getNextObject();
point start = g->getStart();
}
}
The problem only starts when I try accessing the points, I can access other attributes from that line instance without problems. What am I doing wrong?
edit: I hope I've provided enough information, the main code is long and doesn't really have much to do with the line class, so I don't think it's relevant.
The problem lies with your list class.
class DisplayFile {
private:
std::list<GraphObj*>* objectList; // Why not just a list<GraphObj*>
std::list<GraphObj*>::iterator it; // Why use this?
int size; // WHY manually keep track of a STL container size?
public:
DisplayFile();
void add(GraphObj* g);
void resetIterator();
int getSize();
};
In your implementation file:
GraphObj* DisplayFile::getNextObject() {
return *++it;
}
As I already commented: this is the winner... Think about it, what if it already happens to be the last element on the list, and you ask for getNextObject()? Boom
I don't see why you couldn't just replace the entire DisplayFile class with a nice and plain std::list:
std::list<GraphObj*> objectList;
// I would also advice to change to smart pointers here
// for example: std::list<std::shared_ptr<GraphObj> > objectList;
// or std::list<std::unique_ptr<GraphObj> > objectList;
Then you would just use the STL methods to work with the list:
Add an item to the front: (for the sake of simplicity lets imagine that GraphObj has a default constructor)
GraphObj* g = new GraphObj();
objectList.push_front(g);
// If you change to smart pointers:
// objectList.push_front(std::make_shared<GraphObj>());
// or
// objectList.push_front(std::make_unique<GraphObj>());
Get the list size:
objectList.size();
Traverse the list:
for (std::list<GraphObj*>::const_iterator it = objectList.begin();
it != objectList.end();
++it)
{
point start = (*it)->getStart();
// or whatever you need to do here
}
Or with the much nicer range for:
for (const auto & graphObj : objectList)
{
point start = graphObj->getStart();
// or whatever you need to do here
}
Because you are not initilaizing the structs .
Change your constructor a bit
From this
Line(type t, std::string name) : GraphObj(t, name) {};
to
Line(type t, std::string name) : GraphObj(t, name) , start(),end() {};
This may help.
The problem might be coming from your getStart and getEnd because they return a point, which will create a copy(I think) of your start or end point, ie not using the point from line but copies. This usually isn't a big deal but if you want to change an x or y value and have the new value stick you'll need a reference to the original points x and y values.
Try this, change
point getStart();
point getEnd();
into
point *getStart() { return &start; }
point *getEnd() { return &end; }
and in your do_drawing(cairo_t *cr) change
point start = g->getStart();
to
point *start = g->getStart();
start->x = value; // or
double value = start->x; // or however you want to use start

Initializing object to an empty list from a reference parameter

class ListOfGifts
{
private:
Gift list[50];
int count = 0;
public:
void suggest(ListOfGifts& affordable, float dollarLimit) const
{
// how do I initialize affordable to an empty list without a constructor
}
}
Trying to initialize a list from a parameter that is a reference. How can I do this?
Use an std::array:
class ListOfGifts
{
private:
std::array<Gift, 50> list;
int count = 0;
public:
void suggest(ListOfGifts& affordable, float dollarLimit) const
{
affordable.list = std::array<Gift, 50>{};
}
}
FYI, C++ is literally built on constructors. They will come up eventually, and they're actually quite helpful.

Virtual function issue in C++ [duplicate]

This question already has answers here:
Why is virtual function not being called?
(6 answers)
Closed 9 years ago.
AoA,
I am making a console game of chess, But I am stuck at polymorphism, below is the classes and functions definitions
/* old Part
//Base Class
class Piece /*Parent class */
{
protected:
Position* pCoord;
std::string color;
char symbol;
public:
Piece(Position* Coord,std::string Color,char symbol);
Position GetCurrentPos();
std::string GetColor();
void SetColor(std::string color);
void Draw();
virtual bool SetPos(Position* newPos){MessageBox(NULL,L"Virtual Running",L"Error",MB_OK); return true;};
virtual ~Piece();
};
/* Inherited classes */
//Child classes
class Pawn: public Piece
{
private:
std::vector<Position>* allowPos;
public:
Pawn(Position* Coord,std::string Color,char symbol);
~Pawn();
std::vector<Position>* GetThreatendFields();
bool isValidMove(Position* newPos);
bool SetPos(Position* newPos);
};
//Child classes
class Bishops: public Piece
{
private:
std::vector<Position>* allowPos;
public:
Bishops(Position* Coord,std::string Color,char symbol);
~Bishops();
std::vector<Position>* GetThreatendFields();
bool isValidMove(Position* newPos);
bool SetPos(Position* newPos);
};
//Here is the implementation of child class function SetPos
bool Pawn::SetPos(Position* newPos)
{
bool isSet = false;
this->pCoord = new Position();
this->pCoord = newPos;
isSet = true;
MessageBox(NULL,L"Child function running",L"Yuhuu!",MB_OK);
return isSet;
}
class ChessBoard
{
private:
Position ptr; //dummy
int SelectedPiece;
vector<Piece> pPieceSet;
bool isSelected;
public:
ChessBoard();
~ChessBoard();
void ShowPieces(Player *p1,Player *p2);
void Draw();
void MouseActivity();
void Place(Piece& p);
};
//it just shows the peices acquired from player objects..dummy vector pointer
void ChessBoard::ShowPieces(Player* p1,Player* p2)
{
std::vector<Piece>* vPiece = p1->GetPieces();
for( int i=0;i<vPiece->size();i++ )
{
Piece& piece = vPiece->at(i);
Place(piece);
piece.Draw();
}
vPiece = p2->GetPieces();
for( int i=0;i<vPiece->size();i++ )
{
Piece& piece = vPiece->at(i);
Place(piece);
piece.Draw();
}
}
*/
/*new part
I did what you say
Player::std::vector<Piece*> *vPieceSet;
Player::Player(int turn)
{
this->turn = turn%2;
this->vPieceSet = new std::vector<Piece*>;
}
void Player::Initialize() //Initial and final ranges for position
{
//Initialization of pieces to their respective position
Position pos;
Piece *pPiece;
if( this->turn == 0 )
{
this->SetName("Player 1");
for( int i=8;i<16;i++ )
{
pos.SetPosition(i);
Pawn pPawn(&pos,"blue",'P');
pPiece = &pPawn;
this->vPieceSet->push_back(pPiece);
}
//other classes same as above
}
It runs fine at initialzation function(stores all classes fine) but when use function to get the vector object
std::vector<Piece*>* Player::GetPieces()
{
std::vector<Piece*>* tPieces = this->vPieceSet;
return tPieces;
}
//In main.cpp
it doesnot return the vector object
Player p1(0),p2(1);
p1.Initialize();
p2.Initialize(); //initialization done perfectly while debugging
vector<Piece*> *obj = p1.GetPieces(); //returns garbage
Piece* pObj = obj->at(0); //garbage
cout<<pObj->GetColor(); // garbage
*/new part
Sounds like I have another problem!
When you use polymorphism, what you are really trying to do is instantiate an object of derived type and call the methods on that object through a pointer or reference to the base object.
class Foo
{
public:
virtual void DoIt () { cout << "Foo"; }
};
class Bar
:
public Foo
{
public:
void DoIt () { cout << "Bar"; }
};
int main()
{
Foo* foo = new Bar;
foo->DoIt(); // OUTPUT = "Bar"
Foo& fooRef = *foo;
fooRef.DoIt(); // OUTPUT = "Bar"
}
In order for this to work, you need to use either a pointer or a reference to the object. You can't make a copy of the object using a the base class. If you make a copy, you will slice the object.
int main()
{
Foo* foo = new Bar;
foo->DoIt(); // OK, output = "Bar"
Foo fooCopy = *foo; // OOPS! sliced Bar
fooCopy.DoIt(); // WRONG -- output = "Foo"
}
In your code, the Piece class is intended to be polymorphic, and in your ChessBoard class you have a vector of this class:
class ChessBoard
{
private:
vector<Piece> pPieceSet;
};
Since this is a vector of the Piece object itself, and not a pointer-to-Piece, anything you put in here will be sliced. You need to change pPieceSet to be a vector of pointers-to-Piece:
vector <Piece*> pPieceSet;
You have further problems in Initialize, which need to be refactored anyway. For one thing, you have another vector of Piece objects, and there are two problems here. First, it needs to be a vector of pointers, and second, why do you need another vector at all when there is already one associated with the ChessBoard? I didn't thouroughly examine your code so maybe you do need it, but this seems like an error. There should probably just be one collection of pieces, in the ChessBoard.
In your Initialize method:
Piece *pPiece;
// ...
Pawn pPawn(&pos,"blue",'P');
pPiece = &pPawn;
vPieceSet.push_back(*pPiece);
There are a couple of problems. One, you are pushing back a sliced copy of the Piece, which will be fixed when you change your vector to store pointers. Second, if you just change this like so:
Piece *pPiece;
// ...
Pawn pPawn(&pos,"blue",'P');
pPiece = &pPawn;
vPieceSet.push_back(pPiece); // <-- not dereferencing
You will have a new problem because you'll be storing the pointer to a local (automatic) variable. Best is to do this:
Piece* pPiece = new Pawn (...);
// ...
vPieceSet.push_back (pPiece);
Please don't forget to delete everything you new. This is best handled by using smart pointers rather than raw pointers. In C++03 we have auto_ptr, but those can't go in a vector. Instead you'll need to use Boost or something else, or just store raw pointers. In C++11, we now have unique_ptr (preferred) and shared_ptr, which can go in to a vector.
In C++11, the best solution here is to have a vector declared as:
vector <unique_ptr <Piece> > pPieceSet;
...unless you have some compelling need to use shared_ptr instead.
As others have mentioned, it is a slicing issue, and the issue is created here:
class Player
{
private:
std::string pName;
std::vector<Piece> vPieceSet; // <-- This is your problem
int turn;
public:
Player(int turn);
~Player();
void Initialize();
std::string GetName();
void SetName(std::string Name);
int GetTurn();
std::vector<Piece>* GetPieces();
};
You are storing them in the vector as instances of Piece, which is slicing off the details of the piece (e.g. the Bishop implementation). You should modify it to something like:
class Player
{
private:
std::string pName;
std::vector<Piece*> vPieceSet; // or better, use a smart pointer wrapper
int turn;
public:
Player(int turn);
~Player();
void Initialize();
std::string GetName();
void SetName(std::string Name);
int GetTurn();
std::vector<Piece*> GetPieces(); // note this change as well
};
With your additional question/edit, you are getting another unrelated problem:
void Player::Initialize() //Initial and final ranges for position
{
Position pos; // position is declared inside the scope of Initialize
Piece *pPiece;
if( this->turn == 0 )
{
this->SetName("Player 1");
for( int i=8;i<16;i++ )
{
pos.SetPosition(i);
Pawn pPawn(&pos,"blue",'P'); // you are passing the address of position to the Pawn, and Pawn is within the scope of this loop
pPiece = &pPawn; // you are storing the address of the Pawn
this->vPieceSet->push_back(pPiece);
}
// Pawn is now out of scope and pPiece points to the memory location Pawn *used* to be at (but will likely be overwritten soon).
// As soon as this function returns, you have the same problem with pos
}
You need to allocate those variables on the heap (hence the reason we suggested smart pointer wrappers).