Pointer Confusion

Programmers discuss here anything related to FreeOrion programming. Primarily for the developers to discuss.

Moderator: Committer

Post Reply
Krill Swarm
Posts: 11
Joined: Thu Jul 03, 2008 8:35 pm

Pointer Confusion

#1 Post by jackbunny »

Forgive my C++ n00bishness, but could someone explain this line of code to me:

Code: Select all

GG::Clr line_color = Empires().Lookup(*fleet->Owners().begin())->Color();
More specifically the opening "*" within the Lookup method.

As I understand it: fleet->Owners() would be a references to a method of whatever fleet is pointing to. fleet->Owners().begin() would be a method of whatever object that method returns?

So *fleet->Owners().begin() would be a pointer to the object that the begin() method returns?!

Did I get that right? Ow. Head hurt bad.

User avatar
Geoff the Medio
Programming, Design, Admin
Posts: 12764
Joined: Wed Oct 08, 2003 1:33 am
Location: Munich

Re: Pointer Confusion

#2 Post by Geoff the Medio »

In this context, * is the dereferencing operator. If used on a pointer, it would return whatever the pointer points to. If used on an iterator, it's been overloaded to return what the iterator points to.


fleet->Owners() returns a std::set<int>

.begin() acts on the set and returns a std::set<int>::iterator that points to the first int in the set

* acts on the iterator, and returns the int that the iterator points to

Empires() returns an object that has a member function Lookup that takes a single int parameter.

Lookup is passed the int that is returned by the * operator and returns a pointer to an Empire object

->Color() is called on the returned Empire object, and returns a GG::Clr

* can also be used to declare a pointer, but that's not how it's being used here.

Note that you can get a pointer to (the address of) a variable using the & operator.

int x = 5; // declares and initializes int with value 5
int* int_pointer = &x; // declares a pointer to int and initializes with the address of the int x
int y = *int_pointer; // declares another int and initializes with the value of the int pointed to by int_pointer

Replaced "int" with another type or class and things should work the same.

Krill Swarm
Posts: 11
Joined: Thu Jul 03, 2008 8:35 pm

Re: Pointer Confusion

#3 Post by jackbunny »

Great! Thanks for clarifying. I think I had the concept, but I haven't had to worry about pointers in a long while. I've been doing C# programming in .NET at my day job, so that's a bit of a different animal. Thanks again!

Post Reply