Need help understanding this piece of code from a book - c++

This code is from "Sams Teach Yourself C++".It might be something simple but I'm having a hard time trying to figure this out. I get the same output if I don't use the getSpeed() method. So do I need this? If not, why does this book use it?
#include <iostream>
class Tricycle
{
public :
int getSpeed();
void setSpeed(int speed);
void pedal();
void brake();
private :
int speed;
};
int Tricycle::getSpeed() //<-- Why do I need this method
{
return speed;
}
void Tricycle::setSpeed(int newSpeed)
{
if (newSpeed >= 0)
{
speed = newSpeed;
}
}
void Tricycle::pedal()
{
setSpeed(speed + 1);
std::cout << "\nPedaling; tricycle speed " << speed << " mph\n";
}
void Tricycle::brake()
{
setSpeed(speed - 1);
std::cout << "\nBraking ; tricycle speed " << speed << " mph\n";
}
int main()
{
Tricycle wichita;
wichita.setSpeed(0);
wichita.pedal();
wichita.pedal();
wichita.brake();
wichita.brake();
wichita.brake();
return 0;
}

This Method return the Value from Speed.
So if you call setSpeed with value greater as 0 then the Speed Value are set to the new Value. Declared as private int variable.
As example
int main()
{
Tricycle wichita;
wichita.setSpeed(10);
int mySpeed= wichita.getSpeed();
}
The Value of mySpeed is now 10.

Since Speed is a private variable, you cannot retrive/set its value outside the class scope. So here we have used setSpeed and getSpeed public functions through which we can retrive/set Speed to tricycle object outside the class scope.
For example,
Tricycle myTricycle = new Tricycle();
// to set speed of tricycle use,
myTricycle.setSpeed(100);
// to retrive speed of tricycle object use,
myTricycle.getSpeed(); // returns 100;

Because you cannot access the private members directly from the main() function or somewhere else. But you can use a public function to access the private elements of an object of any class. In spite of this, you cannot access those private elements. In your code, speed is a private member and to get the value of this, a public function namely getSpeed is being used.

Related

I can't access to a value of my objectin C++

I'm starting C++ : I was trying to make my "player1" attack my "player2", to make him remove health to my "player2" and finally to display the health of "player2". But it's not working and I can't find the mistake.
Here's my code I hope you will be able to help me:
PLAYER.CPP
class Player {
public:
std::string pseudo;
int healthValue = 100;
int attackValue = 5;
Player(std::string aPseudo) {
pseudo = aPseudo;
healthValue = healthValue;
attackValue = attackValue;
}
std::string getPseudo() {
return pseudo;
}
int getHealthValue() {
return healthValue;
}
int getAttackValue() {
return attackValue;
}
void attack(Player aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
};
MAIN.CPP
#include "Player.cpp"
int main() {
Player player1("player1");
Player player2("player2");
std::cout << player2.getHealthValue() << std::endl;
player1.attack(player2);
std::cout << player2.getHealthValue() << std::endl;
return 0;
}
Here:
void attack(Player aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
The parameter aTargetPlayer is passed by value, this means you decreased the health of a copy, not the original one. You must pass by reference, like this:
void attack(Player &aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
#JuanR's answer is valid. Note also that, they way you designed your class, the attack() method could very well be moved out of the class:
Why?
The attacker does not have a stronger affinity to the code of the method than the attacked player. If anything, and since right now, the attack only affects the stats of the attacked player, you might have written a getAttackedBy(const Player& other_player)...
The code for attack() does not need access to protected or private members of the Player class.
So consider writing:
void attack(Player& attacker, Player& attacked);
(This has both players passed by non-const reference in case you want to reduce the number of actions of the attacker, or allow it to take damage from the attacked player's defense etc.)

Avoid creating named variables when pointer is required

I have been creating named variables in order to be able to pass their adress to a constructor that expects a pointer, but I want to be able to create them in a constructor or other function and then pass their address to the constructor that expects a pointer.
I am using C++ 20 and I have the following classes:
#include <iostream>
#include <string>
#include <vector>
#include <random>
using std::string, std::cout, std::cin, std::endl, std::vector;
class symbol {
public:
enum symbolKind {
null,
terminal,
sequence,
weighted,
random
};
protected:
symbolKind kind;
public:
virtual string evaluate() const = 0;
symbolKind getKind() {
return kind;
}
};
class nullSymbol : public symbol {
public:
nullSymbol() {
kind = symbol::null;
}
string evaluate() const override {
return "";
}
};
class terminalSymbol : public symbol {
private:
string termString;
public:
terminalSymbol(string pString) {
kind = symbol::terminal;
termString = pPhoneme;
}
string evaluate() const override {
return termString;
}
};
class sequenceSymbol : public symbol {
private:
vector<symbol*> symArray;
public:
sequenceSymbol(vector<symbol*> pArr) {
kind = symbol::sequence;
symArray = pArr;
}
string evaluate() const override {
string retStr = "";
for (symbol* current : symArray) {
retStr += current->evaluate();
}
return retStr;
}
};
class weightedSymbol : public symbol {
private:
float weight;
symbol* subSym;
public:
weightedSymbol(symbol* pSym, float pWeight) {
kind = symbol::weighted;
subSym = pSym;
weight = pWeight;
}
string evaluate() const override {
return subSym->evaluate();
}
float getWeight() {
return weight;
}
};
class randomSymbol : public symbol {
private:
vector<weightedSymbol*> symArray;
public:
randomSymbol(vector<weightedSymbol*> pArr) {
kind = symbol::random;
symArray = pArr;
}
string evaluate() const override {
float sum = 0.0;
for (weightedSymbol* current : symArray) {
sum += current->getWeight();
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0.0, sum);
float randomResult = dis(gen);
float prev = 0;
for (weightedSymbol* current : symArray) {
if (randomResult < (prev += current->getWeight())) return current->evaluate();
}
}
};
I have been creating symbols like this:
terminalSymbol term_a("a");
terminalSymbol term_b("b");
sequenceSymbol seq_ab({ &term_a, &term_b});
cout << "ab test: " << seq_ab.evaluate() << endl;
But I would want to be able to do it like this or similar:
sequenceSymbol seq_ab_2({&terminalSymbol("a"), &terminalSymbol("b")});
cout << "ab test 2: " << seq_ab_2.evaluate() << endl;
This creates an error '&' requires l-value in Visual Studio.
This is a pretty simple example, often there are a lot more variables being created than this. In this case, the addresses are being passed to the std::vector<weightedSymbol*>() constructor; it's the same with the weightedSymbol() constructor which also expects a pointer. This should work not only for the constructor (it doesn't even need to work with the constructor itself if there is another way to achieve the same functionality), but I want a way to create heap objects in a function and then return a pointer to them that works in this situation. It might be that I need to change the classes themselves for this to work, they should just provide the same functionality.
In the end, I want to create these symbol objects dynamically based on user input.
I have searched online and tried using a bunch of different things but didn't manage to get the functionality I want working. What would be a good way to implement this? There is probably a common technique/idiom that I can use, if so, please explain it to me in detail so that I can use it in other projects too.
The objects you pass by pointers need to be destroyed somehow. In this snippet they will be destroyed automatically whenever you exit the block:
terminalSymbol term_a("a");
terminalSymbol term_b("b");
sequenceSymbol seq_ab({ &term_a, &term_b});
What should happen if you create objects without a named variable? Your classes never delete the objects that you pass by pointers, so that should be the caller responsibility to manage the lifespan of each object.
One solution for your problem is to wrap the objects into any sort of smart pointers. For example:
class sequenceSymbol : public symbol {
public:
sequenceSymbol(vector<shared_ptr<symbol>> pArr);
};
sequenceSymbol seq_ab_2({
std::make_shared<terminalSymbol>("a"),
std::make_shared<terminalSymbol>("b")
});

C++ declare derived class object inside of if-else and use it outside

I have a (parent) class named Alma with the (virtual) function Getwidth() and two derived class of Alma, named Birs (with the special function Getheight()) and Citrom (with the special function Getdepth()). I want to declare an object - named Attila - which type is Birs or Citrom depending on a bool. Later, I want to use the common function Getwidth() and also the special functions (depending the bool mentioned).
My (not working) code:
/*...*/
/*Classes*/
class Alma{
public: virtual int Getwidth() = 0;
/*ect...*/
}
class Birs: public Alma{
int Getwidth(){return 1;}
public: int Getheight(){return 2;}
/*ect...*/
}
class Citrom: public Alma{
int Getwidth(){return 3;}
public: int Getdepth(){return 4;}
/*ect...*/
}
/*...*/
/*Using them*/
void Useobjects(){
/*Create object depending on bool*/
if(b00lvar){
Birs Andor();
std::cout<<Andor.Getwidth()<<" "<<Andor.Getheight()<<std::endl;
}else{
Citrom Andor();
std::cout<<Andor.Getwidth()<<" "<<Andor.Getdepth()<<std::endl;
}
/*Using the common part of object*/
std::cout<<Andor.Getwidth()<<std::endl;
/*Using the special part of object*/
if(b00lvar){
std::cout<<Andor.Getheight()<<std::endl;
}else{
std::cout<<Andor.Getdepth()<<std::endl;
}
/*ect...*/
}
This is a classic case of polymorphic object handling. Just make sure you are familiar with that concept as well with pointers and references.
What you need is something looking like:
Alma* Andor;
if(b00lvar){
Andor = new Birs();
std::cout<<Andor->Getwidth()<<" "<<Andor->Getheight()<<std::endl;
}else{
Andor = new Citrom();
std::cout<<Andor->Getwidth()<<" "<<Andor->Getdepth()<<std::endl;
}
Next use dynamic_cast to get back to the derived types and finally of course do not forget to delete the object. But first read about those concepts.
You cannot define a single object whose type is this or that, depending on something else. C++ doesn't work this way. C++ is a statically-typed language. This means that the type of every object is determined at compile time. Other languages, like Perl, or Javascript, are dynamically-typed, where the type of an object is determined at runtime, and a single object can be one thing, at one point, and something else at a different point.
But C++ does not work this way.
To do something like what you're trying to do, you have to refactor the code, and work with the virtual superclass. Something like this:
void UseObject(Alma &andor)
{
/*Using the common part of object*/
std::cout<<andor.Getwidth()<<std::endl;
/*Using the special part of object*/
/* This part is your homework assignment */
}
void Useobjects(){
/*Create object depending on bool*/
if(b00lvar){
Birs andor;
std::cout<<Andor.Getwidth()<<" "<<Andor.Getheight()<<std::endl;
UseObject(andor);
}else{
Citrom andor;
std::cout<<Andor.Getwidth()<<" "<<Andor.Getdepth()<<std::endl;
UseObject(andor);
}
}
Another approach would be to use two pointers, in this case passing two pointers to UseObject(). One of the two pointers will always be a nullptr, and the other one a pointer to the instantiated object, with UseObject() coded to deal with whatever object is passed in.
That's also possible, but will result in ugly code, and if I was an instructor teaching C++, I would mark down anyone who handed in code that did that.
If the type of the object (Alma or Citrom) is decided at the startup, then it's a classic polymorphism, as other answers described:
https://stackoverflow.com/a/36218884/185881
What're you missing from your design is, to name the common ancestor with common behaviors (e.g. Gyumolcs).
If the object should once act as Alma and other times as Citrom, you should implement a single class, which have a flag or enum (ACT_AS_CITROM, ACT_AS_ALMA), or, if the behavior is limited to one method, then it should have a parameter, which tells which action to perform (alma-like or citrom-like).
You can do this with pointer semantic and type introspection with dynamic_cast. I extended your example to show how I would approach it.
Here is the Demo
#include <iostream>
#include <memory>
using namespace std;
class Alma{
public:
virtual int Getwidth() = 0;
};
class Birs: public Alma{
public:
int Getwidth() { return 1; }
int Getheight() { return 2; }
};
class Citrom: public Alma{
public:
int Getwidth() { return 3; }
int Getdepth() { return 4; }
};
shared_ptr<Alma> make_attila(bool birs)
{
if (birs)
return make_shared<Birs>();
else
return make_shared<Citrom>();
}
void test_attila(shared_ptr<Alma> attila)
{
cout << "width: " << attila->Getwidth() << "\n";
if (auto as_birs = dynamic_pointer_cast<Birs>(attila))
cout << "height: " << as_birs->Getheight() << "\n";
else if (auto as_citrom = dynamic_pointer_cast<Citrom>(attila))
cout << "depth: " << as_citrom->Getdepth() << "\n";
}
int main() {
shared_ptr<Alma> attila = make_attila(true);
test_attila(attila);
attila = make_attila(false);
test_attila(attila);
return 0;
}
Next step would be to make make_attila a template function taking the Derived class as a template parameter instead of a bool.
template <class Derived>
shared_ptr<Alma> make_attila()
{
return make_shared<Derived>();
}
Two things:
If you want to use it outside the if, you will have to declare it outside the if.
You need references or pointers for this kind of polymorphism.
unique_ptr<Alma> Andor;
if (b00lvar) {
Andor = make_unique<Birs>();
} else {
Andor = make_unique<Citrom>();
}
std::cout << Andor->Getwidth() << std::endl;
Some other answer suggested using shared_ptr but that's overkill here. 99% of the time unique_ptr is sufficient.
Polymorphism isn't always the way to go if an object is known to be either a B or a C. In this case, a boost::variant is often more succinct.
Having said this, if you want to go down the polymorphic route it's important to remember something that will guide the design.
Polymorphic means runtime polymorphic. I.e. the program cannot know the real type of the object. It also cannot know the full set of possible types the object could be, since another developer could manufacture a type that your module's code knows nothing about. Furthermore, when using the Alma interface, the code should not need to know anything more. Invoking magic such as "I know it'll be a Citrom because the bool is true" is laying the foundations for a code maintenance nightmare a few weeks or months down the line. When done in commercial, production code, it results in expensive and embarrassing bug-hunts. Don't do that.
This argues that all relevant information about any object of type Alma must be available in the Alma interface.
In our case, the relevant information is whether it has the concept of height and/or depth.
In this case, we should probably include these properties in the base interface plus provide functions so that the program can query whether the property is valid before using it.
Here is something like your example written this way:
#include <iostream>
#include <memory>
#include <typeinfo>
#include <string>
#include <exception>
#include <stdexcept>
// separating out these optional properties will help me to reduce clutter in Alma
struct HeightProperty
{
bool hasHeight() const { return impl_hasHeight(); }
int getHeight() const { return impl_getHeight(); }
private:
// provide default implementations
virtual bool impl_hasHeight() const { return false; }
virtual int impl_getHeight() const { throw std::logic_error("getHeight not implemented for this object"); }
};
struct DepthProperty
{
bool hasDepth() const { return impl_hasDepth(); }
int getDepth() const { return impl_getDepth(); }
private:
virtual bool impl_hasDepth() const { return false; }
virtual int impl_getDepth() const { throw std::logic_error("getDepth not implemented for this object"); }
};
class Alma : public HeightProperty, public DepthProperty
{
public:
Alma() = default;
virtual ~Alma() = default;
// note: nonvirtual interface defers to private virtual implementation
// this is industry best practice
int getWidth() const { return impl_getWidth(); }
const std::string& type() const {
return impl_getType();
}
private:
virtual int impl_getWidth() const = 0;
virtual const std::string& impl_getType() const = 0;
};
class Birs: public Alma
{
private:
// implement the mandatory interface
int impl_getWidth() const override { return 1; }
const std::string& impl_getType() const override {
static const std::string type("Birs");
return type;
}
// implement the HeightProperty optional interface
bool impl_hasHeight() const override { return true; }
int impl_getHeight() const override { return 2; }
};
class Citrom: public Alma
{
private:
// implement the mandatory interface
int impl_getWidth() const override { return 3; }
const std::string& impl_getType() const override {
static const std::string type("Citrom");
return type;
}
// implement the DepthProperty optional interface
bool impl_hasDepth() const override { return true; }
int impl_getDepth() const override { return 4; }
};
/*...*/
/*Using them*/
// generate either a Birs or a Citrom, but return the Alma interface
std::unique_ptr<Alma> make_alma(bool borc)
{
if (borc) {
return std::make_unique<Birs>();
}
else {
return std::make_unique<Citrom>();
}
}
void Useobjects()
{
for (bool b : { true, false })
{
std::unique_ptr<Alma> pa = make_alma(b);
std::cout << "this object's typeid name is " << pa->type() << std::endl;
std::cout << "it's width is : " << pa->getWidth() << std::endl;
if(pa->hasHeight()) {
std::cout << "it's height is: " << pa->getHeight() << std::endl;
}
if(pa->hasDepth()) {
std::cout << "it's depth is: " << pa->getDepth() << std::endl;
}
}
}
int main()
{
Useobjects();
return 0;
}
expected output:
this object's typeid name is Birs
it's width is : 1
it's height is: 2
this object's typeid name is Citrom
it's width is : 3
it's depth is: 4

unable to use friend class' method

I have a problem with my code. I have two classes, Run and Robot, and I want an object of type Robot to change a private member of an object of type Run. To be specific, I want to increment the value of 'x' in the following code.
The following errors pop up:
error: 'getX' was not declared in this scope
error: 'getX' was not declared in this scope
I have pinpointed with an arrow (<---) the line where the error occurs. The following code is just a test, just to learn how to use the 'friend' keyword for a project.
#include <iostream>
#include <vector>
using namespace std;
class Robot;
class Run{
friend class Robot;
private:
int x;
vector<Robot*>robots;
public:
Run();
vector<Robot*>*getRobots();
void createRobot();
void movAll();
void setX(int);
int getX();
};
class Robot{
friend class Run;
public:
Robot();
void movingRobot();
};
Run::Run(){}
vector<Robot*>*Run::getRobots(){return &robots;}
void Run::createRobot(){getRobots()->push_back(new Robot);setX(1);}
void Run::movAll(){getRobots()->at(0)->movingRobot();}
int Run::getX(){return x;}
void Run::setX(int c){x=c;}
Robot::Robot(){}
void Robot::movingRobot(){setX(getX()+1);} <-------------------------
int main(){
Run Sim;
Sim.createRobot();
Sim.movAll();
}
Using the 'friend' keyword will definitely help on my project, so I am trying to understand how to use it.
You're just calling getX() and setX() as if they're methods of Robot. You need to call the function against an instance of Run, and in this case you don't need it to be a friend because getX() is public anyway.
That said, do you want each Robot to have an x value that you want to increment? In that case, you need it to be a member of Robot rather than Run.
If you want Run to have a single value of x that all instances of Robot can access and modify, then just make x static, then access it directly rather than calling the public methods, which don't require another class to be a friend anyway.
You called getX as if it were a function of the Robot-class. You need a run object to call it:
run.getX()
Ok you can remove the getX() function from The Robot class as it has no code body at present anyway, and for internal use the robot class can always utilise its X variable. Run doesn't need to have a friend class Robot, as Robot should not need to look into Run for anything, and as Run contains a vector of pointers to instances of Robot it can access any values of Robot instances by looking at the contents of its vector (for example myRunInstance.getRobots()[1]->getX() would return the x value of the 2nd robot in the vector of robots).
Now the getX function will have to vary a tad if it is to remain in the Run class: you will need to specify a way to make it gather the information of a specific instance of the Robot class, presumably from its vector of Robots. I have respecced your code above and added a small proof of concept set of code to the main, makes 10 robots moves them all using moveall, then sets Johnny5 to a special place (because he IS special:) Something along the lines of:
#include <iostream>
#include <vector>
using namespace std;
class Run;
class Robot{
friend class Run; // allows the Run class to access all the private data as if it were its own
private:
int x;
public:
Robot() {};
void setX(int newX) { x= newX; }
int getX() { return x; }
void movingRobot() { x+=1; }
};
class Run{
private:
vector<Robot*> robots;
public:
Run(){};
vector<Robot*> *getRobots() { return &robots; }
void createRobot() { robots.push_back(new Robot()); robots.back()->x =1; }
void movAll() { for (int i=0;i<robots.size();i++){ robots[i]->movingRobot();} }
int getX(int robotPosition){ return robots[robotPosition]->x; } //uses the friend status to read directly from Robot class instances x
void setX(int rpos, int xval){ robots[rpos]->setX(xval); }
};
int main()
{
Run *Sim = new Run();
for (int i =0; i< 10; i++)
{
Sim->createRobot();
Sim->setX(i,i); // uses the Run setX
std::cout << "Robot " << i << "(starting position): " << Sim->getRobots()->at(i)->getX() << std::endl;
}
Sim->movAll();
// lets move Johnny 5 to 55 as well...
(Sim->getRobots()->at(4))->setX(55); // uses the robot setx
for (int i=0; i< 10; i++)
{
std::cout << "Robot " << i << "(final position): " << Sim->getRobots()->at(i)->getX()<< std::endl;
}
return 0;
}
Source also viewable with sample output at Ideone

Subclass unable to access parent class' variable

I'm making a program whereby I have a Square class which is a subclass of Shape class
But my program crashes when the subclass tries to access variable from parent class.
Here is my code:
class Shape2D
{
public:
string shape;
void setShape(string newShape);
string getShape();
string specialType;
void setSpecialType(string newSpecialType);
vector <int> shapeXCoordi;
void setshapeXCoordi(int newshapeXCoordi);
vector <int> shapeYCoordi;
void setshapeYCoordi(int newshapeYCoordi);
void toString();
virtual int computeArea()
{
return 0;
}
void displayArea();
};
For testing purpose, I only make this computeArea() return the x-coordinate.
class Square : public Shape2D
{
public:
int computeArea()
{
return shapeXCoordi[0];
}
};
int main()
{
if (aShape2D[0].getShape() == "Square")
{
Shape2D *pShape2D;
pShape2D = &aSquare;
cout << "Area: " << pShape2D -> computeArea() << endl;
}
}
I did a couple of test, if I were to change return shapeXCoordi[0]; to return 123;, it works fine.
I also tried return shape; but it will not display anything, although this time, it doesn't crash.
So I'm guessing there is something wrong when SquareClass is trying to access shapeXCoordi[0] from ShapeClass
Can anyone enlighten me on this situation?
You need to initialize the shapeXCoordi in your constructor by calling setshapeXCoordi first. Since you are accessing shapeXCoordi, an uninitialized vector, there are no elements in it. Hence when you access it using [0] it returns an error.
You can add a sanity check to computeArea() to ensure there is an element in shapeXCoordi before you access it:
int computeArea()
{
assert(shapeXCoordi.size() != 0);
return shapeXCoordi[0];
}
Also, I recommend using .at(0) instead of [0], this way you get actual error handling instead of a crash.