Why is the content of my pointer to a friend class changing? - c++

I am trying to create an object class "Bag" to store a linked list of object of friend class "Items".
Bag contains a pointer to an "Item" object.
The first call to the content of the Item object is always correct.
However, I am facing some problems as the value called subsequently will never be the same as the value called in the first time.
In other words,
Baseclass.BaseclassMember is constant as expected.
But (Baseclass.FriendClassPointer)->FriendClassMember is changing
Anyone knows why?
enum itemtype {potion, poison};
class Item
{
public:
friend class Bag;
Item(itemtype,int);
void initItem();
int qty;
int value;
Item *prevItem, *nextItem;
itemtype type;
};
class Bag
{
public:
Bag(Item,int);
Item *currentItem;
int currentsize;
int maxsize;
};
Item::Item(itemtype ITEMtype, int quantity): type(ITEMtype),qty(quantity)
{
initItem();
prevItem=nullptr;
nextItem=nullptr;
}
void Item::initItem()
{
value=8 ;
}
Bag::Bag(Item firstItem, int maxbagsize) : currentItem(&firstItem),maxsize(maxbagsize),currentsize(1)
{
currentItem->nextItem = currentItem;
currentItem->prevItem = currentItem;
cout<<"constructor check: Item Address "<<currentItem<<" nextAddress "<<currentItem->nextItem<<" "<<"\n";
}
int main()
Item item1(potion,1);
Bag bag1(item1,5);
cout<<" 1st call:"<<" Bagsize "<<bag1.currentsize<<" nextAddress "<<(bag1.currentItem)->nextItem<<"\n";
cout<<" 2nd call:"<<" Bagsize "<<bag1.currentsize<<" nextAddress "<<(bag1.currentItem)->nextItem<<"\n";
getchar(); /* stops window from closing */
return 0;

Related

Member struct of a class prints incorrect attribute values in main, but has the right values in memory

Here's the code I was playing around with to understand member types inside a class better:
class First
{
struct trialStruct; //forward declaration
public:
First() : t {nullptr} //constructor
{
trialStruct temp {1,5};
cout<<temp.a<<" "<<temp.b<<endl<<endl; //attribute values of temporary struct variable
t = &temp;
cout<<t->a<<" "<<t->b<<endl<<endl; //attribute values of member struct variable
}
trialStruct* t; //member struct attribute
private:
struct trialStruct //struct
{
trialStruct(int aTemp , int bTemp) : a {aTemp} , b {bTemp}
{
//done
}
int a,b;
int sum();
};
};
int First::trialStruct::sum() //definition of struct function
{
return a+b;
}
int main()
{
//initialising object, printing struct attribute's attributes
First obj {};
cout<<obj.t->a<<endl;
cout<<obj.t->b<<endl;
cout<<obj.t->sum();
return 0;
}
The outputs in the contructor give the intended value of 1 and 5 for a and b. But the output in main gives output as follows: a = 1, b = 0, return value of sum(): 0
I don't know where I'm going wrong in my understanding of how this should work.
Output Screenshot:
EDIT:John Filleu's comment clarified what I was doing wrong. The temp object is destroyed after the constructor is exited, thus giving the trialStruct pointer undefined behavior.

how to return a list of objects without destroying them

How to fix the function 'func' so that it returns the objects without being destroyed?
function 'func' must add the objects to a list and return them but be destroyed
The Smoothy abstract class has a purely virtual description method (). DecoratorSmoothy
contains a smoothy, description () and getPret () methods return the description and price
aggregate smoothy.
SmoothyCuFream and SmoothyCuUmbreluta classes add the text “cu crema”
respectively “cu umbreluta” in the description of the smoothy contained. The price of a smoothy that has the cream increases by 2 euro, the one with the umbrella costs an extra 3 euro.
BasicSmoothy class is a smoothy without cream and without umbrella, method
description () returns the name of the smothy
#include <iostream>
#include <vector>
using namespace std;
class Smoothy {
private:
int pret=0;
public:
virtual string descriere() = 0;
int getPret(){
return pret;
}
void setPret(int a) {
pret += a;
}
};
class BasicSmooty : public Smoothy {
private:
string nume;
public:
BasicSmooty(string n) :
nume { n } {}
string descriere() {
return nume;
}
};
class DecoratorSmoothy : public Smoothy {
private:
Smoothy* smooty;
public:
DecoratorSmoothy() = default;
DecoratorSmoothy(Smoothy* n) :
smooty{ n } {}
string descriere() {
return smooty->descriere();
}
int getPret() {
return smooty->getPret();
}
};
class SmootyCuFrisca : public DecoratorSmoothy {
private:
BasicSmooty bsc;
public:
SmootyCuFrisca(string desc) :
bsc{ desc } {}
string descriere() {
setPret(2);
return bsc.descriere() + " cu frisca ";
}
};
class SmootyCuUmbreluta : public DecoratorSmoothy{
private:
BasicSmooty bsc;
public:
SmootyCuUmbreluta(string desc) :
bsc{ desc } {}
string descriere() {
setPret(3);
return bsc.descriere() + " cu umbreluta ";
}
~SmootyCuUmbreluta() {
cout << "rip";
}
};
vector<Smoothy*> func(void)
{
std::vector<Smoothy*> l;
SmootyCuFrisca a1{ "smooty de kivi" };
SmootyCuUmbreluta a2{ "smooty de kivi" };
SmootyCuFrisca a3{ "smooty de capsuni" };
BasicSmooty a4{ "smooty simplu de kivi" };
l.push_back(&a1);
l.push_back(&a2);
l.push_back(&a3);
l.push_back(&a4);
return l;
}
int main() {
vector<Smoothy*> list;
// Here when i call func() objects are distroyed
list = func();
return 0;
}
In func you are storing the address of function local variables in l. So when you return l from the function, all the Smoothy* are now pointing to invalid memory.
To fix this, you can allocate memory for each pointer you add to l, like this:
l.push_back(new Smoothy{a1}); // instead of l.push_back(&a1);
// etc. for a2, a3, ...
To really get away from this problem, consider not using pointers at all. If your design doesn't need it, you can get rid of the pointers, and you'll save yourself a lot of trouble.
Well, when a method returns, of course all local/automatic variables are destroyed. Under the late revision c++ changes, there is the return && modifier, which invokes move semantics, which means for not const local/automatic objects you return, it steals: clones the returned object, making a new object and copying all the primitives and object pointers, then sets the object pointers to null so they cannot be deleted/freed by the destructor. (Note that C free of a null pointer does nothing!) For const, of course, it must deep copy.

inserting a multiset in one class from another class

so I have a class Data which has a multiset container and I have a class Item which has "erscheidatum" as one of the constructor parameters,so I want this parameter escheidatum to be inserted in the multiset in the data class i tried to do that in the constructor of the Item class but when I am printing the set its empty the console is empty,i dont know if its possible to insert a set from another class.
//this is Item.h file
#include"Data.h"
#include<string>
class Item
{
public:
Item(std::string Name,int erschDatum, Data pd)// i put Data variable here though that i dont need it just to get access to->
:_Name(Name), dataobject(pd), _erda(erschDatum)//->data class maybe its not the best way.
{
dataobject.insert(erschDatum);
}
~Item();
private:
Data dataobject;
std::string _Name;
int _erda;
};
and this is my Data.h file
#include<set>
#include<iostream>
class Data
{
public:
Data();
std::multiset<int>dataset;
void insert(int a) {
dataset.insert(a);
}
void showData() {
for (const auto& e : dataset) {
std::cout << e << std::endl;
}
}
~Data();
};
and this the main function
#include<iostream>
#include"Item.h"
#include"Data.h"
int main(){
Data DaOb;
Item Buch("xy", 1996,DaOb);
DaOb.showData();
}
You should use reference of Data as parameter of Item. Like this
class Item
{
public:
Item(std::string Name,int erschDatum, Data& pd)// i put Data variable here though that i dont need it just to get access to->
:dataobject(pd), _Name(Name), _erda(erschDatum)//->data class maybe its not the best way.
{
dataobject.insert(erschDatum);
}
~Item();
private:
Data& dataobject;
std::string _Name;
int _erda;
};

C++ : use current instance (object) in function

Greetings C++ community !
I am new to C++ i have this code example :
class Player
{
public:
int pdamage;
int phealth;
/* ... other data members and some void member functions (getName etc.) */
};
class Ennemy
{
public:
int edamage;
int ehealth;
};
**/*here i would like to use current objects parameters for calculation and return to current player instance(current player object) the health value.*/**
int playerHit(this.Player.damage,this.Enemy.ehealth)
{
ehealth = this.Ennemy.ehealth - this.Player.damage;
return ehealth;
};
int ennemyHit(this.Player.phealth,this.Enemy.edamage)
{
phealth = this.Player.phealth - this.Ennemy.edamage ;
return ehealth;
};
int main()
{
/*....*/
return 0;
}
Returning to the post question:
How i use current object parameters in a function for calculations?
/*Since i am new to stackoverflow and C++ Thanks for all advises and suggestions and critics ! */
In C++ you would pass the calles either as pointer or reference
int playerHit(const Player& player, const Ennemy& ennemy)
{
return ennemy.ehealth - player.pdamage;
};

Double astrisk syntax & Help calling member functions

I'm working a program where there's an Airline class. The Airline class contains a vairable to an array of dynamic Flight objects.
In the Airlines class I have (which can't be edited or changed, this was the header file given to me for the assignment):
//Airline.h
class Airline {
public:
Airline(); // default constructor
Airline(int capacity); // construct with capacity n
void cancel(int flightNum);
void add(Flight* flight);
Flight* find(int flightNum);
Flight* find(string dest);
int getSize();
private:
Flight **array; // dynamic array of pointers to flights
int capacity; // maximum number of flights
int size; // actual number of flights
void resize();
};
//Flight.h
class Flight {
public:
Flight();
// Default constructor
Flight(int fnum, string destination);
void reserveWindow();
void reserveAisle();
void reserveSeat(int row, char seat);
void setFlightNum(int fnum);
void setDestination(string dest);
int getFlightNum();
string getDest();
protected:
int flightNumber;
bool available[20][4]; //only four seat types per row; only 20 rows
string destination;
};
I'm trying to impliment one of the find methods in the class.
for that, I have:
Flight* Airline::find(int flightNum){
bool found = false;
for(int i = 0; i < size; i++){
if(array[i].getflightNum() == flightNum){
found = true;
return array[i];
}
}
if(!found)
return 0;
}
// Return pointer to flight with given number if present, otherwise
// return 0.
But it's saying that I need a class type when trying to call the getFlightNum() method. I don't really understand the error. Am I not calling the method correctly? What is the correct syntax?
Since you are dealing with pointers instead of actual objects, try this:
if(array[i]->getflightNum() == flightNum){ // Notice I am using -> instead of .
found = true;
return array[i];
}