I'm having trouble understanding passing references and pointers. I've gone over it so many times in my head but just can't seem to click with it, and I think it's what I need to use here, to actually modify the value in the Account object.
Are there any surefire simple ways to understand them? And how would they apply to this fairly simple scenario?
main code:
if (transactionMenuChoice == 2)
{
cout << "________________________________________________" << endl;
cout << "//TRANSACTION MENU - WITHDRAWAL" << endl;
cout << "//CURRENT CUSTOMER: " << allCustomers.at(customerIndex).getName() << endl;
cout << "//CURRENT ACCOUNT: " << allCustomers.at(customerIndex).getAccounts().at(accountIndex).getAccountNum() << " (" << allCustomers.at(customerIndex).getAccounts().at(accountIndex).getType() << ")" << endl;
cout << "||Withdraw how much?" << endl;
cout << "||£" << endl;
int d;
cin >> d;
allCustomers.at(customerIndex).getAccounts().at(accountIndex).removeFromBalance(d);
}
from my Account.cpp:
void Account::removeFromBalance(double d)
{
balance -= d;
}
Perhaps you are referring to the difference between value references and pointer references? A pointer is the address of a thing, not the thing itself. Your address is a 'pointer' to your mailbox, but not the mailbox itself. In your removeFromBalance function you are passing 'd' by value (not as a pointer). C++ object syntax can sometimes muddy the water since you will see '.' notation to call member function on actual (when you have an object) and '->' notation used to call a member function when you have a pointer to an object.
Related
i have a program that asks for a number of gifts, and then has you input the description, price, and units for it.
i have a function used to display the details here inside it's own cpp file:
void display(const Gift&) {
cout << "Gift Details:" << endl;
cout << "Description: " << gifts.g_description << endl;
cout << "Price: " << gifts.g_price << endl;
cout << "Units: " << gifts.g_units << endl;
}
and here's where i try to call it through another cpp file:
for (int i = 1; i <= numberOfGifts; i++) {
cout << "Gift #" << i << endl;
display(gifts[i]);
cout << endl;
}
i can't seem to figure out how to have it display the first, second, third, and fourth values? it only displays the fourth values 4 times. would greatly appreciate some help
void display(const Gift&) accepts a reference to a Gift as a parameter, but without an identifier (a name) for the parameter the function cannot interact with the parameter.
Instead use void display(const Gift& gift) and then use gift in place of gifts in the function.
Future bug:
Arrays normally are valid between 0 and the array's dimension -1. In
for (int i = 1; i <= numberOfGifts; i++)
i ranges from 1 to numberOfGifts. At the very least this ignores the first, 0th, element of gifts and quite possibly will allow the program to access one past the end of the array. Skipping the first value is a waste of memory, but might be OK. Trying to access a value outside of the array is bad and the results very unpredictable.
I have an vector array in my class which is made to hold pointers to a specific object pointers.
The class should contain methods allowing for adding, removing and finding the objects inside.
The class right now looks like this:
class VectorKontener: public Kontener <VectorKontener> {
protected:
int find(Obiekt &n) {
cout << endl << "---------------------" << endl << "Running find method loop!" << endl;
for (int i = 0; i < stos.size(); i++) {
cout << "Now running for id: " << stos[i]->getId() << endl;
if (stos[i] == &n) return i;
}
return -1;
}
public:
VectorKontener::VectorKontener(Obiekt &n) {
add(n);
}
VectorKontener add(Obiekt &n) {
cout << "Adding: " << n.getId() << endl;
stos.push_back(&n);
return *this;
}
int checkPresent(Obiekt &n) {
return this->find(n) != -1;
}
VectorKontener remove(Obiekt &n) {
if (this->checkPresent(n)) {
stos.erase(stos.begin() + this->find(n));
}
else
cout << endl <<"ELEMENT NOT IN CONTAINER" << endl;
return *this;
}
VectorKontener display() {
cout << endl << "===DISPLAY===" << endl;
for (int i = 0; i < stos.size(); i++) {
stos[i]->display();
}
return *this;
}
};
However when running for test data of:
void Zad3()
{
Obiekt
obj1(5),
obj2(23),
obj3(234),
obj4(33);
cout << endl << "1. Class init" << endl;
VectorKontener k1(obj1);
cout << endl << "2. Adding other objects into array" << endl;
k1
.add(obj2)
.add(obj3)
.display();
cout << endl << "3. Element remove attempt" << endl;
k1
.remove(obj2)
.display();
getchar();
}
The output looks like so:
1. Class init
Adding: 5
2. Adding other objects into array
Adding: 23
Adding: 234
===DISPLAY===
This object has id: 5
This object has id: 23
This object has id: 234
3. Element remove attempt
---------------------
Running find method loop!
Now running for id: 5
Now running for id: 23
---------------------
Running find method loop!
Now running for id: 5
Now running for id: 23
===DISPLAY===
This object has id: 5
The output makes it seem like the third variable of the array becomes lost in the find method (hehe) since it is not calculated by it, despite stos.size() showing the proper value (2).
I am not a cpp expert, to be fair pretty far from it, and am aware this might be a pretty noobish issue, but I have really ran out of ways to make it work properly.
Any help would be really amazing
The issue is that the functions return copies of the object, meaning that in the chained add call the original object is not modified (on the second and any subsequent function call), instead a temporary one is created on each function call that gets destroyed right after.
The simple fix is to change the return value to a reference, e.g.: for the add function:
VectorKontener& add(Obiekt &n) {
instead of
VectorKontener add(Obiekt &n) {
And similar changes for the other functions.
I've been trying to use the PCA module from PCL in C++, but it's been a pain. At one point I want to switch the current indices of points that need to be operated on using the setIndices() function, but to actually make the update there is a private inherited function that one HAS to use called initCompute() or else it doesn't change them (or at least that is how I understood it). Never the less, the code as is, doesn't update the indices for some reason. This is the documentation for the class and everything works, but I have no idea how to make a workaround for this function which they intended to be used for these purposes:
http://docs.pointclouds.org/trunk/classpcl_1_1_p_c_a.html
How to deal with this? This is the error while compiling.
In function ‘void clustering(pcl::PointCloud<pcl::PointXYZ>::ConstPtr, pcl::PointCloud<pcl::PointXYZL>::Ptr, pcl::PointCloud<pcl::PointXYZRGB>::Ptr, pcl::PointCloud<pcl::PointXYZ>::Ptr, float)’:
/usr/include/pcl-1.7/pcl/common/impl/pca.hpp:64:1: error: ‘bool pcl::PCA<PointT>::initCompute() [with PointT = pcl::PointXYZ]’ is private
pcl::PCA<PointT>::initCompute ()
This is the code:
pcl::PCA<pcl::PointXYZ> cpca = new pcl::PCA<pcl::PointXYZ>;
cpca.setInputCloud(input);
std::cout << "We're now performing the cluster elimination!" << endl;
Eigen::Matrix3f pca_matrix; //serves to hold the eigenvectors, and never got updated...hence the couts for checking.
for (int i = 0; i < nclusters; ++i, n++)
{
// the next two lines had to be done so, I found that in a forum, the library just behaves a bit strange.
pcl::PointIndices::Ptr pi_ptr(new pcl::PointIndices);
pi_ptr->indices = cluster_indices[i].indices;
cout << "Current size is: " << pi_ptr->indices.size() << endl;//this shows different sizes on every turn
//now can use pi_ptr
cpca.setIndices(pi_ptr);
pca_matrix = cpca.getEigenVectors();
// but here I get the same vectors every time
std::cout << "vector " << n << " " << pca_matrix(0,0) << " " << pca_matrix(0,1) << " " << pca_matrix(0,2) << endl;
std::cout << "vector " << n << " " << pca_matrix(1,0) << " " << pca_matrix(1,1) << " " << pca_matrix(1,2) << endl;
std::cout << "vector " << n << " " << pca_matrix(2,0) << " " << pca_matrix(2,1) << " " << pca_matrix(2,2) << endl;
Anyway, I got annoyed after a while and did the following.
I created a pca object at the beginning of a for loop using a pointer, and then deleted it at the end of the loop with delete. It is some allocing and deallocing going on there which is most likely not optimal, but it did the trick. The PCA object itself was only 144 bytes large, cause it mostly uses pointers to address necessary elements.
I want to access the current solution of QP after an iteration of the Barrier algorithm. There is a callback ContinuousCallbackI that is triggered after each iteration.
I modified the callback code example:
static ILOBARRIERCALLBACK2(MyCallback, IloCplex, cplex, IloNumVarArray, x) {
cout << "Iteration " << getNiterations() << ": ";
if (isFeasible()) {
cout << "Objective = " << getObjValue() << endl;
//cout << "x[0] = " << (float)cplex.getValue(x[0]) << endl;
//CPLEX Error 1217: No solution exists.
}
else {
cout << "Infeasibility measure = " << getInfeasibility() << endl;
}
}
But cplex doesn't have a solution (error). Is there any way to access the current solution after an iteration?
There is no way to access the current solution.
From inside a callback, only member functions of the callback class should be invoked. These member functions are listed at https://www.ibm.com/support/knowledgecenter/SSSA5P_12.9.0/ilog.odms.ide.help/refcppopl/html/classes/IloCplex_BarrierCallbackI.html, and there is not one that allows to query the current solution.
Trying to understand the difference between rvalue formal parameter and call by value parameter.
When I called fun(move(Demo{}) I see only default constructor called once.
While I called gun(move(Demo{}) I see default constructor and rval constructor called. Please some one help me to understand the behaviour of && formal argument type, uses of && in functions/member functions.
compilers clang++ , g++ , vc++
#include <iostream>
#include <utility>
#include <type_traits>
using namespace std;
class Demo {
int i = 10;
public:
Demo(){
i = 40;
}
Demo(Demo && p) {
i = p.i + 20;
cout << "I am in Demo && " << endl;
}
Demo & operator = (Demo & p) {
cout << "I am in operator && " << endl;
}
Demo & operator = (Demo && p) {
i = p.i + 10;
cout << "I am in operator && " << endl;
}
~Demo(){
cout << "I am in ~Demo " << i << endl;
}
};
void fun(Demo & d) {
cout << "fun( &) " << endl;
cout << " -- End -- " << endl;
}
void fun(Demo && d) {
cout << "fun( && ) " << endl;
std::cout << std::boolalpha;
cout << "Lvalur reference : " << is_lvalue_reference<decltype(d)>::value << endl;
cout << "Rvalue Refernce : " << is_rvalue_reference<decltype(d)>::value << endl;
cout << " -- End -- " << endl;
}
void gun(Demo d) {
cout << "gun( ) " << endl;
std::cout << std::boolalpha;
cout << "Lvalur reference : " << is_lvalue_reference<decltype(d)>::value << endl;
cout << "Rvalue Refernce : " << is_rvalue_reference<decltype(d)>::value << endl;
cout << " -- End -- " << endl;
}
int main() {
cout << "Main begin " << endl;
fun(move(Demo{}));
cout << "------------------- " << endl;
gun(move(Demo{}));
cout << "Main End " << endl;
}
//Output
Main begin
fun( && )
Lvalur reference : false
Rvalue Refernce : true
-- End --
I am in ~Demo 40
-------------------
I am in Demo &&
gun( )
Lvalur reference : false
Rvalue Refernce : false
-- End --
I am in ~Demo 60
I am in ~Demo 40
Main End
Short answer: an rvalue reference behaves mainly like an usual non-const reference (i mean, a non-const lvalue reference) and in your code it's basically the same as providing lvalue references instead of rvalue references (set aside the traits which differentiate them).
The difference is that when you pass an rvalue reference to a function/method you're telling it "i won't use that anymore, go ahead, do anything you want with it".
Longer answer: rvalue references appeared because you can initialize or assign objects with temporaries, but without them you had to:
- build a temporary
- pass a const reference of the temporary to the methof/function
- clear the muting object
- sometimes reallocate memory to hold the temporary's contents
- copy the temporary's contents
- destroy the temporary
In short, we were performing an unneeded (and potentially expensive) copy whereas we could have simply "moved" the ownership of the temporary's contents to the muted object (when possible).
Rvalue references were introduced so that we could have a type to represent objects in the end of their lifetime which can be freely modified because they won't be used any further anyway.
They are noted with && (not to be mistaken for "universal references" which also use && in a template deduction context).
The difference between passing by value and passing by rvalue reference is that passing value will call the copy constructor and provide you with a fresh instance of that object, whereas passing by rvalue reference (as i said before) behaves exactly the same as passing an usual non-const reference.
However, we don't use usual non-const references because they don't have the "same semantics" and that it would be problematic if a constructor mistook our lvalue reference for an rvalue reference and thrashed our object with its move constructor while we intended to use the copy constructor.