What adress does "&ref_var" points to? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Consider the following code:
std::vector &MyClass::getVector() const
{
return (myVec);
}
void aFunc()
{
std::vector *vec = &myClassInstance.getVector();
}
What adress does vec points to? Does it points to the very address of myVec in the myClassInstance object? (btw I know I should return a const ref, but it is an example).

You are returning a reference to myVec in the method getVector. When you take the address of a reference, you get the address of the variable the reference refers to. So vec will contain the address of myVec.

A reference is an alias to another variable. When you return a reference tomyVec from getVector() then you can consider calling the function to be exactly like accessing myVec if it were publicly available.
&MyClass.myVec == &myClassInstance.getVector()
What adress does vec points to?
The address of myClassInstance.getVector() will be the same as the address of myVec.
Also note that since you are returning an lvalue reference you can even use it on the left hand side of an assignment like
myClassInstance.getVector() = some_other_vector;
And now myVec will be a copy of some_other_vector.

Yes, it does point to the very vector myVec in your MyClass instance. See the following sample code:
#include <cstdio>
#include <vector>
class MyClass {
std::vector<int> myVec;
public:
MyClass() {}
~MyClass() {}
std::vector<int>& getVector()
{
return myVec;
}
void printVector() const
{
for(std::vector<int>::const_iterator it = myVec.begin(); it != myVec.end(); ++it)
{
printf("%d ", *it);
}
printf("\n");
}
};
int main(int, char**)
{
MyClass item;
std::vector<int>* vec = &(item.getVector());
vec->push_back(1);
item.printVector();
return 0;
}
Running this program will output:
$ ./a.out
1
So you can see that calling getVector() returns a reference to myVec from the MyClass instance, since we add a new item to the vector (vec->push_back(1)) via the vec pointer then print the MyClass instance's vector, and it shows that the item we added is there in myVec.

Related

Initializing an object as in a vector class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
So, I know a vector object can be declared and initialized like this:
// Nothing new here. I know <int> is a template
// and how to implement it:
vector <int> vect{ 10, 20, 30 };
I assume that the vector object has inside an array of values, and the functions of that class (like push_back() for example) manage it. I would like and have been trying to implement something like that in a class of my own, without success. Would be interesting being able to understand how it's done! Did many "experiments" but none worked.
// Random named class:
class A_Class
{
private:
// A pointer for the type I want:
int *A_pointer_To_int;
public:
// Trying to accept the input values between
// brackets and putting them inside a temp array:
A_Class(int Input_Array[]) {}
};
int main()
{
// trying to create the object like in the vector class.
// Returns error "No instance of constructor matches the argument list":
A_Class My_Object{1,2,3}
return 0;
}
In a function parameter, int Input_Array[] is just syntax sugar for a decayed pointer int* Input_Array, which does not provide any information about any array that may be passed in to it.
For what you are attempting, you need to accept a std::initializer_list instead, eg:
#include <initializer_list>
#include <algorithm>
// Random named class:
class A_Class
{
private:
// A pointer for the type I want:
int *A_pointer_To_int;
// the number of values in the array:
size_t size;
public:
A_Class(std::initializer_list<int> Input_Values) {
size = Input_Values.size();
A_pointer_To_int = new int[size];
std::copy(Input_Values.begin(), Input_Values.end(), A_pointer_To_int);
}
~A_Class() {
delete[] A_pointer_To_int;
}
};
int main()
{
A_Class My_Object{1,2,3}; // works now
return 0;
}
Online Demo

Can't iterate through std::map [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Since I've started to using std::map I've started to receive assertion error whenever I click on the button. I want to clear all the contents inside my_map and start adding again everytime I click the button.
my.cpp
typedef std::map<str, MyClass> mapper;
mapper my_map;
void add_map(const str& name, MyClass* l) { /...../ }
void invoke_me()
{
Here I initialized variable i with the size of my_map, however, it returns the previous size before it was cleared
int i = my_map.size(); // i = 4, my_map.size() = 1
if (!my_map.empty())
{
for (const auto& it : map)
{
// Assert error: map/set iterator not incrementable
const MyClass& l = it.second;
l.on_clicked();
}
}
}
// cont'd
This should do the neat clearing of my_map, but I don't think it's doing the right job
void clear_map()
{
my_map.clear();
}
implementor.h
struct MyClass
{
std::function<void()> on_clicked;
};
implementor.cpp
MyClass button;
button.on_clicked = [&] {
clear_map();
add_map("MyButton", &button);
};
Well actually on_click is a callback, and it has to be called through the invoke_me function
main.cpp
while (RUNNING)
invoke_me();
I would say that it is because of incorrect map size that's why the it keeps looping even if it's out of bounds, or maybe I'd corrupted or messed up that map.
There might be more issues, but this looks to be the main one:
button.on_clicked = [&] {
clear_map();
add_map("MyButton", &button);
};
You're clearing the map, and this function gets called while you're iterating:
for (const auto& it : my_map)
{
// Assert error: map/set iterator not incrementable
const MyClass& l = it.second;
l.on_clicked();
}
Your iterators are being invalidated by the clear.

Reference not returning? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
My class has an array of objects, call it Foo. It is stored as Foo* m_Foos in the class. Say it has a value at [0], guaranteed, and Foo has a property called IsSetthat's just a bool or something.
void TryThis()
{
Foo returnValue;
GetValue(returnValue);
returnValue.IsSet = true;
if(m_Foo[0].IsSet != returnValue.IsSet)
{
// ERROR!!!!
}
}
void GetValue(Foo &container)
{
container = m_Foos[0];
}
Can anyone explain why m_Foo[0] =/= returnValue? Where is the error in my syntax?
I expect m_Foo[0] to be the same reference as returnValue, the same Foo in memory.
TryThis() is not modifying the Foo object that is stored in the m_Foos array.
GetValue() is assigning the Foo object from m_Foos[0] to another Foo object that is local to TryThis(). A copy is being made during that assigment. TryThis() is then modifying the copy, not the original.
If you want TryThis() to modify the original Foo object directly, you need to do something more like this instead:
void TryThis()
{
Foo &returnValue = GetValue();
returnValue.IsSet = true;
// m_Foo[0] is set true.
}
Foo& GetValue()
{
return m_Foos[0];
}
Or this:
void TryThis()
{
Foo *returnValue;
GetValue(returnValue);
returnValue->IsSet = true;
// m_Foo[0] is set true.
}
void GetValue(Foo* &container)
{
container = &m_Foos[0];
}

Best way to return and assign a vector in c++ between multiple functions [duplicate]

This question already has answers here:
Why is it OK to return a 'vector' from a function?
(6 answers)
Closed 6 years ago.
I am hoping to get a newly generated vector and add into a global vector from calling two functions in main. I have a rough idea of how to do this but apparently this is not right..pretty new to c++ and I don't really quite want to deal with vector recycle..do I have to use pointers if I can't use C++11? what's the best way to do this?
void main(){
vector <int> newVector = function1 ();
addVector (newVector);
}
vector <int> function1 (){
....
return returnedVector
}
void addVectors (vector <int> incomingVector){
globalVector.insert( globalVector.end(), incomingVector.begin(), incomingVector.end());
}
First off, void main() in c++ is bad - it should be int main().
Secondly, you have the statement return vector; in function1() whilst you are likely using namespace std; - this is also very bad, as it can be interpreted as attempting to return a type which is not possible nor what you want to do.
Here is a refactoring of your code:
#include <vector>
std::vector<int> function1(); // declaration
void add_vectors(std::vector<int>& ov, const std::vector<int>& iv);
int main() {
std::vector<int> overall_vec;
std::vector<int> vec = function1();
add_vector(overall_vec, vec);
}
std::vector<int> function1() { // definition
std::vector<int> rtnvec;
// fill rtnvec with some values
return rtnvec;
}
// insert incoming_vec to end of overall_vec
void add_vectors(std::vector<int>& overall_vec, const std::vector<int>& incoming_vec) {
overall_vec.insert(overall_vector.end(), incoming_vec.begin(), incoming_vec.end());
}
Note that we haven't used a global std::vector variable here as global variables are generally quite bad, it's typically better to pass the vector around by reference or const reference when and if you need to - or wrap your code in a class or namespace if the situation is suitable for either.

pack multiple c++ objects and pass to function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using a c library to do integration, where the integrand is declared as fun(...,void *fdata,...)
which uses *fdata pointer to pass external variables, however, before doing numerical integration, I need to
interpolate the raw data using other c++ libraries, giving back some interpolating class objects,
basically I want to pass these objects to a integrand which is user-defined ...
You could use an structure and pass a pointer to it but it seems to me that you don't have a fixed number of objects to pass and therefore that an object aggregating others dynamically would suit better your needs so you can use a std::vector and pass its address as func fdata parameter.
An example:
#include <vector>
#include <iostream>
using namespace std;
class C //Mock class for your objs
{
public:
C(int x)
{
this->x = x;
}
void show()
{
cout << x << endl;
}
private:
int x;
};
void func(void *fdata) //Your function which will recieve a pointer to your collection (vector)
{
vector <C *> * v = (vector<C *> *)fdata; //Pointer cast
C * po1 = v->at(0);
C * po2 = v->at(1);
po1->show();
po2->show();
}
int main()
{
vector<C *> topass;
topass.push_back(new C(1)); //Create objects and add them to your collection (std::vector)
topass.push_back(new C(2));
func((void *)(&topass)); //Call to func
for(vector<C *>::iterator it = topass.begin(); it != topass.end(); it++)
delete(*it);
}