Pointer list c++ - c++

The code below:
#include <iostream>
#include <list>
class A
{
public:
void printHello(){std::cout << "hello";}
};
int main(int argc, char *argv)
{
std::list<A*> lista;
lista.push_back(new A());
for(std::list<A*>::iterator it=lista.begin();it!=lista.end();++it)
{
//how to get to printHello method?
//it doesn't work
it->printHello();
}
return 0;
}
This code doesn't work. My question is how to get to method 'printHello' by iterator it? Thanks.

You want
(*it)->printHello();
as the *it returns the stored pointer A* and only then you can apply ->.

Just change following line
it->printHello();
to
(*it)->printHello();
The operator*() gives access to the contained data of the container, which in your case is a pointer. When not using pointers in containers, just using operator->() would work, too.

De-referencing it will give you pointer to A, then you need to access the methods or data members.
So use :
(*it)->printHello();

Let me expand on Daniel's answer.
When you stick an asterisk in front of a variable, it is called 'dereferencing'. Used this way, the Asterisk is a 'Dereference Operator'. To put it noob-ishly (I don't know what level of understanding you have offhand), *pMyPointer acts like it was the Object that the pMyPointer was pointing to. If it was a Pointer to a Pointer, then the result is just the Pointer.
As an example, when you call a method on a pointer, you use the Into Operator ->.
These two often do the same thing:
pMyPointer->MyFunction();
(*pMyPointer).MyFunction();
In the case of the C++ iterators, the Dereference Operator is overwritten to return the object stored in its position. In this case, what is stored in its position is a pointer, so you still have to use -> unless you stick another Dereference Operator in there.

Related

What does the pointer 'this+1' refer to in C++?

I was wandering through the code of Sequitur G2P and found a really strange line of code:
public:
...
const Node *childrenEnd() const { return (this+1)->finalized.firstChild_; }
I know that this is a pointer to the current object, and since it is a pointer, the operation is perfectly legal, but what does this+1 actually refer to?
Presumably this is part of an array, so this+1 would refer to the next object in that array.
this is simply a pointer which refers to this object. Since it's a pointer, you can apply pointer arithmetic and even array indexing.
If this object is an element in an array, this+1 would point to the next object in the array.
If it's not, well it's just going to treat whatever is at that memory the same as this object, which will be undefined behaviour unless it is the same type.
As it is NLP it makes sense to optimize memory management. I assume you find overloaded new/delete methods as well.
The this+1 construct assumes all objects reside in an array. The name 'childrenEnd' of the method indicates it returns a pointer to an address of the end of the children of the current node.
Thus you are looking at an implementation of a tree structure. All siblings are adjacent and their children as well.
"this + 1" in C++ class means:
if the "this" object is a member of another object it will point to the address of the parent's object next variable declared just after the "this" object variable:
Example:
class B
{
public:
void* data()
{
return this + 1;
}
};
class A
{
public:
B m_b;
char m_test;
};
int main(int argc, char* argv[])
{
A a;
a.m_test = 'H';
void* p = a.m_b.data();
char c;
memcpy(&c, p, sizeof(char));
return 0;
}
c is equal 'H'.
Long story short it allows to access to parent's class data without passing parent's pointer to the child class. In this example this + 1 point to the m_test member of the class A.
Actually, there is a case, when this thing could be used. I don't recommend to use this method, but it certainly works.
I believe, in NLP code it was used something like that:
when you want your object to behave as a collection (an array etc) to use it similarly as an array with something range-based etc, you can do this trick:
struct Obj {
...
Obj* begin() { return this; }
Obj* end() { return this+1; }
...
}
Now, you can use this object in, for example, range-based for-loops...
Sometimes all that is necessary... but just even there you'd better use "nullptr" or even do refactoring than to use this trick.

When to use Pointer-to-Pointer in C++?

I was wondering when we use Pointer to Pointer in C++ and why we need to point to a pointer? I know that when we point to a pointer it means we are saving the memory address of a variable into the memory but I don't know why we need it? Also I have seen some examples that always the use Pointer-to-pointer in creating a Matrix! But why a Matrix may need Pointer to Pointer?
When to use Pointer-to-Pointer in C++?
I'd say it is better to never use it in C++. Ideally, you will only have to use it when dealing with C APIs or some legacy stuff, still related to or designed with C APIs in mind.
Pointer to pointer has pretty much been made obsolete by the C++ language features and the accompanying standard library. You have references for when you want to pass a pointer and edit the original pointer in a function, and for stuff like a pointer to an array of strings you are better off using a std::vector<std::string>. The same applies for multidimensional arrays, matrices and whatnot, C++ has a better way of dealing with those things than cryptic pointers to pointers.
When you want to change the value of variable passed to a function as the function argument, and preserve updated value outside of that function, you require pointer(single pointer) to that variable.
void modify(int* p)
{
*p = 10;
}
int main()
{
int a = 5;
modify(&a);
cout << a << endl;
}
Now when you want to change the value of the pointer passed to a function as the function argument, you require pointer to a pointer.
In simple words, Use ** when you want to preserve (OR retain change in) the Memory-Allocation or Assignment even outside of a function call. (So, Pass such function with double pointer arg.)
This may not be a very good example, but will show you the basic use:
void safe_free(int** p)
{
free(*p);
*p = 0;
}
int main()
{
int* p = (int*)malloc(sizeof(int));
cout << "p:" << p << endl;
*p = 42;
safe_free(&p);
cout << "p:" << p << endl;
}
We basically need pointer to pointer when we want to change the address of the pointer it is pointing to. very good example will be the case of linked list where we send a pointer to pointer to the head node when we try to insert a value to the beginning. Snippet of code pasted below.
int main()
{
/* Start with the empty list */
struct node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 2);
.....
....
}
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node = (struct node*) malloc(sizeof(struct node));
.....
.....
}
This is basically because, say a pointer was initially pointing to a memory location 0X100 and we want to change it to point it to some other location say 0X108. In such case pointer to pointer is passed.
You have probably seen int main() before, have you seen this:
int main(int argc, char** argv)
argv is indeed a double pointer, it's not actually a double pointer but it is a pointer to an array of pointers, each pointing to an array of characters pertaining to the command line arguments.
This is not the best example, as you probably want a more practical example. I will write up a better example and edit my post :)
Edit:
If you are familiar with classes and virtual functions then you may also be aware that any class who has a virtual function is automatically given a _vftp member variable.
The _vftp member is a pointer to a list of all the function pointers to your virtual functions. It is inserted at the very beginning of the structure.
If you created a new object as follows:
class myclass
{
public:
//void *_vftp; this is where the _vftp member gets inserted automatically
virtual void vfunc1();
};
void myclass::vfunc1() {printf("yay");}
void main() {
myclass *pMyObject = new myclass();
}
Upon instantiating myclass, the _vftp is added to the object structure and it is the very first variable. Because pMyObject is a pointer to this structure in memory, *pMyObject is eqal to _vftp.
Because _vftp is a pointer to the array of virtual function pointers, *_vftp is equal to vfunc1 (a function pointer).
This means if we dereference pMyObject twice, and call it, we will call vfunc1():
typedef (void* (__thiscall* fnVFunc1))(void);
((fnVFunc)**pMyObject)();
Although this is not a real use for double pointers this is a prime example of applying them. The most common place for double pointers lays in hacking and reverse engineering, where you commonly need to find a pointer in memory and alter whatever it points to.
Anytime you're dealing with C libraries. There are two common answers for the same question in C :
First, anytime you want doubly subscripted array, like :
int main(int argc, char** argv)
Second, anytime you want another return value from a function. There are many functions in libgit2 that do this because they wish to return a meaningful error type as opposed to just null, like the first argument in git_branch_create for example.
You could return a two item struct of course, but that's usually two extra lines of code. In fact, the pointer-to-pointer lets you write the pointer directly into a struct where it'll live.
In C++, you'd avoid using pointers directly whenever suitable C++ data types exist, and my libgit2 example is subsumed by C++'s exceptions, but..
You cannot call C++ from most high level languages, so if you're writing a library that you want available in say Perl, Python, and C++, then you write it in C.
Say you wanna instantiate an object in C++...
MyClass * obj = new MyClass();
You have to do this because new returns a pointer to the allocated object in dynamic memory. The following would be wrong:
MyClass obj = new MyClass(); // wrong. 'new' returns a pointer.
Say you want an array of objects...
MyClass ** objArray = new MyClass*[10];

Is there a case where element selection by reference and element selection through pointer operation are both valid?

My background is in more managed languages (C#, python) but I am becoming more experienced in C/C++. I am familiar with why the selection by reference (.) and selection through pointer operation (->) operators are different. In all cases I have encountered, if you use the incorrect one, it will result in a compile error. If that is the case, they why were they not made into one operator? Is there a case where using either on the same object results in different, meaningful and useful results?
This question inspired by this answer:
Is this right way to call a function in c++?
In C++ you can overload the ->-operator, which is used in pretty much all smart pointer implementations. However, some of those also have their own methods, i.e. to release a reference.
struct test {
int x;
};
std::shared_ptr<int> ptr(new test);
// Write to member x of the allocated object
ptr->x = 3;
// Reset the shared pointer to point to a different object.
// If there are no further shared_ptrs pointing to the previously allocated one,
// it is deleted.
ptr.reset(new test)
Additionally, it would be quite messy for the compiler to resolve operator-. for something like multiple-level pointers, i.e. test*** ptr. With your logic, ptr.x, (*ptr).x, (**ptr).x and (***ptr).x would all be the same.
You cannot apply -> to a reference to a basic type and you cannot apply . to a pointer, but you can apply both to a user-defined type and they will have different meanings. The simplest example is a smart pointer, like std::shared_ptr:
struct A { int x; };
std::shared_ptr<A> p(new A);
p->x = 10;
p.reset();
Is there a case where element selection by reference and element selection through pointer operation are both valid?
Since you can overload operator->() in C++, you can actually arrive at situations where you can use -> and . interchangeably on the same object. You can even engineer things so that you get a different result, as per this example:
#include <iostream>
struct Bar
{
void hello() const { std::cout << "Bar!!!\n"; }
};
struct FooBar
{
Bar bar;
void hello() const { std::cout << "FooBar!!!\n"; }
const Bar* operator->() const {return &bar; }
};
int main()
{
FooBar fb;
fb->hello();
fb.hello();
}
Of course, in real code you would never do something as crazy as this (although I have seen this kind of thing in "production" code).
the short answer would be a smart pointer
you can access the smart pointer class arguments using the "." (if you make your own smart pointer class you can extract from there for instance the current reference count) while you would use the "->" operator to access whatever is being stored using the smart pointer.

C++ Iterators, interfaces and pointers

I'm trying to use c++ iterators with interfaces, but does not manage to make it working.
I'm a bit lost with what type to choose for the vector contents. Is this need to be a pointer ? do I have to make a "new Implementation()"? In brief, it is unclear to me, and I can't manage to find useful examples about that.
Here are the interfaces and implementations (the .h file).
class Interface{
public:
virtual int method() = 0;
};
class Implementation1 : public Interface{
public:
int method();
};
class Implementation2 : public Interface{
public:
int method();
};
The .cpp file:
#include "content.h"
int Implementation1::method(){
return 1;
}
int Implementation2::method(){
return 2;
}
And my main function:
#include "content.h"
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
// create the vector and put elements in it
vector<Interface*> elements;
elements.push_back(new Implementation1());
elements.push_back(new Implementation1());
elements.push_back(new Implementation2());
// now iterate on them
vector<Interface*>::iterator iterator;
for(iterator = elements.begin(); iterator != elements.end(); ++iterator ){
*iterator->method();
}
return 1;
}
the compilator is outputting:
main.cpp: In function ‘int main()’:
main.cpp:19: error: request for member
‘method’ in ‘*
iterator.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> with _Iterator = Interface**, _Container = std::vector >’,
which is of non-class type
‘Interface*’
Any idea about what I'm doing wrong here ?
Change *iterator->method(); to (*iterator)->method();
The former dereferences the return of iterator->method(). Interface* doesn't have a method(), it doesn't have anything.
You want to dereference the iterator to get to your pointer, and then dereference IT.
You've basically got the same thing as Iterator** so act accordingly.
+1 for Noah about the compile error with iterator, that's a good explanation. As for your former question:
I'm a bit lost with what type to choose for the vector contents. Is this need to be a pointer ? do I have to make a "new Implementation()"?
Yes, this has to be a pointer. The reason is simple: the vector of type T stores (and owns) only elements of type T, not subtypes - and there are good reasons for that (what if the subclass had a different size?).
Therefore you have to store the objects somewhere and keep the pointers in the vector. In fact, storing them on the free store via operator new is the easiest option.
If you want your life a bit easier, you can use boost::ptr_vector for your purposes.
try (*iterator)->method();
There's nothing inherently invalid about what you've done, but creating a vector of raw pointers is typically a bad idea, you should use an ownership enforcing pointer (a "smart" pointer) like shared_ptr. And you also don't need to de-reference the iterator, it should just offer ->method() directly. However, I don't see anything directly uncompilable with this code, except possibly your *iterator->method(), cause last time I checked de-reference has a really low precedence and you may be doing *(iterator->method()) which is uncompilable.

when i need pass by pointer (and not by reference)

Can you give me an example when I can't pass argument by reference and I need to use pointer. I've found an example, but I'm not sure.
Suppose you have a class D derived from the base class B. You need pointer if you want do so:
void function(B* b){...}
int main{
D* d;
function(d);
}
The single time where you can not use a reference and must use a pointer is if you allow the concept of "no argument" by passing a null pointer.
However, you might want to use pointers as arguments when you are actually storing a pointer to whatever was passed. Most C++ developpers will notice that you aren't using a reference and pay special attention to what your documentation says.
If there is a coding guideline (like Google's) that says to use pointer arguments, then that's what you do.
Otherwise, only declare your own function with pointer formal argument when
a nullpointer is a valid & meaningful actual argument, or
the actual argument is most naturally pointer already, or
you're going to store that pointer somewhere.
Possibly more cases, but I think you get the drift: when you have a choice (no coding guideline saying otherwise), prefer references.
Cheers & hth.,
Another case: if the thing you're passing is the last argument before varargs:
void fn1(A &a, ...); // Uh oh
void fn2(A *a, ...); // Good
I don't know if this is required by the standard, or is just a bug in the implementation of the C++ compiler I use.
Typically, you use pointers for one of two things:
Reassignability - you can't rebind a
reference.
Null pointers - there's no such
thing as a null reference.
If your intended use case does not need either of those two properties, use a reference. Else, use a pointer.
If you want to allow the lack of an object, you need to use pointers:
// This allows DoSomething to receive pointers to NULL, which cannot
// be done with references
void DoSomething(Something *pSomething)
{
if (pSomething)
{
...
}
}
int main()
{
Something *pSomething=NULL;
DoSomething(pSomething);
}
http://www.daniweb.com/forums/thread216353.html
Singly linked lists example were pointers and pointer of pointers are used as function parameters.
the only reason is if you need to pass null. I.e you want to call the function saying 'I haven't got one of those'
I think that if you want to pass a function, you have to pass it by pointer. I don't see how you can pass the function by reference.
For example, take the following function:
#include <iostream>
#include "math.h"
void myfun (double value, size_t nofloops, double (*function)(double))
{
std::cout << value << std::endl;
for (size_t i=0;i<nofloops;++i)
{
value = function(value);
std::cout << value << std::endl;
}
std::cout << "------------------" << std::endl;
}
void main()
{
myfun(100,10,sin);
myfun(100,10,cos);
myfun(100,10,sqrt);
}
The function in this small utility executes the given function a number of times, taking the result as input in the next iteration. I can't see how you can pass the function by reference.