I'm pretty noobish when it comes to c++, what is the better way of returning an object? I'm coming from the scripting world where Objects are always references, and am trying to achieve the same notion ... I'm basing this off of When to pass by reference and when to pass by pointer in C++?, where one user stated: "A good rule of thumb: "Use references when you can and pointers when you have to"."
// basic layer class
class Layer { private: Channel channel; // NEVER NULL };
// return object by pointer
Channel *Layer::getChannel() {
return &channel;
};
// return by reference
Channel& Layer::getChannel() {
return channel;
};
The problem with the second version is that the compiler will accept this line:
Channel channel = layer.getChannel(); // creates a copy BAD
when it should be:
Channel &channel = layer.getChannel(); // reference good
Is there any way to enforce a caller of the second option to force it to not create a new channel, or is the first option better anyways, even if it will never be NULL?
If a method or function returns an object of a class for which there is no public copy constructor, such as ostream class, it must return a reference to an object. Some methods and functions, such as the overloaded assignment operator, can return either an object or a reference to an object.
Explanation: The objects can be returned either by value or reference.
A function can also return objects either by value or by reference. When an object is returned by value from a function, a temporary object is created within the function, which holds the return value. This value is further assigned to another object in the calling function.
Syntax: object = return object_name; Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type 'Example'(i.e., class name) whose value is stored in E3.
You need to adjust the Channel
class itself so that it isn't copyable. If it is copyable, the user can copy it, and nothing you do can prevent it.
If copying is not a meaningful operation, then you can "disable" it. Simply define the copy constructor (Channel(const Channel&)
) and the assignment operator (Channel& operator=(const Channel&)
) to be private. Then any attempt at copying the class will result in a compile error.
On a side note, as others have mentioned, C++ is not the scripting languages you're familiar with. Everything is not a reference, and you're only setting yourself up for a world of pain by pretending otherwise. In C++, it is common to allocate objects on the stack, and pass objects by value, rather than passing references and pointers around.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With