Updating vector by passing by reference in constructor - c++

I am trying to write a piece of code where I am passing the vector by reference through constructor of a class and updating the vector in the member function of the class. But when I get back to the main function, no update occurs in the vector:
// Header file
class A{
private:
std::vector<T> &x;
public:
A(std::vector<T>& x_):x(x_) {}
int func();
};
// Cpp file
int A::func() {
// process done
T temp;
x.push_back(temp);
}
// Main function
int main() {
std::vector<T> vec;
A a(vec);
a.func();
}
I have tried changing the vector to be a pointer in the class instead of a reference but the vector doesnt update after the function runs. Any suggestions on what to change in the program?

#include <iostream>
#include <vector>
using namespace std;
class A
{
std::vector<int> &x;
public:
A(std::vector<int>& x_):x(x_) {}
int func();
};
int A::func(){
int temp=0;
x.push_back(temp);
return 0;
}
int main(){
std::vector<int> vec;
A a(vec);
a.func();
return 0;
}
everything is ok vec changed. I think you have another question or bug that you even dont aware of .

Related

Why Do I get this error on vector initialisation?

I have a problem with vector declaration and initialization in a
class constructor. I have a Station.h and Station.cpp files of a class and I recall it in main :
Station.h
#ifndef STATION_H
#define STATION_H
#include <vector>
class Station
{
public:
int num_bin;
int num_staz;
vector<int> binari; //here already gives me error! Vector does not name a type
Station(int num_staz, int num_bin);
virtual ~Station();
Station(const Station& other);
protected:
private:
};
Then I want to initialize the vector in the constructor of .cpp like that:
Station.cpp
#include "Station.h"
using namespace std;
Station::Station(int num_staz, int num_bin)
{
this->num_bin = num_bin;
this->num_staz = num_staz;
this->binari(num_bin); //here I want to create a vector of num_bin size
}
and then call it in main like that:
main.cpp
#include <iostream>
#include "Station.h"
using namespace std;
int main()
{
Station staz1(2,3);
staz1.binari.push_back(300); // error! class Station has no member binari
staz1.binari.push_back(250);
staz1.binari.push_back(150);
return 0;
}
Where am I making a mistake?
this->binari(num_bin); //here I want to create a vector of num_bin size
The function you need to use is std::vector::resize().
this->binari.resize(num_bin);
It will be better to initialize the object with the appropriate size as:
Station::Station(int num_staz, int num_bin) : num_bin(num_bin),
num_staz(num_staz),
binari(num_bin)
{
}
this->binari(num_bin); This doesn't work because it is not an initialization that is why it doesn't work.
To make this work use it in in-class initialization list:
Station::Station(int num_staz, int num_bin) :
num_bin(num_bin),
num_staz(num_staz),
binari(num_bin)
{
}

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.

I am unable to initialize a data member of object by passing object as parameter

#include<iostream>
using namespace std;
class one
{
public:
int datam;
void show()
{
cout<<datam;
}
};
void addv(one par)
{
par.datam=2;
}
int main()
{
one w;
addv(w);
w.show();
return 0;
}
After compilation this gives garbage value. Why can't I initialize datamember(datam) of object w.
I know there are other methods to initialize but what is the problem in this method?
You need to pass by reference. See the modified code below:
#include<iostream>
using namespace std;
class one
{
public:
int datam;
void show()
{
cout<<datam;
}
};
void addv(one &par)
{
par.datam=5;
}
int main()
{
one w;
addv(w);
w.show();
return 0;
}
Note that I have changed the prototype of function addv() as:
void addv(one &par)
//------------^^^^
In your code, you are passing by value (and not reference) due to which, you get a garbage value. Working code here.
You are not passing anything by reference. To pass by reference your function should be declared as void addv(one &par) . So you are passing a copy and initializing the copy which gets destroyed before the function returns.

create an unary_function functor for non-static member function

The code should explain my difficulty. Though the code itself is quite meaningless, I'm planning to add containers in MyClass, and use algorithms with member functions.
#include <cstdlib>
#include <algorithm>
#include <functional>
using namespace std;
class MyClass
{
public:
MyClass() { a = 0; }
~MyClass() {}
private:
int a;
bool tiny_test (int);
int Func();
};
bool MyClass::tiny_test (int b)
{
return a == b;
}
int MyClass::Func()
{
// does not compile
(mem_fun(&MyClass::tiny_test))(this);
// commented below is another attempt, also no success
//mem_fun1_t<bool, MyClass, int> tmp_functor = mem_fun(&MyClass::tiny_test);
//tmp_functor(this);
return 0;
}
int main(int argc, char** argv)
{
return 0;
}
Thanks a lot! Btw, I'm not using a static member function, simply because I believe it must work for non-static member functions.
P.S. Eric, Jarod42, thanks for prompt replies!
bool MyClass::tiny_test (int b)
{ // ^^^^^ You missed this argument
return a == b;
}
Try this:
// Supply one more argument. E.g., 3
(mem_fun(&MyClass::tiny_test))(this, 3);

How do you call a class and its method when its stored in a pointer array

How do you use a pointer and call the class methods it points to?
For example:
Image *img[26];
Image IM = outputImage();
img[0] = &IM;
I want to call img[0], or IM's methods. I tried something like this but I received errors.
img[0].getPixel(0,1);
The error is "expression must have a class type"
Since you are using a pointer array, you must dereference it as a pointer.
img[0]->getPixel(0, 1);
And this:
Image IM = outputImage();
should be:
Image &IM = outputImage();
Assuming that outputImage() returns a reference.
you can use following two methods:
1) use -> operator to the member function.
#include<iostream>
using namespace std;
class myclass
{
public:
void printHello()
{
cout<<"hello from class"<<endl;
}
};
int main()
{
myclass *s[10];
myclass inst;
s[0]=&inst;
s[0]->printHello();
return 0;
}
2) use . after de-referencing the pointer.
#include<iostream>
using namespace std;
class myclass
{
public:
void printHello()
{
cout<<"hello from class"<<endl;
}
};
int main()
{
myclass *s[10];
myclass inst;
s[0]=&inst;
(*s[0]).printHello();
return 0;
}