Member variable getting overridden with garbage value - c++

In a class, I have a member variable which is set when I call a method and am able to print it but it gets overridden when I try to print it a second time.
Below is the approximate code of whats happening.
nodezero.h
#ifndef NODEZERO_H
#define NODEZERO_H
//does nothing but sets three properties let say m_a, m_b and m_c.
#endif
nodefirst.h
#ifndef NODEFIRST_H
#define NODEFIRST_H
#include "nodezero.h"
class nodefirst {
public:
nodezero* root=nullptr;
void insert(int, int, int);
};
#endif
nodefirst.cpp
void nodefirst::insert(int a, int b, int c) {
nodezero realnode = nodezero(a,b,c);
nodezero* node = &realnode;
root = node;
return;
}
test.cpp
#include "nodezero.h"
#include "nodefirst.h"
#include <iostream>
using namespace std;
int main() {
nodefirst nf;
nf.insert(1,2,3);
cout<<nf.root->n_a<<"test"<<nf.root->n_a;
When the cout is called, part before "test" is printed correctly as 1 but after test is some garbage value.
Can someone please help me with this? I am not able to find what I am missing.

Related

How to access a atribute in a different class

I'm doing a program that just have to print value of the variables, i think the first class is working, the 'm_valor' is printed like i want , but the second class should be printing 'm_valor + m_valorAdicional', but it is printing just the value of 'm_valorAdicional':
#ifndef INGRESSO_H
#define INGRESSO_H
#include <iostream>
using namespace std;
class Ingresso
{
protected:
float m_valor;
public:
Ingresso(): m_valor(0){};
Ingresso(float valor): m_valor(valor){};
~Ingresso(){};
float getValor() const {return m_valor; };
};
class IngressoVip : public Ingresso
{
private:
float m_valorAdicional;
public:
IngressoVip(): m_valorAdicional(0){};
IngressoVip(float valor): m_valorAdicional(valor){};
~IngressoVip(){};
float getValor(){return m_valorAdicional +=m_valor;};
};
#endif
main.cpp:
#include "Ingresso.hpp"
int main()
{
Ingresso a(10);
IngressoVip b(5);
out<<"valor Ingresso: "<<a.getValor()<<endl;
cout<<"valor IngressoVip: "<<b.getValor()<<endl;
return 0;
}
I think this should be easy, but i just don't know what i have to do to work like i want.
You should use +, not +=. What += does here in this line:
return m_valorAdicional +=m_valor;
is it adds the value of m_valor to m_valorAdicional, changing the value of m_valorAdicional, and then returning this new value. If you don't want to change the values of the variables use +.

C++ Pointer function to other class function

I need help with passing a function pointer on C++. I can't linkage one function for a class to other function. I will explain. Anyway I will put a code resume of my program, it is much larger than the code expose here but for more easier I put only the part I need to it works fine.
I have one class (MainSystem) and inside I have an object pointer to the other class (ComCamera). The last class is a SocketServer, and I want when the socket received any data, it sends to the linkage function to MainSystem.
ComCamera is a resource Shared with more class and I need to associate the functions ComCamera::vRecvData to a MainSystem::vRecvData or other function of other class for the call when receive data and send de data to the function class associate.
Can Anyone help to me?
EDDITED - SOLUTION BELOW
main.cpp
#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <exception>
#include <unistd.h>
using std::string;
class ComCamera {
public:
std::function<void(int, std::string)> vRecvData;
void vLinkRecvFunction(std::function<void(int, std::string)> vCallBack) {
this->vRecvData = vCallBack;
}
void vCallFromCamera() {
this->vRecvData(4, "Example");
};
};
class MainSystem {
private:
ComCamera *xComCamera;
public:
MainSystem(ComCamera *xComCamera) {
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iChannelNumber, std::string sData) {vRecvData(iChannelNumber, sData); });
}
void vRecvData(int iNumber, string sData) {
std::cout << "RECV Data From Camera(" + std::to_string(iNumber) + "): " << sData << std::endl;
};
};
int main(void) {
ComCamera xComCamera;
MainSystem xMainSystem(&xComCamera);
xComCamera.vCallFromCamera();
return 0;
}
Output will be:
MainSystem RECV Data From Camera(4): Example
You can have ComCamera::vRecvData be of type std::function<void(int, std::string)> and then have ComCamera::vLinkRecvFunction() be like this:
void ComCamera::vLinkRecvFunction(std::function<void(int, std::string)> callBack)
{
this->vRecvData = callBack;
}
and have MainSystem constructor be like this:
MainSystem::MainSystem(ComCamera *xComCamera)
{
using namespace std::placeholders;
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iNumber, std::string sData){vRecvData(number, sData);});
}
Still though the original question has way too much code to go through friend.
Here what you want :
#include<iostream>
using std::cout;
class A; //forward declare A
class B{
public:
void (A::*ptr)(int x); //Only declare the pointer because A is not yet defined.
};
class A{
public:
void increase_by(int x){
a+=x;
} // this function will be pointed by B's ptr
int a = 0; // assume some data in a;
B b; // creating B inside of A;
void analyze(int y){
(*this.*(b.ptr))(y);
} // Some function that analyzes the data of A or B; Here this just increments A::a through B's ptr
};
int main(){
A a; // creates A
cout<<a.a<<"\n"; // shows initial value of a
a.b.ptr = &A::increase_by; // defines the ptr that lies inside of b which inturns lies inside a
a.analyze(3); // calls the initialize method
(a.*(a.b.ptr))(3); // directly calls b.ptr to change a.a
cout<<a.a; // shows the value after analyzing
return 0;
}
Output will be :
0
6
I still don't get why would you do something like this. But maybe this is what you wanted as per your comments.
To know more read this wonderful PDF.

Pass created object as argument, from inside that object, C++

I am facing the following problem. I have the following classes, Room and Reservation . For Reservation class there is a function (void Reservation :: rsrvRoomAssignment(Room* r)) that assigns the Room* rsrvRoom member of Reservation class, to a Room object. I want though to call this class from inside the Room object but i have no clue on how to achieve that properly passing as argument the created object that runs the code.
The code describes the above:
Reservation.h
class Room;
class Reservation {
public:
static int rsrvCode;
string rsrvName;
unsigned int rsrvDate;
unsigned int rsrvNights;
unsigned int rsrvPersons;
Room* rsrvRoom; // Room assigned to reservation.
Reservation();
~Reservation();
void rsrvRoomAssignment(Room*);
};
Reservation.cpp
#include <iostream>
#include "Reservation.h"
using namespace std;
/*
Constructor & Destructor
*/
void Reservation :: rsrvRoomAssignment(Room* r){
rsrvRoom=r;
}
Room.h
#include "Reservation.h"
class Room {
public:
static unsigned int roomNumber;
unsigned int roomCapacity;
Reservation* roomAvailability[30];
double roomPrice;
Room();
~Room();
bool roomReservationAdd(Reservation*);
};
Room.cpp
#include <iostream>
#include <string>
#include "Room.h"
using namespace std;
/*
Constructor & destructor
*/
bool Room::roomReservationAdd(Reservation* r){
/* some statement that returns flase */
r->rsrvRoomAssignment(/* & of created object */); // This is the problem i described.
return 1;
}
I am pretty new to OOP so there might be some more logical errors on the above snipsets, so don't be harsh :) .
Thanks for any kind of help!
When inside a class method, this indicates the instance of the object calling it. In your case, when a room instance X calls X.roomReservationAdd(r),
this points to the room instance X.
Hence, you can simply call r->rsrvRoomAssignment(this);

Access variable from another class (in C++)

This may be a really easy question but... here it goes. (Thanks in advance!)
I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.
source.ccp
#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply();
system("pause");
exit(1);
}
begin.h
#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
public:
void collectdata();
int test;
};
#endif
begin.cpp
#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
test = 6;
}
calculation.h
#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
public:
void multiply();
};
#endif
calculation.cpp
#include <iostream>
#include "begin.h"
#include "calculation.h"
void calculationclass::multiply()
{
beginclass BEGINOBJECT;
// BEGINOBJECT.collectdata(); // If I uncomment this it works...
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
Simply define member function multiply as
void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
And call it as
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply( BEGINOBJECT );
system("pause");
exit(1);
}
In your code beginclass has no explicit constructor, hence the implicitly defined default constructor will be used, which default constructs all members. Hence, after construction beginclass::test is either 0 or uninitiliased.
What you appear to be wanting is to avoid to call beginclass::collectdata() more than once. For this you would want to set a flag that remembers if beginclass::collectdata() has been called. The member function which returns the data then first checks this flags and, if the flag was not set, calls beginclass::collectdata() first. See also the answer by CashCow.
It looks like you are looking for some kind of lazy evaluation / caching technique whereby a value is calculated the first time it is requested then stored to return it subsequently without having to reevaluate.
In a multi-threaded environment the way to achieve this (using the new standard thread library) is by using std::call_once
If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.
For a "calc_once" example:
class calculation_class
{
std::once_flag flag;
double value;
void do_multiply();
double multiply();
public:
double multiply()
{
std::call_once( flag, do_multiply, this );
return value;
}
};
If you want multiply to be const, you'll need to make do_multiply also const and value and flag mutable.

C++ Linked Lists with struct

I'm new in C++ and I have something to do with a linked list, and I don't know why it doesn't work, need help from a prof :O)
Here's my .h
#ifndef UnCube_H
#define UnCube_H
using namespace std;
class ACube{
public:
ACube();
struct Thecube;
private:
void PrintList();
};
#endif
My ACube.cpp
#include <iostream>
#include "ACube.h"
ACube::ACube(){
};
struct Thecube{
int base;
int cube;
Thecube * next ;
};
void ACube::PrintList(){
};
and finally my main.cpp
#include <cstdlib>
#include <iostream>
#include "ACube.h"
using namespace std;
int main()
{
ACube * temp;
temp = (ACube*)malloc(sizeof(ACube));
for (int inc=1; inc <=20 ; inc++){
temp->ACube->nombrebase = inc;
temp->cube = inc*inc*inc;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Everything was working fine, but when I add these lines :
temp->ACube->nombrebase = inc;
temp->cube = inc*inc*inc;
I add error saying :
'class ACube' has no member named 'TheCube'
'class ACube' has no member named 'cube'
Can someone help me because I want to create my list and fill the cube with number.
Other thing I want to use THIS. in the print,
Maybe someone can teach me what's wrong and how to do it !
Thanks for any help
You don't need to have a struct inside your class.
#ifndef UnCube_H
#define UnCube_H
using namespace std;
class ACube{
public:
ACube();
int base;
int cube;
ACube * next ;
private:
void PrintList();
};
#endif
ACube.cpp
#include <iostream>
#include "ACube.h"
ACube::ACube(){
};
void ACube::PrintList(){
};
Also, this string is wrong:
temp->ACube->nombrebase = inc;
it should be just:
temp->base = inc;
Last but not least, this code doesn't create a linked list, because you don't do anything with the ACube::next pointer.
There are so many horrible problems in your code, I suggest you should learn more C++ knowledge before writing linked list.
1. What is nombrebase?
I think nobody can answer.
2. You must allocate C++ class by new key word instead of malloc.
new invokes not only allocation but also class constructor, while malloc allocates only.
3. Thecube should been defined inside ACube
Since the code in your main() refers the member cube in class Thecube, main() must know what it is.
4. The member next in class ACube is a pointer which points to what?
What does a pointer point to without initilization? You should initial it in constructor, and destroy it in destructor.
5. temp->ACube
ACube is a class type, you can access member object, but not a type.
6. Never using namespace into a header file
It would make the client of header file has name collision.
The following is the corrected code. Just no compile error and runtime error, but this is NOT linked list:
ACube.h
#ifndef UnCube_H
#define UnCube_H
class ACube{
public:
struct Thecube
{
int base;
int cube;
Thecube * next;
};
ACube();
~ACube();
Thecube *next;
private:
void PrintList();
};
#endif
ACube.cpp
ACube::ACube()
: next(new Thecube)
{
}
ACube::~ACube()
{
delete next;
}
void ACube::PrintList(){
}
main.cpp
#include <cstdlib>
#include <iostream>
#include "ACube.h"
using namespace std;
int main()
{
ACube * temp;
temp = new ACube;
for (int inc = 1; inc <= 20; inc++)
{
temp->next->base = inc; // <-- This is not linked list, you shall modify.
temp->next->cube = inc*inc*inc; // <-- This is not linked list, you shall modify.
}
system("PAUSE");
return EXIT_SUCCESS;
}