Why can't you call functions on a pointer object? - c++

Edit: sorry about the stupid title; by "pointer object" I think I mean dereferenced object pointer (if that's any clarification).
I'm new to C++, and I've been trying to get used to its idiosyncrasies (coming from Java).
I know it's not usually necessary, but I wanted to try passing an object by its pointer. It works, of course, but I was expecting this to work too:
void test(Dog * d) {
*d.bark();
}
And it doesn't. Why is this? I found out that I can do the following:
void test(Dog * d) {
Dog dawg = *d;
dawg.bark();
}
and it works flawlessly. It seems so redundant to me.
Any clarification would be appreciated. Thanks!

Imo . has precedence over dereference * , thus:
(*d).bark();
or, for pointers, as stated in other replies - use ->
d->bark();
be sure to check for null :)

Just to clarify the situation, you can use either (*pointer).member(), or pointer->member() -- a->b is equivalent to (*a).b.
That, of course, is assuming you're dealing with "real" (built-in) pointers. It's possible to overload operator-> to do something different. Overloads of operator-> are somewhat restricted though, which generally prevents people from doing too strange of things with them. The one thing you might run into (e.g., with old implementations of some iterators) is simply failing to support operator-> at all, so trying to use it will result in a compile error. Though such implementations are (mostly?) long gone, you might still see some (typically older) code that uses (*iterator).whatever instead of -> because of this.

You have to use the -> operator on pointers. The . operator is for non-pointer objects.
In your first code snippet, try d->bark();. Should work fine!
EDIT: Other answers suggest (*d).bark();. That will work as well; the (*d) dereferences the pointer (ie. turns it into a normal object) which is why the . operator works. To use the original pointer, simply d, you must use the -> operator as I described.
Hope this helps!

Its all in the parentheses:
(*d).bark();

Everyone is missing one point to answer: Operator Precedence.
The precedence of operator. is higher than that of (unary) pointer indirection (*) opeartor. That's why brackets are needed. It's just like putting parenthesis around + to get correct average:
int nAverage = (n1+n2) / 2;
For pointer indirection case, you are lukcy that compiler is giving you error!

You need to use -> operator when using pointers, i.e. code should be d->bark();.

Related

using std::swap instead of assignment with '=' operator

I was going over some C++ source code from a library related to a pet-project I'm working on and encountered something I don't understand. In a place where I expected a pointer dereference followed by assignment, the library authors use std::swap() near the end of the function to write the result:
std::swap(*out, result);
I expected to see something like this:
*out = result;
Note that result is a typedef of size_t and out is a pointer to that same type.
When it comes to "systems programming", my background is in C and C# but not much at all in C++. Is there any particular reason for this type of "assignment"?
When the value types are more interesting, say, a std::vector<T>, for example, it may make more sense to std::swap() a temporarily constructed object into place rather than assigning it: given that the temporary result is about to go away, avoiding an assignment and just changing pointers makes some sense. I don't see any reason to do something like that with fundamental types like std::size_t, though.

Difference between treating the object as such or as pointer?

So say I have an object/pointer/whatever the definition of such a thing is:
A* a = new A();
who happens to have methods
b();
c();
The way of doing things that I've found out is this:
a->b();
and the method worked very well.
However now I have seen people doing it this way:
(*a).b();
The question is: What is the difference (i.e. how are addresses and values managed in each) between these two ways of calling methods and according to that, which is best one to use?
If this a duplicate of other question, just let me know, I will erase it after I see the original question.
There is no difference. It just a different notation.
For pointers, there is no difference:
If you declare:
A* pointer_to_A = new A();
Then these two are equivalent by definition:
pointer_to_A->b();
(*pointer_to_A).b();
If, however, you declare on object:
A a;
Then these two are not necessarily equivalent:
a->b();
(*a).b();
In this case, the first line invokes A::operator->() while the second invokes A::operator*(). (Aside: this case is somewhat rare. It is most often used for objects that behave like pointers: iterators, smart points and such. If they are well-designed, then the two forms above are still identical.)
There is no difference. Prefer -> as it is cleaner and states what you mean better.
However, -> and * can be overloaded. So for certain classes they may do different things, although this is very very uncommon, and impossible for pointers.
The -> notation is syntactic sugar.

What is wrong with my syntax in this 1 line bit of code (pointers and references and dereferences oh my)?

The code that I am having trouble with is this line:
result.addElement(&(*(setArray[i]) + *(rhs.setArray[j])));
The + operator in my class is overloaded like this (there are a variety of overloads that can fit in this set, but they all have a similar header):
const Rational Rational::operator+(const Rational &rhs) const
The setarrays in the code above are both arrays of pointers, but the + operator requires references, which might be the problem.
AddElement, the method of result, has this header:
bool Set::addElement(Multinumber* newElement)
The Multinumber* in the header is the parent class of Rational, mentioned above. I don't think any of the specific code matters. I'm pretty sure that it is a syntax issue.
My compiler error is:
68: error: invalid conversion from 'const Multinumber*' to 'Multinumber*'
Thank you for your help!
the issue is with const
bool Set::addElement(Multinumber* newElement) should be Set::addElement(const Multinumber* newElement)
Your operator + returns a const object. However, addElement requires a non-const object, which is where your compiler error is coming from. Basically, addElement is telling you that it feels at liberty to modify your Multinumber at will, but the operator + is beginning you not to modify the returned value.
You should just return a non-const object, unless there's a good reason not to. You're not returning a reference after all.
Of course, if the data in your Set is supposed to be constant and will never be changed, you may as well make addElement take a const pointer, and make sure that it internally deals with const pointers EVERYWHERE.
The issue is with the addElement expecting a non-const where as operator+ is returning a const object.
The fix for the code is cast the return as mentioned below
addElement((Multinumber * )&( *(setArray[i]) + *(rhs.setArray[j])));
If you dont want to cast, as casting might defeat the purpose of type checking here, then you have to change the signature of the addElement. That depending upon your project scope may have impact else where and if this API is public and other developers are using it. Changing signature will impact them also.
So choose wisely.
This code has much more serious issues than you can fix by adding a const or a typecast somewhere.
The result of this code will ultimately be a crash somewhere down the line, because you're passing a pointer to a temporary. Once you finish with line of code that calls addElement, the pointer will be left dangling, and trying to use the object it points to will either result in nonsense (if you're reading the object) or stack corrpution (if you're writing to the object).
The best way to redefine your code would be to change this to
bool Set::addElement(Multinumber newElement) //pass the Multinumber by value
and call addElement as follows:
result.addElement(*setArray[i] + *rhs.setArray[j]);
Note that I eliminated all of the extra parentheses because * has lower precedence than [], so the parentheses around setArray[i] and setArray[i] were redundant. I think the code is more readable this way.
Well really, if I can guess what's going on here, setArray is the internal storage of the Set class, so it's type will need to be redefined from Multinumber** to Multinumber*, in which case the call really should be
result.addElement(setArray[i] + rhs.setArray[j]);
EDIT Ugggh. None of the above will actually allow you to keep your polymorphism. You need to call new Rational somewhere, and the only reasonable place that I can think of is:
result.addElement( new Rational(*setArray[i] + *rhs.setArray[j]) );
This will work without having to redefine Set::addElement.
A better solution would be to redesign the whole thing so that it doesn't depend on polymorphism for numeric classes (because numeric classes really shouldn't be wrapped in pointers in most normal use).

c++ shorthand operator-> operator()

Suppose I have:
Foo foo;
is there a shorthand for this?
foo.operator->().operator()(1, 2);
Well... Yes. The shorter form would look as
foo.operator->()(1, 2)
As for eliminating the operator -> part... From the information you supplied so far it is impossible to say, but if it is implemented the way I can guess it is implemented (judging from your expression), then you can't eliminate it.
In C++ the use of overloaded -> operator in an expression is interpreted as a chain of repetitive overloaded -> calls, which eventually ends in a built-in -> invocation. This means that at some point the overloaded -> must return a pointer. Your overloaded -> obviously doesn't return a pointer. So, in order to use it you have no other choice but to spell it out explicitly as operator ->().
Assuming you actually meant foo.operator->().operator()(1, 2), and that you have control over the class Foo, a simpler form would be (*foo)(1, 2). It requires the operator* to that defined though, but since we usually expect foo->bar to be equivalent to (*foo).bar, it seems reasonable.
If your Foo is a smart pointer class of some sort, which points to an object which defines an operator(), this would be the most concise way of calling the object's operator().
But without more detail (and without you providing an expression that's actually valid C++ -- there's no way in which operator(1, 2) as you wrote it can be valid), it's impossible to answer your question. I'm just guessing at what you're trying to do.
Well, no, but, assuming you have write permissions to the class, you could define another member function that calls operator(), and then you'd have something like:
foo->myfunc(1,2);
That you find yourself in this position is a sign that you (or the person who wrote this class) is being a bit too cute with operator overloading.

What am I doing wrong with this pointer cast?

I'm building a GUI class for C++ and dealing a lot with pointers. An example call:
mainGui.activeWindow->activeWidget->init();
My problem here is that I want to cast the activeWidget pointer to another type. activeWidget is of type GUI_BASE. Derived from BASE I have other classes, such as GUI_BUTTON and GUI_TEXTBOX. I want to cast the activeWidget pointer from GUI_BASE to GUI_TEXTBOX. I assume it would look something like this:
(GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget)->function();
This isn't working, because the compiler still thinks the pointer is of type GUI_BASE. The following bit of code does work, however:
GUI_TEXTBOX *textbox_pointer;
textbox_pointer = (GUI_TEXTBOX*)mainGui.activeWindow->activeWidget;
textbox_pointer->function();
I'm hoping my problem here is just a syntax issue. Thanks for the help :)
The problem is that casts have lower precedence than the . -> () [] operators. You'll have to use a C++ style cast or add extra parentheses:
((GUI_TEXTBOX*)mainGui.activeWindow->activeWidget)->function(); // Extra parentheses
dynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget)->function(); // C++ style cast
You should not be using the C style cast.
You need to use the C++ dynamic cast. This will then allow you to test that the object is actually a GUI_TEXTBOX before you call the method on it.
GUI_TEXTBOX* textboxPointer = dynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget);
if (textboxPointer)
{
// If activeWidget is not a text box then dynamic_cast
// will return a NULL.
textboxPointer->textBoxMethod();
}
// or
dynamic_cast<GUI_TEXTBOX&>(*mainGui.activeWindow->activeWidget).textBoxMethod();
// This will throw bad_cast if the activeWidget is not a GUI_TEXTBOX
Note the C style cast and reinterpret_cast<>() are not guaranteed to work in this situation (Though on most compilers they will [but this is just an aspect of the implementation and you are getting lucky]). All bets are off if the object assigned to activeWidget actually uses multiple inheritance, in this situation you will start to see strange errors with most compilers if you do not use dynamic_cast<>().
You just need more parentheses:
((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();
Actually, this would work too:
((GUI_TEXTBOX*)mainGui.activeWindow->activeWidget)->function();
As others noted:
((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();
The reason is that the -> operator has a higher precedence than the type casting.
I'll put another plug in here for Steve Oualline's rule from "Practical C":
There are fifteen precedence rules in
C (&& comes before || comes before
?:). The practical programmer reduces
these to two:
1) Multiplication and division come
before addition and subtraction.
2) Put parentheses around everything
else.
And a final note: downcasts can be dangerous, see Martin York's answer for information on using dynamic_cast<> to perform the cast safely.
It's a matter of order of operators (operator precedence). Consider the code you were trying that didn't work:
(GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget)->function();
Here, the -> operator takes higher precedence than your cast. That's why your other code sample works. In the other sample, you explicitly cast first, then call the function. To make it more streamlined try adding another set of parenthesis so that the code looks like:
((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();
There are two strategies. One is "fail fast": If you cast to the wrong type, then you will have an exception thrown, so you will notice immediately that you cast to the wrong type. Another one is "run fast": No checking of the destination type of the cast is done. This cast should only be used if you know that you can't be wrong or if you don't have a polymorphic type with the base or the derived. I recommend the following depending on your needs (remember to keep const when you cast):
dynamic_cast<GUI_TEXTBOX&>(*mainGui.activeWindow->activeWidget).function();
Fail fast: throws std::bad_cast if you cast to the wrong type.
static_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget)->function();
Run fast: Doesn't do a runtime check. So it won't fail fast. Rather, it will produce undefined behavior if you cast to the wrong type. Beware!
((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();
-> has a higher precedence than (cast), so the member access is being done before the cast. See here for operator precedence: http://www.cppreference.com/wiki/operator_precedence
As stated above, you need more parentheses.
if( GUI_TEXTBOX* ptr =
dynamic_cast<GUI_TEXTBOX *>(mainGui.activeWindow->activeWidget) )
{
ptr->function();
}
The reason you want to do that is because the pointer you are trying to cast may not actually point to a GUI_TEXTBOX object and you want to make sure it does before calling textbox methods on it. C++'s dynamic cast is what you need for this.