user834850
user834850

Reputation:

What means that kind of declaration in c++?

CSmth & CSmth::operator = (const CSmth & rhs)
{
    return *this;
}

Upvotes: 0

Views: 121

Answers (3)

Greg Howell
Greg Howell

Reputation: 1945

operator= is the 'Copy Assignent Operator'. Any time you see

A a, b;
a = b;

What really happens in the simplest case is this:

A & A::operator=(A const &rhs);

a.operator=(b);

To break this down:

  • operator= is a member of A. The operator has access to all of the variables in the object the operator is being called upon, aka the left hand side variable.
  • operator= takes as a parameter a reference to another A, the right hand side of the assignment. Good coding practice states you should only access the public interface of rhs from within this function. **
  • operator= returns a reference to an A, by convention this is to the left hand side of the assignment, or *this. This return is important because it allows you to chain assignments like so: A a, b, c, d; a = b = c= d;

A call to operator= should "copy" the state of the right hand side object into the left hand side object. Because it looks like we're doing an assignment, this is called the "Copy Assignment Operator"

** Denoting a variable as 'private' makes that variable private to that class, not to that object. You can fully access the private implementation of the passed object from within a copy assignment operator but this isn't a good idea as it violates object encapsulation, among other things.

Upvotes: 0

sergio
sergio

Reputation: 69047

This is an assignment operator, so you can write:

CSmth a;
CSmth b;
a = b;

The actual implementation does nothing useful, apart from returning a reference to the first addendum. A more standard implementation would be:

CSmth & CSmth::operator = (const CSmth & rhs) {
    if (this != &rhs) // protect against invalid self-assignment
    {
        do_whatever_required_to_copy_rsh_on_to_this;
    }
    return *this;
}

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122468

It's an assignment operator, used to assign values from the rhs object to the current (this). It hasn't been implemented, however.

Upvotes: 1

Related Questions