Kalec
Kalec

Reputation: 2881

About overloading "=" and if I can avoid it

I have a Binary Search Tree, I use template to add any class object to it.

I have a search function that returns said class object or NULL

Do I need to overload "=" to return this object ? I was hoping if I return object it would know to check: If same type replace values stored in LHS with values stored in RHS and if NULL mark first object as NULL.

Is my mistake maybe somewhere else (all I return is either full object or NULL, nothing else) or do I actually have to overload it ?

I have limited time (very) so how can I do this if needed ? and is it a fast process or will it involve a lot of modifications.

Sorry for lack of code but I can't think of any that would be relevant.

EDIT I also use a lot of NULL so can I return NULL into an object ? Example:

class Matrix {
   private:
     int col;
     int line;
     int value;
}

Matrix mat; mat = NULL;

Some code:

template <typename Type>
Type BST<Type>::search(int key) {
    if (this->root == NULL)
        return NULL;
    else
        return root->search(key);

Here Type is Matrix. Can I return NULL or go further with search and return Type, which again is Matrix?

Note: This is for homework purposes, leaking memory is my last concern. Simplicity and speed is by far my first problem

Upvotes: 0

Views: 110

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254661

To return an object from a function, it must have an accessible copy or move constructor. It does not need an assignment operator; that's only needed for assignment. Of course, you will need that if you're assigning the function result to a previously declared variable.

Note that a public copy constructor and copy-assignment operator will be generated automatically, if you don't delcare them yourself.

However, if your object is managing resources that are freed in its destructor, then you'll need to consider the Rule of Three. You should either implement or delete the copy constructor and assignment operator; otherwise, it's very easy to accidentally introduce memory leaks, and worse, to have two objects both trying to free the same resources.

To answer the new question, you can't return a null pointer in place of an object. You could either return a pointer (either a raw pointer to something contained in the tree, or a smart pointer like std::unique_ptr<Type> to a newly allocated copy, to make memory leaks less likely), or a nullable object type such as boost::optional<Type>.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

No, you cannot assign NULL to an object.

Matrix mat; mat = NULL;

Is illegal in your case. If you want to be able to have NULL, you can use pointers instead (raw or smart).

Upvotes: 2

Related Questions