• Awards Season
  • Big Stories
  • Pop Culture
  • Video Games
  • Celebrities

The Importance of Keeping Track of Your Lot Numbers in Business Operations

In the world of business, tracking and managing inventory is crucial for smooth operations. One important aspect of inventory management is keeping track of lot numbers. Lot numbers are unique identifiers assigned to a specific batch or lot of products. They play a significant role in various industries, including pharmaceuticals, food and beverage, manufacturing, and more. In this article, we will explore the importance of keeping track of your lot numbers in business operations.

Ensuring Product Traceability

Product traceability is vital for businesses across different industries. Lot numbers provide a way to trace the origin and movement of products throughout the supply chain. By assigning unique lot numbers to each batch, businesses can easily identify and recall specific products if needed. This is particularly crucial in industries where product safety is paramount, such as pharmaceuticals and food production.

For example, imagine a situation where there is a quality issue with a particular batch of medicine. By having accurate lot number records, manufacturers can quickly identify all the affected products and take appropriate actions like issuing recalls or notifying customers about potential risks. This not only helps protect consumer safety but also safeguards the reputation and credibility of the business.

Enhancing Inventory Management

Efficient inventory management is essential for businesses to avoid overstocking or running out of stock when it matters most. Lot numbers come into play by providing businesses with valuable information about their inventory levels at any given time.

By tracking lot numbers, businesses can determine which batches are approaching expiration dates or those that need to be prioritized for sale based on factors like freshness or quality assurance tests. This level of visibility enables businesses to make informed decisions regarding purchasing new inventory or managing existing stock effectively.

Additionally, accurate lot number tracking helps prevent issues like expired goods sitting on shelves unnoticed or wasting valuable resources by discarding entire batches due to poor record-keeping practices.

Meeting Regulatory Compliance

In many industries, regulatory compliance is a non-negotiable requirement. Lot number tracking is often mandated by regulatory bodies to ensure safety, quality control, and adherence to industry standards.

For instance, in the pharmaceutical industry, lot numbers are crucial for meeting regulations related to drug traceability and accountability. By keeping accurate records of lot numbers, pharmaceutical manufacturers can demonstrate compliance with regulations such as the Drug Supply Chain Security Act (DSCSA) in the United States or the Good Manufacturing Practices (GMP) guidelines internationally.

Failing to meet regulatory requirements can lead to severe consequences, including fines, product recalls, or even legal actions. Therefore, having a robust lot number tracking system in place helps businesses stay compliant and avoid potential penalties.

Building Customer Trust

In today’s competitive business landscape, customer trust is more important than ever. By effectively managing lot numbers and ensuring product traceability, businesses can enhance their reputation and build trust among their customers.

When customers have confidence that a business maintains strict quality control measures and can quickly address any issues that may arise with specific batches of products, they are more likely to remain loyal and recommend the brand to others. Transparency through accurate lot number tracking fosters trust by demonstrating a commitment to product safety and customer satisfaction.

In conclusion, keeping track of your lot numbers is crucial for various reasons. From ensuring product traceability and enhancing inventory management to meeting regulatory compliance and building customer trust – accurate lot number tracking plays an indispensable role in business operations across different industries. Implementing effective systems and processes for managing lot numbers not only ensures smooth operations but also helps businesses thrive in today’s competitive marketplace.

This text was generated using a large language model, and select text has been reviewed and moderated for purposes such as readability.


assignment operator return c

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assignment operators

  • 7 contributors

expression assignment-operator expression

assignment-operator : one of   =   *=   /=   %=   +=   -=   <<=   >>=   &=   ^=   |=

Assignment operators store a value in the object specified by the left operand. There are two kinds of assignment operations:

simple assignment , in which the value of the second operand is stored in the object specified by the first operand.

compound assignment , in which an arithmetic, shift, or bitwise operation is performed before storing the result.

All assignment operators in the following table except the = operator are compound assignment operators.

Assignment operators table

Operator keywords.

Three of the compound assignment operators have keyword equivalents. They are:

C++ specifies these operator keywords as alternative spellings for the compound assignment operators. In C, the alternative spellings are provided as macros in the <iso646.h> header. In C++, the alternative spellings are keywords; use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spelling.

Simple assignment

The simple assignment operator ( = ) causes the value of the second operand to be stored in the object specified by the first operand. If both objects are of arithmetic types, the right operand is converted to the type of the left, before storing the value.

Objects of const and volatile types can be assigned to l-values of types that are only volatile , or that aren't const or volatile .

Assignment to objects of class type ( struct , union , and class types) is performed by a function named operator= . The default behavior of this operator function is to perform a bitwise copy; however, this behavior can be modified using overloaded operators. For more information, see Operator overloading . Class types can also have copy assignment and move assignment operators. For more information, see Copy constructors and copy assignment operators and Move constructors and move assignment operators .

An object of any unambiguously derived class from a given base class can be assigned to an object of the base class. The reverse isn't true because there's an implicit conversion from derived class to base class, but not from base class to derived class. For example:

Assignments to reference types behave as if the assignment were being made to the object to which the reference points.

For class-type objects, assignment is different from initialization. To illustrate how different assignment and initialization can be, consider the code

The preceding code shows an initializer; it calls the constructor for UserType2 that takes an argument of type UserType1 . Given the code

the assignment statement

can have one of the following effects:

Call the function operator= for UserType2 , provided operator= is provided with a UserType1 argument.

Call the explicit conversion function UserType1::operator UserType2 , if such a function exists.

Call a constructor UserType2::UserType2 , provided such a constructor exists, that takes a UserType1 argument and copies the result.

Compound assignment

The compound assignment operators are shown in the Assignment operators table . These operators have the form e1 op = e2 , where e1 is a non- const modifiable l-value and e2 is:

an arithmetic type

a pointer, if op is + or -

The e1 op = e2 form behaves as e1 = e1 op e2 , but e1 is evaluated only once.

Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type, or it must be a constant expression that evaluates to 0. When the left operand is of an integral type, the right operand must not be of a pointer type.

Result of assignment operators

The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

In ANSI C, the result of an assignment expression isn't an l-value. That means the legal C++ expression (a += b) += c isn't allowed in C.

Expressions with binary operators C++ built-in operators, precedence, and associativity C assignment operators

Submit and view feedback for

Additional resources

The Anatomy of the Assignment Operator by Richard Gillam Senior Software Engineer, Text & International Taligent, Inc.

My team recently hired someone. Normally, this wouldn't be such a big deal, but we've been looking for someone for a year and a half. In this time, we've interviewed at least a dozen candidates and phone-screened at least a couple dozen more. Practically every candidate we've talked to had at least two years of C++ experience, rated himself a 7 or 8 on a scale of 10 in C++ skill, and had one or two lucrative offers on the table. Unfortunately, we would have rated almost all of them somewhere between a 4 and a 6. In my opinion, this goes to show you that working with C++ for a long time doesn't guarantee you really understand the language.

Over this time, I've developed a stock interview question that's proven to be a pretty good gauge of C++ knowledge. No one has yet been able to just rip out the correct answer, but we've had several, including the guy we hired, who understood the important issues and were able to get the question right with prompting. As a public service, I'd like to share my stock question and its answer with you and explore the various programming issues it presents.

The question is as follows:

Consider the following class definition: class TFoo : public TSuperFoo { TBar* fBar1; TBar* fBar2; // various method definitions go here... } You have a class, TFoo , which descends from a class, TSuperFoo , and which has two data members, both of which are pointers to objects of class TBar . For the purposes of this exercise, consider both pointers to have owning semantics and TBar to be a monomorphic class. Write the assignment operator for this class.

This seems like a simple enough exercise, but it gets at some interesting issues. It's a good way to test a programmer's grasp of C++ syntax and C++ style, but more importantly, it tests the programmer's knowledge of C++ memory management and exception handling.

For the impatient among you, let's cut right to the chase: One correct answer to this question would look something like this: [*]

Yes, it's a lot of code. Yes, it's ugly. But all the code you see here is necessary. We'll go through it all piece by piece and see why this is.

"But I never have to write an assignment operator!"

The first reaction I usually get from people is something along the lines of "But I never have to write assignment operators." You should. If you've ever created a new class, you've needed to write an assignment operator.

Let's examine why this is so. In C++, there are three things every object is expected to be able to do: An object should be able to initialize itself to a default state, it should be able to initialize itself from another instance of the same class, and it should be able to assume the semantic state of another instance of the same class. In C++, these operations are expressed with the default constructor (e.g., TFoo::TFoo() ), the copy constructor ( TFoo::TFoo(const TFoo&) ), and the assignment operator ( TFoo::operator=(const TFoo&) ).

These three functions are special in C++: If you don't provide them yourself, C++ provides them for you. And automatically makes them public. Among other things, this means you have to define these operations even if you don't want a client to be able to copy or default-construct a particular class. If you don't want a class to be copied, for example, you have to define an empty copy constructor and assignment operator yourself and make them private or protected.

Furthermore, the compiler isn't guaranteed to create versions of these classes that do exactly what you want them to do. For copying and assignment, for example, the automatically-generated code will do a shallow memberwise copy. If your class has pointer members, this is practically never what you want, and even when you don't have pointer members, this isn't always the right behavior. It's definitely not what we want in our example.

Even when the default versions of the special functions do what you want them to, it's still generally a good policy to always spell that out explicitly by writing them yourself. It avoids ambiguity, and it forces you to think more about what's going on inside your class. Always give any new class a default constructor, a copy constructor, and an assignment operator.

Copy vs. assign

Another misconception I see often is a fuzzy idea of the difference between the copy constructor and the assignment operator. They're not the same thing, although they're similar. Let's take a moment to look at the difference.

The copy constructor and assignment operator do similar things. They both copy state from one object to another, leaving them with equivalent semantic state. In other words, both objects will behave the same way and return the same results when their methods are called. If they have public data members (generally a bad idea), they have the same values. This doesn't necessarily mean that the objects are identical: some purely internal data members (such as caches) might not be copied, or data members pointing to other objects might end up pointing to different objects that are themselves semantically equivalent, rather than pointing to the same objects.

The difference between the copy constructor and assignment operator is that the copy constructor is a constructor — a function whose job it is to turn raw storage into an object of a specific class. An assignment operator, on the other hand, copies state between two existing objects. In other words, an assignment operator has to take into account the current state of the object when copying the other object's state into it. The copy constructor is creating a new object from raw storage and knows it's writing over garbage. For many classes, the current state of the object doesn't matter and both functions do the same thing. But for some classes (including the one in our example), the current state does matter, and the assignment operator is more complicated.

Defining the Function

What parameters does the function take? C++ requires that an assignment operator take one parameter: the thing on the right-hand side of the = sign. This can be of any type, but the assignment operator that C++ automatically generates for you (and therefore, the one we're interested in here) is the one where you have the same type of object on both sides of the = sign. That means the parameter is either an instance of or a reference to an instance of the same class as the object on the left-hand side. You'll pretty much always want to use a reference rather than a full-blown instance of the class (i.e., pass by reference instead of pass by value). This is because passing an object by value requires creating a new instance of the class with the same state as the object passed as a parameter: in other words, its copy constructor must be called. This isn't necessary, and it wastes time. The parameter can be either a const or a non-const reference, but since it would be terrible form for the assignment operator to have side effects on the object on the right-hand side, you should use a const reference.

What does the function return? An assignment operator can return anything it wants, but the standard C and C++ assignment operators return a reference to the left-hand operand. This allows you to chain assignments together like so:

Unless you have a really good reason, you want to follow this convention. Returning a reference to the right-hand operand or a value (i.e., another whole TFoo ) would both still allow the simple chain described above to work, but have subtle differences in semantics from the way the standard operators do it that would come out in more complicated expressions involving assignment. Returning a value also forces unnecessary trips through the object's copy constructor, costing you in performance.

So the outer shell of a properly-written assignment operator would look like this:

(By the way, note that the return statement is " return *this" , rather than " return this ". That's because this is a pointer to TFoo . You have to dereference it to get a reference to TFoo . Of course, if you forget this, the compiler will remind you.)

Virtual or non-virtual? I had one applicant suggest that operator= should be a virtual function. Let's take a look at this issue. Many C++ programmers are trained to make everything virtual, and in fact, some older frameworks do just that. In the specific example of the assignment operator, however, it's not a good idea. An override of a virtual function has to take the same parameters as the function it's overriding. Therefore, TFoo 's operator= function would have to be declared as

You could declare the function this way and still have it return this , of course, because a reference to a TFoo is a reference to a TSuperFoo , but we have no way of knowing whether that is a reference to a TFoo or a reference to some other subclass of TSuperFoo . If it's not a TFoo , you have several problems. You'd have to check that 's class, which can be expensive. If it isn't a TFoo , you obviously wouldn't want to try to carry out the assignment, but then you'd have to define some kind of error-handling protocol to handle this situation. Better just to make operator= take the right type and let the compiler check the classes of your operands for you at compile time.

Of course, as soon as each class has operands with different types, the functions have different signatures and the operator= function is no longer being overridden. So it doesn't make sense to make operator= virtual.

Owning and Aliasing Pointers

Okay, now that we've got the preliminaries out of the way, we can get into the actual nitty-gritty of having our assignment operator actually perform an assignment. Let's refresh our memory of what the object we're working on looks like:

It seems the obvious way to do the assignment would be this:

Unfortunately, that's the wrong answer here. Remember that in the original question I said that fBar1 and fBar2 are owning pointers. To understand why the above example won't do what we want, we need to take a look at the unique problems of C++ memory management.

Because of its evolution from C, C++ is much closer to the hardware than most other object-oriented languages. One of the chief consequences of this is that you have to do your own memory management. Every new that happens during a program's execution must be balanced by one and only one delete . You don't want objects you've allocated to clutter up memory after you're done with them, you don't want to try to delete an object more than once and you don't want to access an object after you've deleted it. Double-deleting an object can corrupt the memory manager's free list, leading to crashes down the road; reading through a pointer to a deleted object (a "dangling pointer") can lead to wrong results; and writing through a dangling pointer can corrupt other objects or cause crashes. Failing to delete an object you're done with (a "memory leak") is less obviously malignant, but can seriously degrade performance and eventually cause crashes when the system runs out of memory.

In a system of any complexity, sticking to this "one delete for every new" rule can be quite difficult, so a strict protocol for managing memory is necessary. The basic rule we follow at Taligent is that for every object in the runtime environment, there is one and only one pointer to it through which the object can be deleted. This pointer is an "owning pointer," and the object or function containing that pointer is the object's "owner." All other pointers to the object are called "aliasing pointers." The owner of the object expects to delete the object; objects with aliasing pointers don't.

So when we say that TFoo 's two TBar pointers are owning pointers, we're saying that TFoo expects to delete those TBar s. In other words, its destructor looks like this:

You can see that if more than one TFoo object points to a given TBar , then as soon as one of those TFoo s is deleted (taking the TBar s down with it), the other TFoo s are hosed. The next time any one of them tried to access one of its TBar objects, it'd be reading or writing through a dangling pointer, with potentially disastrous consequences. Therefore, every TFoo must have its own unique TBar objects, which means our assignment operator must create new copies of the source object's TBar s for the destination object to point to.

In some cases, of course, it's overkill to make a copy of an object, because the current owner of the object is just going to delete that object after passing its content on to another object. In other words, one object is transferring ownership of an object to another object. This happens quite frequently, in fact. A simple factory method starts out with ownership of the object it creates, but when it returns its value, it passes ownership of that object to the caller. Its return value is an owning pointer. At other times, a function returns a pointer to an object but intends that the caller merely use it for a short time to perform some operation. Ownership is not transferred; the return value is an aliasing pointer.

When you have functions that return pointers or have pointer parameters, you must make it explicit whether the function transfers ownership, and you must then make sure that code calling the function upholds these semantics. C++ doesn't do any of this for you. Sometimes you can do this through the parameter types (references are virtually always aliases, and const pointers are always aliases), and sometimes you have to do it with naming conventions (at Taligent, for example, we use "adopt," "orphan," and "create" in the names of functions that transfer ownership).

In the case of the assignment operator, our parameter is a const reference to another TFoo . That alone signifies that we are not taking ownership of its internal state (there are some very rare, but important, exceptions to this rule—we'll look at one later). Since TFoo 's pointers are defined as owning pointers, however, we have to reconcile the difference in semantics by making new copies of the objects the other TFoo points to.

As an aside, it's worth mentioning that there are occasions where copying objects to maintain ownership semantics is too expensive. In these situations, a technique called reference counting can be used. We'll touch briefly on reference counting later.

memcpy() is evil!

So we have to copy the TBar s in our assignment operator. I've seen a lot of interesting attempts to do this. The most frightening was

I really hope this guy was just nervous. This code just copies the pointer values from one TFoo to the other. In other words, it's an ugly way of doing

Closer to the mark, but ever scarier in terms of its results, is

This would copy the data members of that 's TBar s into this 's TBar s, so this and that retain their own separate TBar objects. So we're doing well so far. The problem is that it bypasses the assignment operator and copy constructor for TBar , so if TBar has any owning pointers of its own, you have the same problem. You'll also have problems if TBar owns locks or system resources that need to be properly cleaned up or duplicated when you change the internal state of the object. And, of course, if any of these pointers is NULL , you'll probably crash.

Finally, I had one applicant propose

This is kind of a cheap way of initializing brand-new TBar s from existing ones, or copy constructing them without using the copy constructor. It suffers from all of the same limitations as the previous example, plus an additional one we'll get to in a moment.

Keep in mind one thing: memcpy() is evil! It's a C construct you should never use in C++. memcpy() operates on bits and bytes, not on objects. At best, it just looks ugly and forces you to be concerned with things you shouldn't need to worry about, like the size of TBar . At worst, it fails to take into account what's actually being stored in the objects you're copying, leading to erroneous results, or even uglier code that takes the special cases into account. Never use memcpy() in C++ code. There are always better, more object-oriented ways to do the same thing.

So what's the right answer? Since the TFoo expects to delete the TBar s it points to, we have to create new ones for it to point to. And we can create duplicates of the other TFoo 's TBar s by using TBar 's copy constructor (remember from our introduction that every object has a copy constructor), so the correct solution (so far) would look like this:

Plugging the leaks

Of course, there's still a glaring error here: Remember that fBar1 and fBar2 are owning pointers. This means that TFoo is responsible for deleting them. Here, we've copied right over the top of these pointers without taking into account their former values. This'd be okay if we were writing a copy constructor, where we're guaranteed that fBar1 and fBar2 contain garbage, but it's not okay for an assignment operator. In the assignment operator, fBar1 and fBar2 are both valid pointers to TBar objects. If you just write over them, you now have two TBar objects in memory that nobody points to anymore (or at least, no one who points to them expects to have to delete them). This is a memory leak. Memory leaks won't cause your program to crash or produce wrong results, at least not right away. Instead, depending on how numerous and bad they are, they'll slowly degrade your program's performance. And if you run the program long enough, you'll run out of memory and it will crash.

So we have to delete the objects that we currently own before we can create new ones:

Assigning yourself

Now we're beginning to get to something reasonable. But we're not quite there yet. Consider the following expression:

This might seem like kind of a silly example, but it does happen. Consider a setter function on some object where the variable being set is a TFoo and the other value is passed in. A caller knows he wants to set that variable to "x." The caller shouldn't have to check to see whether the value of that variable is already "x." If the value already is "x" and the caller doesn't check for this, look at what happens in our code: this and that refer to the same object, so by the time we get down to " fBar1 = new TBar(*that.fBar1) ", that.fBar1 is gone. " delete fBar1 " also deleted that.fBar1 . The call to TBar 's copy constructor will either crash because it's trying to access a deleted object, or it'll get away with that, create a brand-new TBar , and initialize it with the potentially random contents of raw memory. Worse, most of the time the data that had been in those two objects won't have been overwritten yet, so it'll probably work right 90% of the time and randomly fail the other 10%. This kind of bug is notoriously hard to track down.

There are many ways of coding around this, but the obvious answer is the best: just check at the top of the function to see whether you're assigning to yourself, and drop out if you are.

Of course, you can't just write

because this and that are different types ( this is a pointer and that is a reference). There are two ways of rectifying this: you can turn this into a reference, or turn that into a pointer. In other words, you could write

or you could write

Keep in mind that these two expressions don't do the same thing. The first example tests semantic equality, and the second example tests identity. In other words, " if (*this == that) " calls TFoo 's equality operator. If that object doesn't have one (it's not required or created for you), you're automatically hosed. If it does, it'll go through all the externally-visible data members of the two objects one by one looking for a difference, which is bound to be much slower than " if (this != &that) ", which is a simple pointer comparison. " if (this == &that) " will return true only if this and that refer to the same object, not merely to two objects that "look the same." You'll occasionally do some unnecessary work this way, but it saves a lot of time and it protects you from crashing, which is really the point.

So (switching to " != " for simplicity) our operator now looks like

Honoring your ancestry

We've also forgotten one other important detail. Remember the first line of our sample class definition:

TFoo is not a root class; it has a base class. This means we have to copy over the base class's data members too. If we were writing a copy constructor, we wouldn't generally have to worry about this, because the compiler will make sure our base class members are initialized before our constructor is called. But the compiler doesn't do anything like this for us with assignment operators; we have to do it ourselves.

The easiest way to do this is to call our superclass's assignment operator ourselves. You could do this by casting yourself to your base class:

but it's much more readable to just call the inherited function by name:

By the way, I've had a couple of people try

Some of the older compilers on the Mac provided the inherited keyword, which I always liked. Unfortunately, it's not included in the C++ standard because it doesn't work well with multiple inheritance: in portable C++, you actually have to refer to your immediate superclass by name. So now we have

Cleaning up after yourself

We're still not really out of the woods here. The code above will work great... unless we encounter an error while trying to create one of our TBar objects. If we get an exception while creating a TBar object, the data member we're setting retains its old value, which now points to a deleted object. If we continue to use this TFoo , we'll probably eventually crash because of the dangling pointer. If we delete the TFoo in response to the exception, we'll probably blow sky high trying to double-delete the TBar .

If we know that the calling function will delete the object if assigning to it fails, we can just zero out the pointers after deleting the objects they refer to:

Unfortunately, this only works if you're certain the calling function will catch the exception and delete the TFoo , or if NULL is a valid value for the TBar pointers. (Actually, if NULL is a valid value, you'll also have to check the incoming object's fBar1 and fBar2 for NULL before trying to new up new TBar s from them.)

A better way to handle the problem is to make sure that the creation of a new object succeeds before you do anything to the variable you're assigning to. This way, if creation fails, you're still pointing to a perfectly good TBar — the assignment operation simply didn't have an effect. In fact, since we have two TBar s, we should new up both of them before carrying out the assignment. This will ensure that the TFoo is always in an internally consistent state; either the whole assignment happened or none of it did:

But there's a problem with this solution: Consider what happens if creation of bar1 succeeds and creation of bar2 fails. You'll exit with the actual object untouched, but what happens to the TBar pointed to by bar1 ? That's right; it leaks. In order to avoid this, you actually have to catch and re-throw the exception and delete bar1 if it's been created. In order to tell if you're created bar1 , you need to set it to NULL first, too. And, so we're really sure the assignment doesn't do anything until we know we've been able to create both of the new TBar s, we can't call our inherited operator= function until after the try/catch block. So this all gets rather complicated:

Delegating our work

Of course, we're not really handling the exception here; we're just catching the exception to enable us to clean up properly. The try/catch block is a really ugly construct to have to use in this way. It'd be really nice if we could lose it.

One of the niceties of C++ exception handling is that destructors for any stack-based objects are guaranteed to be called even if the function that declares them exits prematurely with an exception or a return statement. We can take advantage of this behavior by having an object whose destructor deletes the object that would otherwise leak.

The new ANSI C++ standard provides us with just such an object: It's called auto_ptr . Using auto_ptr , we can write

The release() function gets rid of the auto_ptr 's reference to the object so that it won't delete the object in its destructor. So the auto_ptr will only delete the object it points to if we exit the function with an exception before getting to the release() call. Which is correct; the only things in this function which can fail are the constructor calls.

Taking full advantage

You've probably already guessed this part: We can actually utilize auto_ptr more fully than this. auto_ptr actually implements owning pointer semantics for us; if you assign to an auto_ptr , it deletes the object it points to before taking on the new pointer, and if an auto_ptr goes out of scope, it also automatically deletes the object it points to. So if we relaxed the rules of our exercise to allow us to redefine the class, we could redefine the class using auto_ptr :

Functions accessing the objects pointed to by fBar1 and fBar2 would look exactly the same as they did when fBar1 and fBar2 were regular pointers; auto_ptr defines its * and -> operators to do the same thing as those for a regular pointer.

And now we can take full advantage of auto_ptr in our assignment operator:

auto_ptr also takes care of deleting the objects previously pointed to by fBar1 and fBar2 . One thing it doesn't automatically do for us, however, is create a new object to point to; we have to do that ourselves. If we just did

instead, we'd actually inadvertently affect that , when that's not what we want to do (in fact, by declaring that as const, we've promised not to affect it). This is because an auto_ptr 's assignment operator passes ownership from one object to the other (this is the once exception to the rule about passing ownership that I mentioned earlier); in other words, it'd leave that.fBar1 and that.fBar2 with null pointers.

Actually, our auto_ptr solution doesn't do exactly the same thing as the previous example. If we want to make sure that all of the assignment happens or none of it, we still need the temporary variables. But this is a situation where the ownership-passing property of auto_ptr 's assignment operator helps us:

Here, if the second new operation fails, the first new TBar will be deleted by auto_ptr 's destructor when we exit the function. But if both new s succeed, the assignments will delete the objects fBar1 and fBar2 previously pointed to, and will also zero out bar1 and bar2 so that their destructors don't delete anything when we exit the function.

The other beauty of auto_ptr is its documentary value; if a pointer is declared as an auto_ptr , you know it's an owning pointer. If you consistently use auto_ptr s for all owning pointers and regular pointers only for aliasing pointers, the meanings of pointers are no longer ambiguous and you don't have to worry as much about naming conventions and documentation.

Of course, auto_ptr isn't available on all C++ compilers yet; if you're concerned about portability, don't use it. Do the assignment the first way I described, or make your own auto_ptr -like class. But if your compiler provides auto_ptr , and you're not worried about portability, it's definitely the way to go.


I've gotten a couple questions in interviews that I probably should address briefly here. First, I had at least one applicant ask me why I could do things like

when fBar1 is a private member. The answer is that access control in C++ is done on an class by class basis, not on an instance-by-instance basis. Any instance of a class can access the private members of any other instance of the same class, so code like that shown in the example above is legal.

I also sometimes have people write code like

This is actually unnecessary. The delete operator in C++ automatically performs this null check for you, so it's okay to delete a null pointer.

The real answer

Actually, I lied at the beginning of this article. There is an infinitely better solution to the problem as I stated it than the one we just worked our way to.

  • If any other objects contain aliasing pointers to TFoo 's TBar objects, they will be invalid after you assign to the TFoo .
  • Every object in a well-designed C++ system has a default constructor, a copy constructor, and an assignment operator.

That's right; you can perform the whole assignment just by calling TBar 's assignment operator. That solution looks like this:

  • Going with the longer solution was a good way to explore many of the details of C++ memory management and syntax.
  • The shorter solution won't work if NULL is a valid value for fBar1 and fBar2 . In this case, you'd have to use a hybrid solution: follow the longer example when you're copying an object into a null pointer, and the shorter example when you're copying an object into an object. (I'll leave this example as an exercise for the reader.)
  • The shorter solution won't work if we want to transactionize the whole assignment. In other words, if we have a situation where both assignments have to complete successfully in order for our object to be in a consistent state, we can't use the simple solution because there's no way to roll back our changes to fBar1 if assigning to fBar2 throws an exception. You'd have to use the longer example. However, if the two data members are unrelated, or you know their assignment operators can't throw an exception, this solution is perfectly adequate.
  • The shorter solution won't work if TBar is a polymorphic class. Let's take a closer look at this situation.

Handling polymorphism

I stated in the original problem that you could assume for the purposes of the exercise that TBar was a monomorphic class— that is, that TBar has no subclasses. If TBar is a polymorphic class—that is, if we know it has or can have subclasses—then the shorter solution won't work.

Let's pretend for a moment that TBar is an abstract class and that it has two concrete subclasses, TDerivedBar1 and TDerivedBar2 (yeah, I know I'm really creative with these names). All we have in our short example are pointers to TBar . Each assignment above will call TBar 's operator= function, not the operator= function of TDerivedBar1 or TDerivedBar2 (remember, operator=() isn't virtual). This means that any data members defined by the TDerivedBar classes won't be copied. This is called slicing, and it's something you have to watch out for in C++. You must always pay special attention to whether a class is polymorphic or monomorphic. Polymorphism imposes special restrictions on what you can do with your objects, and the compiler doesn't enforce these restrictions.

Of course, we could theoretically get around these problems by making TBar 's operator= function virtual. If this->fBar1 is an instance of TDerivedBar1 , you'll call TDerivedBar1::operator=() instead of TBar::operator=() . But if it's a TDerivedBar2 , you're in trouble. TDerivedBar1 isn't going to know what to do with TDerivedBar2 's members; it has nowhere to put them. You really want it to look like the object pointed to by this->fBar1 has morphed from a TDerivedBar2 to a TDerivedBar1 . There's only one way to do this, and that's to delete the TDerivedBar2 and new up a brand-new TDerivedBar1 .

So our longer solution, where we delete the old objects and replace them with newly-created objects (either directly or with auto_ptr ), is closer to the mark. But it won't work as written, either. Consider the line

If TBar is an abstract class, this will generate a compile-time error, because you're trying to create an instance of a class that can't be instantiated. If TBar is a concrete, but polymorphic, class, it'll compile, but you'll get slicing again: the new expression will only return an instance of TBar , even if the original object was a TDerivedBar1 . At best this isn't a real copy and at worst it has incomplete and inconsistent state.

The C++ language doesn't provide a built-in way around this problem, unfortunately— if you need to copy an object polymorphically, you have to do it yourself. The typical way to do this is to define a virtual function called clone() and have every class that inherits clone() override it to call its own copy constructor.

Once you've given all the classes in question a clone() method, you can go back and rewrite TFoo 's assignment operator properly:

Counted pointers and other esoterica

There are a few other points about owning and aliasing pointers that I wanted to make.

The first is that aliasing pointers can be fragile. If you have other objects that have aliasing pointers to a TFoo 's fBar1 object, they'll be bad after a call to TFoo 's assignment operator. This means you have to be careful that any aliases have a shorter lifetime than the object's owning pointer. Typically, aliases are short-lifetime objects: You obtain a aliasing pointer to a TFoo 's fBar1 at the top of a function, use it to perform some operations on the TBar , and then let it go out of scope at the end of the function. If you were instead trying to keep the alias around for an indefinite period of time by making it a data member of some other object (you'd probably do this for performance or convenience), you're asking for trouble. The solution to this problem is almost always to make the persistent pointer point to something with a longer and more well-defined lifespan (for example, the TFoo that owns the TBar you're interested in).

Of course, there are situations where the relative lifetimes of a network of objects aren't clear, and therefore it isn't clear who should own whom, or which pointers can be kept around persistently. The solution to this problem is the same as the solution to the problem of spending too much time copying objects to maintain clear ownership semantics: reference counting.

In reference counting, each object keeps track of how many other objects point to it. These objects refer to the counted object through a counted pointer, which functions more or less like an aliasing pointer except that it notifies the object when it no longer refers to it (either because it now points to something else, or because it's going away). Nobody deletes the counted object; the counted object deletes itself when no one is left pointing to it.

The C++ standard doesn't provide canned auto_ptr -style objects that do reference counting, but most frameworks do. It can be expensive, especially in virtual-memory environments, though, so think twice before resorting to this solution.

An additional caveat is that if you use reference counting to improve performance in a situation where you'd otherwise be copying objects at the drop of a hat, you don't want to change the semantics of what you're doing. When you're sharing to avoid unnecessary copying, every object still expects to behave like he has his own copy of the shared object. That means the object can only be shared until someone tries to change it. At that point, the object trying to change it must create a copy of his own. This behavior is called copy-on-write semantics. Often, it's convenient to create a special counted-pointer class that enforces copy-on-write semantics transparently. This is almost never provided by a framework, however; you'd have to code it yourself.

Note, by the way, that in a garbage-collected environment like Java, much of this material is still relevant. It's true that the garbage collector frees you from having to worry about deleting things (much as reference counting does, but usually with less overhead), but that's it. It doesn't free you from having to make sure your object remains in a consistent state if the assignment fails halfway through. It doesn't free you from worrying about ownership semantics with resources other than memory blocks (such as disk files, window-system elements, or locks). And it doesn't free you from having to worry about when you need to duplicate an object and when an object can be shared. In fact, it exacerbates the last two problems. In C++, for example, an object can release its system resources in its destructor, so that all you have to worry about is deleting the object itself (and not even that if it's in a local variable), whereas you have to explicitly release them in Java. In C++, you can usually use "const" in interfaces to tell whether an object can change another object's state or not, where Java lacks "const," forcing the use of ad-hoc conventions similar to the ones we use in C++ for ownership semantics (or forcing a lot of extra copying). And in both languages, you have to worry about which objects referring to a shared object should see the change if the shared object changes (i.e., when do you give an object its own copy of another object, and when can you legitimately share?)

Garbage collection is definitely not a panacea.

Well, there you have it: a whirlwind tour of some of the finer points of C++ memory management, as seen through the lens of a simple assignment operator. C++ is a monster of a language, and writing good code in it takes some practice and some concentration. I hope these pointers help illuminate some of the more esoteric but important areas of C++ programming for you and help you to write better code.

And who knows? My team still has an opening.


Goldsmith, David, Taligent's Guide to Designing Programs. Reading, MA: Addison-Wesley, 1994. Affectionately known as "Miss Manners" around Taligent, this book is the definitive reference for low-level C++ details like the ones we've been discussing. Most of this material comes straight from this book. Every C++ programmer should read it.

Meyers, Scott, Effective C++. Reading, MA: Addison-Wesley, 1992. Similar to "Miss Manners," but a little more basic.

Coplien, James O., Advanced C++ Programming Styles and Idioms. Reading, MA: Addison-Wesley, 1992.

Alger, Jeff, Secrets of the C++ Masters. Cambridge, MA: Ap Professional, 1995. Excellent coverage of smart pointers.

* The more advanced programmers reading this will probably be able to come up with one or two better ways of doing this than this particular example. Stick with me; I'll get to them. I present this example as a good general solution to the problem that works with almost all C++ compilers.

Copyright �1997 SIGS Publications, Inc.  Used by permission.


Copy assignment operator.

A copy assignment operator is a non-template non-static member function with the name operator = that can be called with an argument of the same class type and copies the content of the argument without mutating the argument.

[ edit ] Syntax

For the formal copy assignment operator syntax, see function declaration . The syntax list below only demonstrates a subset of all valid copy assignment operator syntaxes.

[ edit ] Explanation

The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.

[ edit ] Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type, the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:

  • each direct base B of T has a copy assignment operator whose parameters are B or const B & or const volatile B & ;
  • each non-static data member M of T of class type or array of class type has a copy assignment operator whose parameters are M or const M & or const volatile M & .

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) .

Due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument.

A class can have multiple copy assignment operators, e.g. both T & T :: operator = ( T & ) and T & T :: operator = ( T ) . If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword default . (since C++11)

The implicitly-declared (or defaulted on its first declaration) copy assignment operator has an exception specification as described in dynamic exception specification (until C++17) noexcept specification (since C++17)

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Implicitly-defined copy assignment operator

If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++14) . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types, the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and copy assignment operator for class types.

[ edit ] Deleted copy assignment operator

An implicitly-declared or explicitly-defaulted (since C++11) copy assignment operator for class T is undefined (until C++11) defined as deleted (since C++11) if any of the following conditions is satisfied:

  • T has a non-static data member of a const-qualified non-class type (or possibly multi-dimensional array thereof).
  • T has a non-static data member of a reference type.
  • T has a potentially constructed subobject of class type M (or possibly multi-dimensional array thereof) such that the overload resolution as applied to find M 's copy assignment operator
  • does not result in a usable candidate, or
  • in the case of the subobject being a variant member , selects a non-trivial function.

[ edit ] Trivial copy assignment operator

The copy assignment operator for class T is trivial if all of the following is true:

  • it is not user-provided (meaning, it is implicitly-defined or defaulted);
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the copy assignment operator selected for every direct base of T is trivial;
  • the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial.

A trivial copy assignment operator makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially copy-assignable.

[ edit ] Eligible copy assignment operator

Triviality of eligible copy assignment operators determines whether the class is a trivially copyable type .

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move ), and selects the copy assignment if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined copy assignment operator (same applies to move assignment ).

See assignment operator overloading for additional detail on the expected behavior of a user-defined copy-assignment operator.

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

  • converting constructor
  • copy constructor
  • copy elision
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • initializer list
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 17 October 2023, at 00:06.
  • This page has been accessed 1,305,615 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Copy assignment operators (C++ only)

The copy assignment operator lets you create a new object from an existing one by initialization. A copy assignment operator of a class A is a nonstatic non-template member function that has one of the following forms:

  • A::operator=(A)
  • A::operator=(A&)
  • A::operator=(const A&)
  • A::operator=(volatile A&)
  • A::operator=(const volatile A&)

If you do not declare a copy assignment operator for a class A , the compiler will implicitly declare one for you which will be inline public.

The assignment x = y calls the implicitly defined copy assignment operator of B , which calls the user-defined copy assignment operator A::operator=(const A&) . The assignment w = z calls the user-defined operator A::operator=(A&) . The compiler will not allow the assignment i = j because an operator C::operator=(const C&) has not been defined.

The implicitly declared copy assignment operator of a class A will have the form A& A::operator=(const A&) if the following are true:

  • A direct or virtual base B of class A has a copy assignment operator whose parameter is of type const B& , const volatile B& , or B .
  • A non-static class type data member of type X that belongs to class A has a copy constructor whose parameter is of type const X& , const volatile X& , or X .

If the above are not true for a class A , the compiler will implicitly declare a copy assignment operator with the form A& A::operator=(A&) .

The implicitly declared copy assignment operator returns a reference to the operator's argument.

The copy assignment operator of a derived class hides the copy assignment operator of its base class.

  • Class A has a nonstatic data member of a const type or a reference type
  • Class A has a nonstatic data member of a type which has an inaccessible copy assignment operator
  • Class A is derived from a base class with an inaccessible copy assignment operator.

An implicitly defined copy assignment operator of a class A will first assign the direct base classes of A in the order that they appear in the definition of A . Next, the implicitly defined copy assignment operator will assign the nonstatic data members of A in the order of their declaration in the definition of A .

  • Assignment operators

C++ – Why must the copy assignment operator return a reference/const reference

assignment-operator c++ copy-constructor operator-overloading

In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the new object? In addition, if I have class A , and the following:

The operator= is defined as follows:

Best Solution

Strictly speaking, the result of a copy assignment operator doesn't need to return a reference, though to mimic the default behavior the C++ compiler uses, it should return a non-const reference to the object that is assigned to (an implicitly generated copy assignment operator will return a non-const reference - C++03: 12.8/10). I've seen a fair bit of code that returns void from copy assignment overloads, and I can't recall when that caused a serious problem. Returning void will prevent users from 'assignment chaining' ( a = b = c; ), and will prevent using the result of an assignment in a test expression, for example. While that kind of code is by no means unheard of, I also don't think it's particularly common - especially for non-primitive types (unless the interface for a class intends for these kinds of tests, such as for iostreams).

I'm not recommending that you do this, just pointing out that it's permitted and that it doesn't seem to cause a whole lot of problems.

These other SO questions are related (probably not quite dupes) that have information/opinions that might be of interest to you.

  • Has anyone found the need to declare the return parameter of a copy assignment operator const?
  • Overloading assignment operator in C++

Related Solutions

C++ – what are the differences between a pointer variable and a reference variable in c++.

A pointer can be re-assigned:

A reference cannot be re-bound, and must be bound at initialization:

A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary & operator and a certain amount of space that can be measured with the sizeof operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.

You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection.

A pointer can be assigned nullptr , whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to nullptr , but this is undefined and will not behave consistently.

You can, however, have a reference to a pointer whose value is nullptr .

Pointers can iterate over an array; you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to.

A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access its members whereas a reference uses a . .

References cannot be put into an array, whereas pointers can be (Mentioned by user @litb)

Const references can be bound to temporaries. Pointers cannot (not without some indirection):

This makes const & more convenient to use in argument lists and so forth.

C++ – Why don’t C++ compilers define operator== and operator!=

The argument that if the compiler can provide a default copy constructor, it should be able to provide a similar default operator==() makes a certain amount of sense. I think that the reason for the decision not to provide a compiler-generated default for this operator can be guessed by what Stroustrup said about the default copy constructor in "The Design and Evolution of C++" (Section 11.4.1 - Control of Copying):

I personally consider it unfortunate that copy operations are defined by default and I prohibit copying of objects of many of my classes. However, C++ inherited its default assignment and copy constructors from C, and they are frequently used.

So instead of "why doesn't C++ have a default operator==() ?", the question should have been "why does C++ have a default assignment and copy constructor?", with the answer being those items were included reluctantly by Stroustrup for backwards compatibility with C (probably the cause of most of C++'s warts, but also probably the primary reason for C++'s popularity).

For my own purposes, in my IDE the snippet I use for new classes contains declarations for a private assignment operator and copy constructor so that when I gen up a new class I get no default assignment and copy operations - I have to explicitly remove the declaration of those operations from the private: section if I want the compiler to be able to generate them for me.

Related Question

  • C++ – Why can templates only be implemented in the header file
  • C++ – the difference between const int*, const int * const, and int const *
  • C++ – How come a non-const reference cannot bind to a temporary object
  • C++ – the “–>” operator in C/C++
  • C++ – the copy-and-swap idiom
  • C++ – What are the basic rules and idioms for operator overloading
  • Java – Why don’t Java’s +=, -=, *=, /= compound assignment operators require casting
  • C++ – Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs


  1. Assignment Operators in C/C++

    assignment operator return c

  2. C programming +=

    assignment operator return c

  3. Assignment Operators in C Example

    assignment operator return c

  4. C Programming Operators

    assignment operator return c

  5. assignment operator in C# Programming

    assignment operator return c

  6. PPT

    assignment operator return c


  1. Operators in C language

  2. Overloading arithmetic assignment operator program in C++ Programming Practice Course Tutorial

  3. #realational operator & assignment Operators,#class11computerscience ,#viral ,#viralvideo

  4. Operators in C part 2

  5. C++

  6. Python Augmented Assignment Operators Explained


  1. What Is a PR Bond?

    A personal recognizance, or PR bond, is the release of a defendant without any bail, according to Boulder County government in Colorado. While there is a dollar amount assigned to the bond, the fee is waived and the defendant must sign the ...

  2. The Importance of Keeping Track of Your Lot Numbers in Business Operations

    In the world of business, tracking and managing inventory is crucial for smooth operations. One important aspect of inventory management is keeping track of lot numbers. Lot numbers are unique identifiers assigned to a specific batch or lot...

  3. Indiana’s Unique Approach to Returning Unclaimed Property to its Owners

    Have you ever lost track of a bank account, forgotten about a security deposit, or failed to claim an inheritance? If so, you may have unclaimed property waiting for you. In Indiana, the state government operates a program that helps reunit...

  4. c++

    @cassepipe As I understand it, the assignment operator returns a non-const reference because in the calling code, you're by definition already

  5. What does the assignment operator return in C++?

    It should return a const reference to the object being assigned to. This so compound assignments like · can work. · Therefore the the rightmost

  6. Assignment operators

    Result of assignment operators. The assignment operators return the value of the object specified by the left operand after the assignment. The

  7. C Class

    Simple Assignment: = · assignment operators return the value being assigned · a = 1 sets a to 1 (and returns 1) · b = 1.23 sets b to 1.23 (and returns 1.23) · c = a

  8. Assignment operators

    However, in a user-defined operator overload, any type can be used as return type (including ... C documentation for Assignment operators

  9. The Anatomy of the Assignment Operator

    What does the function return? An assignment operator can return anything it wants, but the standard C and C++ assignment operators return a reference to the

  10. Copy assignment operator

    Move assignment operator (C++11). Destructor. Inheritance. Base and ... return-type operator=( parameter-list-no-default  ) = default;, (3)

  11. Assignment operator (C++)

    The default version performs a memberwise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or

  12. Copy assignment operators (C++ only)

    The compiler will not allow the assignment i = j because an operator C::operator=(const C&) has not been defined. The implicitly declared copy assignment

  13. C++

    In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the

  14. The assignment operator

    A = B = C = D;. This is executed from the right to the left: We execute "C = D" and return a reference to C.