• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Overloading assignment operator in a class template that can cast to another template type

The commented assignment operator overloading is my attempt to do what I want, I thought it might provide a better description than the one above the snippet.

I want to be able to do the following:

Where a then would be casted to an int and given the value of b , but still be an instance of class Number .

Is it possible? Can you help me out here?

Thanks in advance.

mkroman's user avatar

2 Answers 2

You should do this:

That is, use T2 in the parameter type, not in the return type!

I would rather use different letter for template parameter:

I think, it is better to use explicit cast, if you want to use class type as template argument and whose constructor has been declared explicit :

By the way, the other operator= should be implemented as:

Nawaz's user avatar

You have some of the T s in the wrong place. It should be

This will let you do

and it will print 6 , a behaviour similar to that of the int and float types you are imitating.

Seth Carnegie's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged c++ templates casting or ask your own question .

Hot Network Questions

overload assignment operator in template

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

    Overloaded assignment operator for class template objects

overload assignment operator in template

C++ Tutorial

Assignment Operators Overloading in C++

You can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor.

Following example explains how an assignment operator can be overloaded.

When the above code is compiled and executed, it produces the following result −

14.15 — Overloading the assignment operator

Related Articles

C++ Assignment Operator Overloading

Prerequisite: Operator Overloading

The assignment operator,”=”, is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types.

We can’t directly use the Assignment Operator on objects. The simple explanation for this is that the Assignment Operator is predefined to operate only on built-in Data types. As the class and objects are user-defined data types, so the compiler generates an error.

here, a and b are of type integer, which is a built-in data type. Assignment Operator can be used directly on built-in data types.

c1 and c2 are variables of type “class C”. Here compiler will generate an error as we are trying to use an Assignment Operator on user-defined data types.

The above example can be done by implementing methods or functions inside the class, but we choose operator overloading instead. The reason for this is, operator overloading gives the functionality to use the operator directly which makes code easy to understand, and even code size decreases because of it. Also, operator overloading does not affect the normal working of the operator but provides extra functionality to it.

Now, if the user wants to use the assignment operator “=” to assign the value of the class variable to another class variable then the user has to redefine the meaning of the assignment operator “=”.  Redefining the meaning of operators really does not change their original meaning, instead, they have been given additional meaning along with their existing ones.

Please Login to comment...

New Course Launch!

Improve your Coding Skills with Practice

Start your coding journey now.

cppreference.com

Move assignment operator.

A move assignment operator of class T is a non-template non-static member function with the name operator = that takes exactly one parameter of type T && , const T && , volatile T && , or const volatile T && .

[ edit ] Syntax

[ edit ] explanation.

The move assignment operator is called whenever it is selected by overload resolution , e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.

Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, move-assigning from a std::string or from a std::vector may result in the argument being left empty. This is not, however, a guarantee. A move assignment is less, not more restrictively defined than ordinary assignment; where ordinary assignment must leave two copies of data at completion, move assignment is required to leave only one.

[ edit ] Implicitly-declared move assignment operator

If no user-defined move assignment operators are provided for a class type ( struct , class , or union ), and all of the following is true:

then the compiler will declare a move assignment operator as an inline public member of its class with the signature T & T :: operator = ( T && ) .

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

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

Because some assignment operator (move or copy) 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 ] Deleted implicitly-declared move assignment operator

The implicitly-declared or defaulted move assignment operator for class T is defined as deleted if any of the following is true:

A deleted implicitly-declared move assignment operator is ignored by overload resolution .

[ edit ] Trivial move assignment operator

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

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

[ edit ] Eligible move assignment operator

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

[ edit ] Implicitly-defined move assignment operator

If the implicitly-declared move 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 move assignment operator copies the object representation (as by std::memmove ).

For non-union class types ( class and struct ), the move assignment operator performs full member-wise move assignment of the object's direct bases and immediate non-static members, in their declaration order, using built-in assignment for the scalars, memberwise move-assignment for arrays, and move assignment operator for class types (called non-virtually).

As with copy assignment, 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 move assignment operator:

[ 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 move assignment operator (same applies to copy assignment ).

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

[ edit ] Example

[ edit ] defect reports.

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

[ edit ] See also

Powered by MediaWiki

Title: Efficient Expression Templates for Operator Overloading-based Automatic Differentiation.

You are accessing a document from the Department of Energy's (DOE) OSTI.GOV . This site is a product of DOE's Office of Scientific and Technical Information (OSTI) and is provided as a public service. Visit OSTI to utilize additional information resources in energy science and technology.

Abstract not provided.

Citation Formats

Similar records in OSTI.GOV collections:

C++ Tutorial Operator Overloading II self assignment - 2020

cplusplus_icon.png

Why do we need to protect against the self assignment when we do overloading assignment operator?

But before we dig into the reason why, who would do that kind of silly self assignment?

Anything can happen. When we write a code, we're not supposed to do make any assumption. So, we need to guard against it.

Here is the code without any protection.

The code shows a typical overloading assignment overloading. What could be the flaws in the code?

What could happen if *this and rhs is the same Window instance?

If that's the case, the following line is the problem:

We're deleting rhs.sb since *this and rhs are the same object. After deleting the sb , we're trying to access already deleted object of rhs :

We do not want to that happen. The immediate solution is this:

Still there is a problem.

What if an exception is thrown in the copy constructor after we deleted sb . Then, we're end up having a pointer which is pointing to nothing. So, we need a better code:

In this way, the Window object can still holding the ScrollBar even in when there is a thrown exception.

Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

Sponsor Open Source development activities and free contents for everyone.

C++ Tutorials

IMAGES

  1. Solved Objectives: To understand why operator overloading is

    overload assignment operator in template

  2. A sample program to overload assignment operator!

    overload assignment operator in template

  3. Solved: Need Help With This C++ Assignment. Please No Adva...

    overload assignment operator in template

  4. Overloading Assignment Operator =, C++ Example

    overload assignment operator in template

  5. Assignment Operator in JavaScript

    overload assignment operator in template

  6. Assignment Operators in PHP Tutorial 11 June 2022

    overload assignment operator in template

VIDEO

  1. Applied Assignment Presentation Template

  2. 1DV027

  3. Sweetness Overload Marang Fruits #Shorts

  4. C++ substraction assignment operator (-=)

  5. C++ addition assignment operator

  6. overload + operator in c++

COMMENTS

  1. Overloading assignment operator in a class template that can cast to

    You should do this: template <class T2> Number<T>& operator=( const Number<T2>& number ) { m_value = number.value(); return *this; }.

  2. Overloaded assignment operator for class template objects

    However, I can't for the life of me fathom why my overloaded assignment operator worked perfectly well only for integer datatype and not for

  3. Assignment Operators Overloading in C++

    Assignment Operators Overloading in C - You can overload the assignment operator (=) just as you can other operators and it can be used to create an object

  4. 14.15

    14.15 — Overloading the assignment operator · If a new object has to be created before the copying can occur, the copy constructor is used (note:

  5. C++ Assignment Operator Overloading

    Overloading assignment operator in C++ copies all values of one object to another object. Only a non-static member function should be used to

  6. Copy assignment operator

    A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter

  7. Move assignment operator

    A move assignment operator of class T is a non-template ... The move assignment operator is called whenever it is selected by overload

  8. Efficient Expression Templates for Operator Overloading-based

    class ETFad : public Expr<ETFadTag> { public : // ELR expression template assignment operator template <typename T> ELRFad& operator=(const Expr<T>& x). { val =

  9. stack.h

    template <class T> class Stack { static const int initialSize = 32; ... copy constructor */ Stack& operator=(const Stack &); /* overloaded assignment

  10. C++ Tutorial: Operator Overloading II

    Why do we need to protect against the self assignment when we do overloading assignment operator? But before we dig into the reason why, who would do that