Difference between treating the object as such or as pointer? - c++

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.

Related

Any reason not to use global lambdas?

We had a function that used a non-capturing lambda internal to itself, e.g.:
void foo() {
auto bar = [](int a, int b){ return a + b; }
// code using bar(x,y) a bunch of times
}
Now the functionality implemented by the lambda became needed elsewhere, so I am going to lift the lambda out of foo() into the global/namespace scope. I can either leave it as a lambda, making it a copy-paste option, or change it to a proper function:
auto bar = [](int a, int b){ return a + b; } // option 1
int bar(int a, int b){ return a + b; } // option 2
void foo() {
// code using bar(x,y) a bunch of times
}
Changing it to a proper function is trivial, but it made me wonder if there is some reason not to leave it as a lambda? Is there any reason not to just use lambdas everywhere instead of "regular" global functions?
There's one very important reason not to use global lambdas: because it's not normal.
C++'s regular function syntax has been around since the days of C. Programmers have known for decades what said syntax means and how they work (though admittedly that whole function-to-pointer decay thing sometimes bites even seasoned programmers). If a C++ programmer of any skill level beyond "utter newbie" sees a function definition, they know what they're getting.
A global lambda is a different beast altogether. It has different behavior from a regular function. Lambdas are objects, while functions are not. They have a type, but that type is distinct from the type of their function. And so forth.
So now, you've raised the bar in communicating with other programmers. A C++ programmer needs to understand lambdas if they're going to understand what this function is doing. And yes, this is 2019, so a decent C++ programmer should have an idea what a lambda looks like. But it is still a higher bar.
And even if they understand it, the question on that programmer's mind will be... why did the writer of this code write it that way? And if you don't have a good answer for that question (for example, because you explicitly want to forbid overloading and ADL, as in Ranges customization points), then you should use the common mechanism.
Prefer expected solutions to novel ones where appropriate. Use the least complicated method of getting your point across.
I can think of a few reasons you'd want to avoid global lambdas as drop-in replacements for regular functions:
regular functions can be overloaded; lambdas cannot (there are techniques to simulate this, however)
Despite the fact that they are function-like, even a non-capturing lambda like this will occupy memory (generally 1 byte for non-capturing).
as pointed out in the comments, modern compilers will optimize this storage away under the as-if rule
"Why shouldn't I use lambdas to replace stateful functors (classes)?"
classes simply have fewer restrictions than lambdas and should therefore be the first thing you reach for
(public/private data, overloading, helper methods, etc.)
if the lambda has state, then it is all the more difficult to reason about when it becomes global.
We should prefer to create an instance of a class at the narrowest possible scope
it's already difficult to convert a non-capturing lambda into a function pointer, and it is impossible for a lambda that specifies anything in its capture.
classes give us a straightforward way to create function pointers, and they're also what many programmers are more comfortable with
Lambdas with any capture cannot be default-constructed (in C++20. Previously there was no default constructor in any case)
Is there any reason not to just use lambdas everywhere instead of "regular" global functions?
A problem of a certain level of complexity requires a solution of at least the same complexity. But if there is a less complex solution for the same problem, then there is really no justification for using the more complex one. Why introduce complexity you don't need?
Between a lambda and a function, a function is simply the less complex kind of entity of the two. You don't have to justify not using a lambda. You have to justify using one. A lambda expression introduces a closure type, which is an unnamed class type with all the usual special member functions, a function call operator, and, in this case, an implicit conversion operator to function pointer, and creates an object of that type. Copy-initializing a global variable from a lambda expression simply does a lot more than just defining a function. It defines a class type with six implicitly-declared functions, defines two more operator functions, and creates an object. The compiler has to do a lot more. If you don't need any of the features of a lambda, then don't use a lambda…
After asking, I thought of a reason to not do this: Since these are variables, they are prone to Static Initialization Order Fiasco (https://isocpp.org/wiki/faq/ctors#static-init-order), which could cause bugs down the line.
if there is some reason not to leave it as a lambda? Is there any reason not to just use lambdas everywhere instead of "regular" global functions?
We used to use functions instead of global functor, so it breaks the coherency and the Principle of least astonishment.
The main differences are:
functions can be overloaded, whereas functors cannot.
functions can be found with ADL, not functors.
Lambdas are anonymous functions.
If you are using a named lambda, it means you are basically using a named anonymous function. To avoid this oxymoron, you might as well use a function.

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

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();.

Is it okay to use the this pointer? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Is there any reason to use this->
When should this-> be used?
When should I make explicit use of the this pointer?
When working with pointers to classes, I like to add a this-> in front of variables in a class to make it clearer that the variable I'm talking about is in the current class, as opposed to temporary variables, etc. So my lines would be something like
if(this->thing > other->thing)
this->doFoo();
Instead of
if(thing > other->thing)
doFoo();
Is it okay to add the superfluous this, or would that degrade code readability?
Consistency consistency consistency.
I conisder the this-> prefix a valid coding style if you use it throughout your entire project everywhere a member is accessed.
I prefer using a signifying prefix for members, e.g. m_. I feel it is less cutter and less tag soup than the explicit this->:
(alpha-this->gamma > this->alpha-gamma)
vs.
(alpha-m_gamma > m_alpha-gamma)
(The dotNetties have labeled m_ outdated - I use it on small C# projects out of spite. but anyway, any other distinct prefix would do, too.)
I've seen it used often to help intellisense get in gear, or to specifically filter members - which is ok, though leaving it in for that reason is questionable, especially if not used consistently.
That depends on your coding style, however many people would use
_myVariable
m_myVariable
myVariable_
To differentiate member variables from the other.
But the most important thing is to just be consistent
This is a style question, so answers will be subjective. Similarly, a lot of people I've worked with like to prefix member variables with m_ to make it clear that it's a member. (m_foo would be like your this->foo.) Then I'm sure there are people who feel this is a crime against the universe. YMMV. Use what works for you and anyone you might be working with.
One advantage (or disadvantage, depending on who you ask) to this-> is that you can have a variable with the same name that can be both a member and something locally scoped like a parameter or local variable, eg.:
foo bar;
void f(foo bar)
{
this->bar = bar;
}
As already noted this is, mostly, a matter of style.
Personally I do not use it for the data-members (I use the m prefix alternative), however I do use it for functions:
for consistency with templated code, where this might be necessary to defer lookup
for clarity, in order to distinguish at a glance whether it's a method of the class (possibly a base class) or a free-standing function
I think that, since you definitely don't want to trudge through levels of base class when reading up some code, the this-> clarification makes it much easier for the reader. And it's only 6 more characters to type.
I like this pattern too, but I like it more in managed code where it's "this." - the arrow operator does feel a bit noisier, but still it makes it very clear when you're referring to instance-level stuff.
of course you can do it, besides, the compiler would add it for you.
Normally you use this notation, when your method arguments and the member variables have the same name. (to differentiate the method argument with the member variable)
Say for e.g,
void CMYClass::fun1(int sameName)
{
...
this->sameName = sameName;
}
Otherwise, it's just a matter of taste...

why C++ uses DOT to access structure members and -> to access method?

I come from a Delphi/Pascal programming world but I also "play" around with C++ or C once in a while, there is a question that bothers me the most: why does C++ use "." to access a structure member and "->" to access method? in Delphi/Pascal we use "." for any of those even properties...
Someone told me it has something to do with how C++ accesses memory, however that answer is NOT enough to help me understand.
Thank you.
Your understanding is incorrect. C++ accesses data members and member functions (the term "method" is not used by C++ programmers) the same way.
. accesses a member of an object. -> accesses a member of the object that is pointed to by a pointer-to-object. foo->bar is exactly equivalent to (*foo).bar.
That is why someone told you "it has something to do with how C++ accesses memory" - because it does.
All structure members (fields and methods) are accessed same way. But, in case of pointer to structure, there is two different syntaxes for the same purpose: (*pStruct).member and pStruct->member.
In Pascal (or Delphi):
var pointerToSomeRecord: ^SomeRecord;
pointerToSomeRecord^.field := 42;
In C++:
SomeStruct* pointerToSomeStruct;
(*pointerToSomeStruct).field = 42;
But, in C++ there is also another way:
pointerToSomeStruct->field = 42;
Most C++ programmers like the later form much more.
You are confusing them.
foo->bar() is semantically equivalent to (*foo).bar() (barring operator overload.)
-> is used when the left-hand argument is a pointer.
. is used when it is a reference or otherwise not a pointer.
It has nothing whatsoever to do with the right-hand side.
You are mistaken. C++ uses dot for member access and to call methods unless you have a pointer to the object the the -> operator applies.
The -> is functionally the same as (*obj).x()
The arrow operator is an abbreviation for accessing structure members via pointer:
struct foo {
int field;
}
struct foo* ptr = ...;
This
(*ptr).field
is essentially the same as
ptr->field
This has nothting to do with accessing member functions or data fields.

Why is is it not possible to pass a const set<Derived*> as const set<Base*> to a function?

Before this is marked as duplicate, I'm aware of this question, but in my case we are talking about const containers.
I have 2 classes:
class Base { };
class Derived : public Base { };
And a function:
void register_objects(const std::set<Base*> &objects) {}
I would like to invoke this function as:
std::set<Derived*> objs;
register_objects(objs);
The compiler does not accept this. Why not? The set is not modifiable so there is no risk of non-Derived objects being inserted into it. How can I do this in the best way?
Edit:
I understand that now the compiler works in a way that set<Base*> and set<Derived*> are totally unrelated and therefor the function signature is not found. My question now however is: why does the compiler work like this? Would there be any objections to not see const set<Derived*> as derivative of const set<Base*>
The reason the compiler doesn't accept this is that the standard tells it not to.
The reason the standard tells it not to, is that the committee did not what to introduce a rule that const MyTemplate<Derived*> is a related type to const MyTemplate<Base*> even though the non-const types are not related. And they certainly didn't want a special rule for std::set, since in general the language does not make special cases for library classes.
The reason the standards committee didn't want to make those types related, is that MyTemplate might not have the semantics of a container. Consider:
template <typename T>
struct MyTemplate {
T *ptr;
};
template<>
struct MyTemplate<Derived*> {
int a;
void foo();
};
template<>
struct MyTemplate<Base*> {
std::set<double> b;
void bar();
};
Then what does it even mean to pass a const MyTemplate<Derived*> as a const MyTemplate<Base*>? The two classes have no member functions in common, and aren't layout-compatible. You'd need a conversion operator between the two, or the compiler would have no idea what to do whether they're const or not. But the way templates are defined in the standard, the compiler has no idea what to do even without the template specializations.
std::set itself could provide a conversion operator, but that would just have to make a copy(*), which you can do yourself easily enough. If there were such a thing as a std::immutable_set, then I think it would be possible to implement that such that a std::immutable_set<Base*> could be constructed from a std::immutable_set<Derived*> just by pointing to the same pImpl. Even so, strange things would happen if you had non-virtual operators overloaded in the derived class - the base container would call the base version, so the conversion might de-order the set if it had a non-default comparator that did anything with the objects themselves instead of their addresses. So the conversion would come with heavy caveats. But anyway, there isn't an immutable_set, and const is not the same thing as immutable.
Also, suppose that Derived is related to Base by virtual or multiple inheritance. Then you can't just reinterpret the address of a Derived as the address of a Base: in most implementations the implicit conversion changes the address. It follows that you can't just batch-convert a structure containing Derived* as a structure containing Base* without copying the structure. But the C++ standard actually allows this to happen for any non-POD class, not just with multiple inheritance. And Derived is non-POD, since it has a base class. So in order to support this change to std::set, the fundamentals of inheritance and struct layout would have to be altered. It's a basic limitation of the C++ language that standard containers cannot be re-interpreted in the way you want, and I'm not aware of any tricks that could make them so without reducing efficiency or portability or both. It's frustrating, but this stuff is difficult.
Since your code is passing a set by value anyway, you could just make that copy:
std::set<Derived*> objs;
register_objects(std::set<Base*>(objs.begin(), objs.end());
[Edit: you've changed your code sample not to pass by value. My code still works, and afaik is the best you can do other than refactoring the calling code to use a std::set<Base*> in the first place.]
Writing a wrapper for std::set<Base*> that ensures all elements are Derived*, the way Java generics work, is easier than arranging for the conversion you want to be efficient. So you could do something like:
template<typename T, typename U>
struct MySetWrapper {
// Requirement: std::less is consistent. The default probably is,
// but for all we know there are specializations which aren't.
// User beware.
std::set<T> content;
void insert(U value) { content.insert(value); }
// might need a lot more methods, and for the above to return the right
// type, depending how else objs is used.
};
MySetWrapper<Base*,Derived*> objs;
// insert lots of values
register_objects(objs.content);
(*) Actually, I guess it could copy-on-write, which in the case of a const parameter used in the typical way would mean it never needs to do the copy. But copy-on-write is a bit discredited within STL implementations, and even if it wasn't I doubt the committee would want to mandate such a heavyweight implementation detail.
If your register_objects function receives an argument, it can put/expect any Base subclass in there. That's what it's signature sais.
It's a violation of the Liskov substitution principle.
This particular problem is also referred to as Covariance. In this case, where your function argument is a constant container, it could be made to work. In case the argument container is mutable, it can't work.
Take a look here first: Is array of derived same as array of base. In your case set of derived is a totally different container from set of base and since there is no implicit conversion operator is available to convert between them , compiler is giving an error.
std::set<Base*> and std::set<Derived*> are basically two different objects. Though the Base and Derived classes are linked via inheritance, at compiler template instantiation level they are two different instantiation(of set).
Firstly, It seems a bit odd that you aren't passing by reference ...
Secondly, as mentioned in the other post, you would be better off creating the passed-in set as a std::set< Base* > and then newing a Derived class in for each set member.
Your problem surely arises from the fact that the 2 types are completely different. std::set< Derived* > is in no way inherited from std::set< Base* > as far as the compiler is concerned. They are simply 2 different types of set ...
Well, as stated in the question you mention, set<Base*> and set<Derived*> are different objects. Your register_objects() function takes a set<Base*> object. So the compiler do not know about any register_objects() that takes set<Derived*>. The constness of the parameter does not change anything. Solutions stated in the quoted question seem the best things you can do. Depends on what you need to do ...
As you are aware, the two classes are quite similar once you remove the non-const operations. However, in C++ inheritance is a property of types, whereas const is a mere qualifier on top of types. That means that you can't properly state that const X derives from const Y, even when X derives from Y.
Furthermore, if X does not inherit from Y, that applies to all cv-qualified variants of X and Y as well. This extends to std::set instantiations. Since std::set<Foo> does not inherit from std::set<bar>, std::set<Foo> const does not inherit from std::set<bar> const either.
You are quite right that this is logically allowable, but it would require further language features. They are available in C# 4.0, if you're interested in seeing another language's way of doing it. See here: http://community.bartdesmet.net/blogs/bart/archive/2009/04/13/c-4-0-feature-focus-part-4-generic-co-and-contra-variance-for-delegate-and-interface-types.aspx
Didn't see it linked yet, so here's a bullet point in the C++ FAQ Lite related to this:
http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.3
I think their Bag-of-Apples != Bag-of-Fruit analogy suits the question.