• Sign In / Suggest an Article

Current ISO C++ status

Upcoming ISO C++ meetings

Upcoming C++ conferences

Compiler conformance status

CppCon 2024

September 15-20, Aurora, CO, USA

Meeting C++ 2024

November 14-16, Berlin, Germany

assignment operators

Assignment operators, what is “self assignment”.

Self assignment is when someone assigns an object to itself. For example,

Obviously no one ever explicitly does a self assignment like the above, but since more than one pointer or reference can point to the same object (aliasing), it is possible to have self assignment without knowing it:

This is only valid for copy assignment. Self-assignment is not valid for move assignment.

Why should I worry about “self assignment”?

If you don’t worry about self assignment , you’ll expose your users to some very subtle bugs that have very subtle and often disastrous symptoms. For example, the following class will cause a complete disaster in the case of self-assignment:

If someone assigns a Fred object to itself, line #1 deletes both this->p_ and f.p_ since *this and f are the same object. But line #2 uses *f.p_ , which is no longer a valid object. This will likely cause a major disaster.

The bottom line is that you the author of class Fred are responsible to make sure self-assignment on a Fred object is innocuous . Do not assume that users won’t ever do that to your objects. It is your fault if your object crashes when it gets a self-assignment.

Aside: the above Fred::operator= (const Fred&) has a second problem: If an exception is thrown while evaluating new Wilma(*f.p_) (e.g., an out-of-memory exception or an exception in Wilma ’s copy constructor ), this->p_ will be a dangling pointer — it will point to memory that is no longer valid. This can be solved by allocating the new objects before deleting the old objects.

Okay, okay, already; I’ll handle self-assignment. How do I do it?

You should worry about self assignment every time you create a class . This does not mean that you need to add extra code to all your classes: as long as your objects gracefully handle self assignment, it doesn’t matter whether you had to add extra code or not.

We will illustrate the two cases using the assignment operator in the previous FAQ :

If self-assignment can be handled without any extra code, don’t add any extra code. But do add a comment so others will know that your assignment operator gracefully handles self-assignment:

Example 1a:

Example 1b:

If you need to add extra code to your assignment operator, here’s a simple and effective technique:

Or equivalently:

By the way: the goal is not to make self-assignment fast. If you don’t need to explicitly test for self-assignment, for example, if your code works correctly (even if slowly) in the case of self-assignment, then do not put an if test in your assignment operator just to make the self-assignment case fast. The reason is simple: self-assignment is almost always rare, so it merely needs to be correct - it does not need to be efficient. Adding the unnecessary if statement would make a rare case faster by adding an extra conditional-branch to the normal case, punishing the many to benefit the few.

In this case, however, you should add a comment at the top of your assignment operator indicating that the rest of the code makes self-assignment is benign, and that is why you didn’t explicitly test for it. That way future maintainers will know to make sure self-assignment stays benign, or if not, they will need to add the if test.

I’m creating a derived class; should my assignment operators call my base class’s assignment operators?

Yes (if you need to define assignment operators in the first place).

If you define your own assignment operators, the compiler will not automatically call your base class’s assignment operators for you. Unless your base class’s assignment operators themselves are broken, you should call them explicitly from your derived class’s assignment operators (again, assuming you create them in the first place).

However if you do not create your own assignment operators, the ones that the compiler create for you will automatically call your base class’s assignment operators.

Please Login to submit a recommendation.

If you don’t have an account, you can register for free.

C++ Tutorial

C++ functions, c++ classes, c++ data s tructures, c++ reference, c++ examples, c++ inheritance, inheritance.

In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:

  • derived class (child) - the class that inherits from another class
  • base class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent):

Why And When To Use "Inheritance"?

- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

21.12 — Overloading the assignment operator

21.12 — Overloading the assignment operator

Inheriting const Assignment Operator in C++

Understanding Inheritance of const Assignment Operator in C++: A Closer Look

Abstract: In this article, we delve into the intricacies of inheriting const assignment operators in C++. Discover how the derived class's operator can override the base class's implicitly defined one and explore the use of 'using Base::operator='.

Understanding Inheritance, const Assignment Operator, and C++: A Closer Look

Inheritance is a fundamental concept in object-oriented programming, allowing the creation of new classes that reuse, extend, and modify the behavior defined in other classes. In C++, inheritance is implemented using the : keyword. When a class inherits from another class, it automatically gains access to all the members of the base class. However, sometimes we need to customize the behavior of the inherited members, especially when it comes to assignment operators.

Assignment Operators and Inheritance

In C++, the assignment operator ( = ) is a special member function that is used to assign values from one object to another. When a class inherits from another class, the derived class automatically gets its own assignment operator, which performs a shallow copy of the base class sub-object. This behavior is usually sufficient for most cases, but sometimes we need to customize the assignment operator to perform a deep copy or to handle specific situations.

The const Assignment Operator

In C++, we can declare the assignment operator as a const member function. A const member function is a function that promises not to modify the state of the object it is called on. This means that we can use the const assignment operator to assign values to const objects, which is useful in some situations.

In the example above, we declare a const assignment operator for the Base class. This operator performs a deep copy of the other object, which is useful if the Base class contains dynamically allocated memory or other resources that need to be managed.

Using the Base::operator= in Derived Classes

When a derived class inherits from a base class that has a custom assignment operator, the derived class automatically gets its own assignment operator that performs a shallow copy of the base class sub-object. If we want to use the custom assignment operator of the base class, we need to explicitly call it using the Base::operator= syntax.

In the example above, we declare a custom assignment operator for the Derived class. This operator first calls the const assignment operator of the base class using the Base::operator= syntax. Then, it performs any custom behavior that is specific to the derived class.

Inheritance is a powerful concept in object-oriented programming, but it can lead to some unexpected behavior when it comes to assignment operators. By understanding how the const assignment operator works and how to use the Base::operator= syntax, we can customize the behavior of the assignment operator in derived classes and avoid common pitfalls.

  • Stroustrup, Bjarne. The C++ Programming Language . 4th ed. Addison-Wesley Professional, 2013.
  • Lippman, Stanley B., Josée Lajoie, and Barbara E. Moo. C++ Primer . 5th ed. Addison-Wesley Professional, 2012.
  • Const assignment operator in C++
  • Const Assignment Operator FAQ

Online resources:

  • Operators (C++ reference)
  • GFact #38: Assignment operator in C++

Explore the full article to gain a deeper understanding of C++ inheritance and assignment operators.

Customizing laravel pest: single argument unit tests with readable folder structure.

In this article, we'll discuss how to customize Laravel Pest for single argument unit tests and create a more readable folder structure.

Understanding the Impossibility of Implementing an Algorithm Fewer Steps than Claimed by an Engineer: A Harvard CS50 Perspective

In this article, we discuss the challenges of understanding and verifying the implementation of an algorithm with fewer steps than claimed by an engineer. We provide insights from the Harvard CS50 perspective.

Using ViewNavigationMenu in Vuforia Studio

Learn how to use the ViewNavigationMenu feature in Vuforia Studio for AR application development.

Docker Compose: Not Setting PostgreSQL User and DB

Learn how to set a PostgreSQL user and database in a Docker Compose file.

Passing JSON Data to Desktop Version of Power Automate using cURL

Learn how to pass JSON data to the Desktop Version of Power Automate using cURL.

Unable to Deploy Project to O2Switch: Static Build Issues

Learn how to resolve issues with deploying a project to O2Switch due to static build problems. Discover solutions for Node.js hosting and server installation.

Unable to Run 'django-admin' after setting up Django project in VSCode

Learn how to resolve the issue of being unable to run 'django-admin' after setting up a Django project in Visual Studio Code.

Tags: :  C++ Inheritance Assignment Operator

Latest news

  • Kindle-friendly HTML5 Canvas: Building Simple Web Apps with User-Drawn Canvas Objects
  • Deprecated Gradle Features Used in build.gradle Making Incompatible with Gradle 9.0.q
  • Implementing an Elorating System for Local Tennis Players: Setting Starting Values
  • Rewriting a Regulard Discord Bot to a Discord Self Bot using discord.py-Right
  • Understanding switchMap and convertObservable in Angular
  • Oracle APEX: Consuming JSON Data from a Webhook for Table Insertion
  • Google Sign-In in Android: Default Redirect URI
  • Deploying Per-App Content Filters with Intune for iOS 16 and Above
  • CSS Scrolling Table Affects Quarto Document: One Table with gt Package
  • Failed to Bypass SSL Verification in React Native App
  • Updating Dynamically Created Variables with Skillscript: A Step-by-Step Guide
  • Resolving Authorization Errors with iOS and macOS Devices on Loading Widgets
  • File Corruption Problem in Jupyter Notebook (PyCharm)
  • Resolving IOException: An Invalid State Exception When Launching ChromeDriver for Selenium
  • Compilation Error in Xcode 16 with iOS 18 when Integrating Flutter Projects
  • Understanding the Difference Between MySQL Error and MySQLConnectorError in Python
  • Error in Cloud Recognition: Recreating GameObjects
  • Tracking Last Login: Managing Client Interactions in CouchDB
  • Error in Creating Flutter Bloc: Couldn't find correct Provider<XYZ> BuilderWidget
  • Quarkus: Changing OIDC Claim Path for Secured Endpoints
  • Making Fields Required Based on Schema-Specific Parent: A Comprehensive Guide
  • Missing Origin Level Data on Halfords' Website since September 2024
  • VBA: Index Match Lookup Returns Multiple Columns - Column Name but not First Column Lookup
  • Kafka Message Compression Not Working at Broker Level
  • Adding Border Points to Chart.js
  • Introducing Variable X: Range Call Function in Excel
  • Desktop Central: Not Connecting Issues with Remote Control Feature
  • Running a Face Recognition Project: Which File to Enter Command in VSCode after Cloning GitHub?
  • Automatically Port Forwarding Python: A Simple Solution
  • Encoding Diacritics in JSON-LD for Software Development Sites: A German Example
  • Unable to Get Current Sessions Data Row in Laravel
  • IntelliJ: Display Last Execution Timeline in the Editor
  • Correct SELinux Policy for MongoDB 7 Enterprise on RHEL 9: Installing the .rpmvs.tgz
  • Updating SSL Policy for a GCP Internal Load Balancer Frontend using gCloud CLI
  • Boosting Python Performance: Important Localising Variables
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

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.

Get early access and see previews of new features.

C++ Class Inheritance and assignment operator

I came here to ask something I can't figure out on my own. I've been coding a little class that stores an array of 32 bits and can perform simple mathematic operations like + , - , / and * .

Suppose I have a class like:

Until now, no problem comes up if i declare 3 objects a , b , c of class Binary_Class , then set_dec to a and b , the statement c=a+b can be used (?)

However, I want to extend the class binary by using a new class

If I declare 3 objects a , b , c of class Binary_Class_Extended , am I still able to use c=a+b as the same before that?

In Netbean it says there's no operator= that match my c=a+b if all are of Binary_Class_Extended , but if I declare c as Binary_Class that statement works. That means a+b returns a const Binary_Class as if the operator+ doesn't get carried to the new class.

Am I missing something or this is the way it is?

Of course, I can post the whole code because it's just an assignment but I think these infos are enough for now.

When I try to have all objects of Binary_Class_Extended this error show up:

main.cpp:285: error: no match for 'operator=' in 'sd = ((Binary_Class*)(&sa))->Binary_Class::operator+(((const Binary_Class&)((const Binary_Class*)((Binary_Class*)(&sb)))))'

Binary_ET_Class sa,sb,sc;

sc=sa+sb //initialized sa and sb to non-null value;

The full source code I've been working on: https://pastebin.com/eiVz0f5p

  • inheritance
  • operator-keyword

Meraj al Maksud's user avatar

  • Please use proper capitalization. –  Antimony Commented Jun 18, 2013 at 4:30
  • Ah, thanks for correcting the post. My mind wasn't focus on that at the time, sorry. –  Luong Commented Jun 18, 2013 at 8:11

2 Answers 2

Inherited functions retain their finger prints, so if the Binary_Class operator+ was inherited, it's return value would be ... ?

kfsone's user avatar

  • Ah, what a simple answer. I think I've treated those so called operator differently. They're just functions right? So if I want to retain the function of thte operator+ I shall write one in the new class, shouldn't I? –  Luong Commented Jun 18, 2013 at 8:09
  • Yep -- one other thing occurred to me; your operator+ isn't const, and it probably should be -- operator "+" is used for x = a + b but it is used on a and b, not on x. So you probably want const Binary_Class& operator+(const Binary_Class& src) const; . See courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html . Your Binary_Class_Extended can kill two birds with one stone by defining it as const Binary_Class_Extended& operator+(const Binary_Class& rhs) const; and allowing it to take the base class rather than the derived class. –  kfsone Commented Jun 18, 2013 at 17:32
  • oh ive come across that paged and read that too but missed that last const after the bracket. this is the error when all are of Binary_Class_Extended, and i don't redeclare = and + operator on that class aka the operator= error i mentioned in the question: main.cpp:285: error: no match for 'operator=' in 'sd = ((Binary_Class*)(&sa))->Binary_Class::operator+(((const Binary_Class&)((const Binary_Class*)((Binary_Class*)(&sb)))))' –  Luong Commented Jun 18, 2013 at 18:41
  • Can you append this to the original post along with the updated code so I can see it more easily? –  kfsone Commented Jun 18, 2013 at 19:36
  • pastebin.com/eiVz0f5p I pasted it here the full source, hope you can try and read my messy code if you don't mind. I'll update the post right away –  Luong Commented Jun 19, 2013 at 0:35

In general, inheritance and assignment ("value semantics") don't mix easily in C++. In your second case, the "a+b" would return an instance of the baseclass, unless you define a separator operator+ for the derived class. The result is then only assigned to the base-class part of "c", which is triggering the error. This is also sometimes call slicing/truncation. Note that the choice of the operator is at compile time, no virtual functions are called, so the static type has to match.

Don't mix value types and polymorphic types. If you really need to and you have a fixed and known hierarchy, you can use the "Handle-Body Idiom" to preserve derived information when assigning to the baseclass. This is not a beginner topic though.

Ulrich Eckhardt's user avatar

  • Oh, so they don't carry the operator to the child? What I think is that the new class "inherit" all the good of the base class and if I don't re-define the operator + then the function remain the same, only change the class from Binary_Class to Binary_Class_Extended . The purpose of the new class is to extend functionality of the base class by providing additional functions to it, but I think I have failed to achieve that because the original functions (like operator+) is lost (can't perform on the new class). –  Luong Commented Jun 18, 2013 at 8:05

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

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 and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ class inheritance binary operator-keyword or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Real Estate Partition Suit with Negative Equity
  • PCB design references and roadmap
  • Can there be a proper class of Dedekind-finite cardinals?
  • Consequences of registering a PhD at german university?
  • Are 8086 family microprocessors accumulator based?
  • Does General Relativity predict Mercury's orbital precession without other planets?
  • When is due diligence enough when attempting to contact a copyright holder?
  • Does Tempestuous Magic allow you to avoid attacks of opportunity *after* they have already triggered?
  • Terminated employee will not help the company locate its truck
  • Seeking Advice on Correction of Minor Errors in a Published Research Paper
  • Is it ok if I was wearing lip balm and my bow touched my lips by accident and then that part of the bow touched the wood on my viola?
  • Why color of my painting changed from brownish to greenish?
  • Why doesn't Josephus mention the golden calf?
  • How safe is the runastool.exe, any known issues?
  • Trinitarian Christianity says Jesus was fully God and Fully man. Did Jesus (the man) know this to be the case?
  • Fear of getting injured in Judo
  • How is AC and DC defined?
  • If directly exposed to the vacuum of space, what would be the effects on a womans reproductive system?
  • What size wire nut for joining #8 and #10 wire?
  • Model looks dented but geometry is correct
  • Numerical integration of ODEs: Why does higher accuracy and precision not lead to convergence?
  • How can I connect heavy-gauge wire to a 20A breaker?
  • Superuser and Sudo not working on Debian 12
  • Does it ever make sense to have a one-to-one obligatory relationship in a relational database?

c inheritance class assignment operator

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

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.

  • Assignment operator overloading is binary 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 overload the assignment operator.

In C++, the compiler automatically provides a default assignment operator for classes. This operator performs a shallow copy of each member of the class from one object to another. This means that if we don’t explicitly overload the assignment operator, the compiler will still allow us to assign one object to another using the assignment operator ( = ), and it won’t generate an error.

So, when we should perform assignment operator overloading? when our class involves dynamic memory allocation (e.g., pointers) and we need to perform a deep copy to prevent issues like double deletion or data corruption.

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”.

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.

Also, always check if the object is not being assigned to itself (e.g., if (this != &other)), as assigning an object to itself does not make sense and may cause runtime issues.

While managing dynamic resources, the above approach of assignment overloading have few flaws and there is more efficient approach that is recommended. See this article for more info – Copy-and-Swap Idiom in C++

Please Login to comment...

Similar reads.

  • cpp-operator
  • cpp-operator-overloading
  • Best External Hard Drives for Mac in 2024: Top Picks for MacBook Pro, MacBook Air & More
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

cppreference.com

Operator overloading.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
(C++11)
(C++20)
(C++26)
(C++11)
(C++11)
-expression
-expression
-expression
(C++11)
(C++11)
(C++17)
(C++20)
    

Customizes the C++ operators for operands of user-defined types.

Syntax Overloaded operators Static overloaded operators Restrictions Canonical implementations Assignment operator Stream extraction and insertion Function call operator Increment and decrement Binary arithmetic operators Comparison operators Array subscript operator Bitwise arithmetic operators Boolean negation operator Rarely overloaded operators Notes Keywords Example Defect reports See also External links

[ edit ] Syntax

Overloaded operators are functions with special function names:

op (1)
type (2)

(3)

(4)
suffix-identifier (5) (since C++11)
(6) (since C++20)
op - any of the following operators:+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= <=>(since C++20) && || ++ -- , ->* -> ( ) [ ]

[ edit ] Overloaded operators

When an operator appears in an expression , and at least one of its operands has a class type or an enumeration type , then overload resolution is used to determine the user-defined function to be called among all the functions whose signatures match the following:

Expression As member function As non-member function Example
@a (a).operator@ ( ) operator@ (a) ! calls .operator!()
a@b (a).operator@ (b) operator@ (a, b) << 42 calls .operator<<(42)
a=b (a).operator= (b) cannot be non-member Given s;, s = "abc"; calls s.operator=("abc")
a(b...) (a).operator()(b...) cannot be non-member Given r;, auto n = r(); calls r.operator()()
a[b...] (a).operator[](b...) cannot be non-member Given <int, int> m;, m[1] = 2; calls m.operator[](1)
a-> (a).operator-> ( ) cannot be non-member Given <S> p;, p->bar() calls p.operator->()
a@ (a).operator@ (0) operator@ (a, 0) Given <int>::iterator i;, i++ calls i.operator++(0)

In this table, is a placeholder representing all matching operators: all prefix operators in @a, all postfix operators other than -> in a@, all infix operators other than = in a@b.

In addition, for comparison operators ==, !=, <, >, <=, >=, <=>, overload resolution also considers the generated from operator== or operator<=>.

(since C++20)

Note: for overloading co_await , (since C++20) user-defined conversion functions , user-defined literals , allocation and deallocation see their respective articles.

Overloaded operators (but not the built-in operators) can be called using function notation:

Overloaded operators that are member functions can be declared . However, this is only allowed for operator() and operator[].

Such operators can be called using function notation. However, when these operators appear in expressions, they still require an object of class type.

SwapThem { template <typename T> static void operator()(T& lhs, T& rhs) { std:: (lhs, rhs); } template <typename T> static void operator[](T& lhs, T& rhs) { std:: (lhs, rhs); } }; inline constexpr SwapThem swap_them {};   void foo() { int a = 1, b = 2;   swap_them(a, b); // OK swap_them[a, b]; // OK   SwapThem{}(a, b); // OK SwapThem{}[a, b]; // OK   SwapThem::operator()(a, b); // OK SwapThem::operator[](a, b); // OK   SwapThem(a, b); // error, invalid construction SwapThem[a, b]; // error }
(since C++23)

[ edit ] Restrictions

  • The operators :: (scope resolution), . (member access), .* (member access through pointer to member), and ?: (ternary conditional) cannot be overloaded.
  • New operators such as ** , <> , or &| cannot be created.
  • It is not possible to change the precedence, grouping, or number of operands of operators.
  • The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded.
  • The overloads of operators && and || lose short-circuit evaluation.
, , and (comma) lose their special when overloaded and behave like regular function calls even when they are used without function-call notation. (until C++17)

[ edit ] Canonical implementations

Besides the restrictions above, the language puts no other constraints on what the overloaded operators do, or on the return type (it does not participate in overload resolution), but in general, overloaded operators are expected to behave as similar as possible to the built-in operators: operator + is expected to add, rather than multiply its arguments, operator = is expected to assign, etc. The related operators are expected to behave similarly ( operator + and operator + = do the same addition-like operation). The return types are limited by the expressions in which the operator is expected to be used: for example, assignment operators return by reference to make it possible to write a = b = c = d , because the built-in operators allow that.

Commonly overloaded operators have the following typical, canonical forms: [1]

[ edit ] Assignment operator

The assignment operator ( operator = ) has special properties: see copy assignment and move assignment for details.

The canonical copy-assignment operator is expected to be safe on self-assignment , and to return the lhs by reference:

The canonical move assignment is expected to (that is, a state with class invariants intact), and either or at least leave the object in a valid state on self-assignment, and return the lhs by reference to non-const, and be noexcept:

T& operator=(T&& other) noexcept { // Guard self assignment if (this == &other) return *this; // delete[]/size=0 would also be ok   delete[] mArray; // release resource in *this mArray = (other.mArray, nullptr); // leave other in valid state size = (other.size, 0); return *this; }
(since C++11)

In those situations where copy assignment cannot benefit from resource reuse (it does not manage a heap-allocated array and does not have a (possibly transitive) member that does, such as a member std::vector or std::string ), there is a popular convenient shorthand: the copy-and-swap assignment operator, which takes its parameter by value (thus working as both copy- and move-assignment depending on the value category of the argument), swaps with the parameter, and lets the destructor clean it up.

This form automatically provides strong exception guarantee , but prohibits resource reuse.

[ edit ] Stream extraction and insertion

The overloads of operator>> and operator<< that take a std:: istream & or std:: ostream & as the left hand argument are known as insertion and extraction operators. Since they take the user-defined type as the right argument ( b in a @ b ), they must be implemented as non-members.

These operators are sometimes implemented as friend functions .

[ edit ] Function call operator

When a user-defined class overloads the function call operator, operator ( ) , it becomes a FunctionObject type.

An object of such a type can be used in a function call expression:

Many standard algorithms, from std:: sort to std:: accumulate accept FunctionObject s to customize behavior. There are no particularly notable canonical forms of operator ( ) , but to illustrate the usage:

[ edit ] Increment and decrement

When the postfix increment or decrement operator appears in an expression, the corresponding user-defined function ( operator ++ or operator -- ) is called with an integer argument 0 . Typically, it is implemented as T operator ++ ( int ) or T operator -- ( int ) , where the argument is ignored. The postfix increment and decrement operators are usually implemented in terms of the prefix versions:

Although the canonical implementations of the prefix increment and decrement operators return by reference, as with any operator overload, the return type is user-defined; for example the overloads of these operators for std::atomic return by value.

[ edit ] Binary arithmetic operators

Binary operators are typically implemented as non-members to maintain symmetry (for example, when adding a complex number and an integer, if operator+ is a member function of the complex type, then only complex + integer would compile, and not integer + complex ). Since for every binary arithmetic operator there exists a corresponding compound assignment operator, canonical forms of binary operators are implemented in terms of their compound assignments:

[ edit ] Comparison operators

Standard algorithms such as std:: sort and containers such as std:: set expect operator < to be defined, by default, for the user-provided types, and expect it to implement strict weak ordering (thus satisfying the Compare requirements). An idiomatic way to implement strict weak ordering for a structure is to use lexicographical comparison provided by std::tie :

Typically, once operator < is provided, the other relational operators are implemented in terms of operator < .

Likewise, the inequality operator is typically implemented in terms of operator == :

When three-way comparison (such as std::memcmp or std::string::compare ) is provided, all six two-way comparison operators may be expressed through that:

The inequality operator is automatically generated by the compiler if operator== is defined. Likewise, the four relational operators are automatically generated by the compiler if the three-way comparison operator operator<=> is defined. operator== and operator!=, in turn, are generated by the compiler if operator<=> is defined as defaulted:

Record { name; unsigned int floor; double weight;   auto operator<=>(const Record&) const = default; }; // records can now be compared with ==, !=, <, <=, >, and >=

See for details.

(since C++20)

[ edit ] Array subscript operator

User-defined classes that provide array-like access that allows both reading and writing typically define two overloads for operator [ ] : const and non-const variants:

Alternatively, they can be expressed as a single member function template using an :

T { decltype(auto) operator[](this auto& self, idx) { return self.mVector[idx]; } };
(since C++23)

If the value type is known to be a scalar type, the const variant should return by value.

Where direct access to the elements of the container is not wanted or not possible or distinguishing between lvalue c [ i ] = v ; and rvalue v = c [ i ] ; usage, operator [ ] may return a proxy. See for example std::bitset::operator[] .

operator[] can only take one subscript. In order to provide multidimensional array access semantics, e.g. to implement a 3D array access a[i][j][k] = x;, operator[] has to return a reference to a 2D plane, which has to have its own operator[] which returns a reference to a 1D row, which has to have operator[] which returns a reference to the element. To avoid this complexity, some libraries opt for overloading operator() instead, so that 3D access expressions have the Fortran-like syntax a(i, j, k) = x;.

(until C++23)

operator[] can take any number of subscripts. For example, an operator[] of a 3D array class declared as T& operator[]( x, y, z); can directly access the elements.

#include <cassert> #include <iostream>   template<typename T, Z, Y, X> struct Array3d { <T, X * Y * Z> m{};   constexpr T& operator[]( z, y, x) // C++23 { (x < X and y < Y and z < Z); return m[z * Y * X + y * X + x]; } };   int main() { Array3d<int, 4, 3, 2> v; v[3, 2, 1] = 42; << "v[3, 2, 1] = " << v[3, 2, 1] << '\n'; }

Output:

(since C++23)

[ edit ] Bitwise arithmetic operators

User-defined classes and enumerations that implement the requirements of BitmaskType are required to overload the bitwise arithmetic operators operator & , operator | , operator ^ , operator~ , operator & = , operator | = , and operator ^ = , and may optionally overload the shift operators operator << operator >> , operator >>= , and operator <<= . The canonical implementations usually follow the pattern for binary arithmetic operators described above.

[ edit ] Boolean negation operator

The operator operator! is commonly overloaded by the user-defined classes that are intended to be used in boolean contexts. Such classes also provide a user-defined conversion function to boolean type (see for the standard library example), and the expected behavior of operator! is to return the value opposite of operator bool.

(until C++11)

Since the built-in operator ! performs , user-defined classes that are intended to be used in boolean contexts could provide only operator bool and need not overload operator!.

(since C++11)

[ edit ] Rarely overloaded operators

The following operators are rarely overloaded:

  • The address-of operator, operator & . If the unary & is applied to an lvalue of incomplete type and the complete type declares an overloaded operator & , it is unspecified whether the operator has the built-in meaning or the operator function is called. Because this operator may be overloaded, generic libraries use std::addressof to obtain addresses of objects of user-defined types. The best known example of a canonical overloaded operator& is the Microsoft class CComPtrBase . An example of this operator's use in EDSL can be found in boost.spirit .
  • The boolean logic operators, operator && and operator || . Unlike the built-in versions, the overloads cannot implement short-circuit evaluation. Also unlike the built-in versions, they do not sequence their left operand before the right one. (until C++17) In the standard library, these operators are only overloaded for std::valarray .
  • The comma operator, operator, . Unlike the built-in version, the overloads do not sequence their left operand before the right one. (until C++17) Because this operator may be overloaded, generic libraries use expressions such as a, void ( ) ,b instead of a,b to sequence execution of expressions of user-defined types. The boost library uses operator, in boost.assign , boost.spirit , and other libraries. The database access library SOCI also overloads operator, .
  • The member access through pointer to member operator - > * . There are no specific downsides to overloading this operator, but it is rarely used in practice. It was suggested that it could be part of a smart pointer interface , and in fact is used in that capacity by actors in boost.phoenix . It is more common in EDSLs such as cpp.react .

[ edit ] Notes

macro Value Std Feature
202207L (C++23) static operator()
202211L (C++23) static operator[]

[ edit ] Keywords

[ edit ] example, [ edit ] defect reports.

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

DR Applied to Behavior as published Correct behavior
C++98 the non-member prefix increment operator could
only have a parameter of class or enumeration type
no type requirement

[ edit ] See also

  • Operator precedence
  • Alternative operator syntax
  • Argument-dependent lookup
Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[...]
*a
&a
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

[ edit ] External links

on StackOverflow C++ FAQ
  • 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 11 August 2024, at 22:37.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

IMAGES

  1. Explore the 5 Types of Inheritance in C++ with Syntax & Example

    c inheritance class assignment operator

  2. Solved C++ PROGRAMMING: INHERITANCE AND OPERATOR OVERLOADING

    c inheritance class assignment operator

  3. Inheritance in C++

    c inheritance class assignment operator

  4. Inheritance in C++

    c inheritance class assignment operator

  5. What is assignment operator in C with example?

    c inheritance class assignment operator

  6. Inheritance in c++ And It's types [Explained] with example program

    c inheritance class assignment operator

VIDEO

  1. Augmented assignment operators in C

  2. Objective C Programming Tutorial

  3. Assignment Operator in C Programming

  4. Inheritance Program

  5. C++ Inheritance and Polymorphism explained

  6. C++ Assignment Operators Practice coding

COMMENTS

  1. c++

    Derived& operator=(const Base& a); in your Derived class. A default assignment operator, however, is created: Derived& operator=(const Derived& a); and this calls the assignment operator from Base. So it's not a matter of inheriting the assignment operator, but calling it via the default generated operator in your derived class.

  2. inheritance

    The copy assignment operator of the derived class that is implicitly declared by the compiler hides assignment operators of the base class. Use using declaration in the derived class the following way. using A::operator =; B():A(){}; virtual ~B(){}; virtual void doneit(){myWrite();} Another approach is to redeclare the virtual assignment ...

  3. Is assignment operator inherited?

    In C++, like other functions, assignment operator function is inherited in derived class. For example, in the following program, base class assignment operator function can be accessed using the derived class object. Output: base class assignment operator called. Summer-time is here and so is the time to skill-up!

  4. Derived classes

    Derived classes. Any class type (whether declared with class-keyclass or struct) may be declared as derived from one or more base classes which, in turn, may be derived from their own base classes, forming an inheritance hierarchy.

  5. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs. Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

  6. Using-declaration

    If a using-declaration brings the base class assignment operator into derived class, whose signature happens to match the derived class's copy-assignment or move-assignment operator, that operator is hidden by the implicitly-declared copy/move assignment operator of the derived class.

  7. Assignment Operators, C++ FAQ

    If you define your own assignment operators, the compiler will not automatically call your base class's assignment operators for you. Unless your base class's assignment operators themselves are broken, you should call them explicitly from your derived class's assignment operators (again, assuming you create them in the first place).

  8. C++ Inheritance

    In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: derived class (child) - the class that inherits from another class. base class (parent) - the class being inherited from. To inherit from a class, use the : symbol.

  9. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  10. Inheritance in C++

    The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the class.

  11. Copy assignment operator

    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.

  12. 21.12

    21.12 — Overloading the assignment operator. Alex July 22, 2024. The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports "Move assignment". We discuss move assignment in lesson 22.3 -- Move constructors and move assignment.

  13. 14: Inheritance & Composition

    The first is quite straightforward: You simply create objects of your existing class inside the new class. This is called composition because the new class is composed of objects of existing classes. The second approach is subtler. You create a new class as a type of an existing class. You literally take the form of the existing class and add ...

  14. Move assignment operator

    5,6) Definition of a move assignment operator outside of class definition (the class must contain a declaration (1)). 6) The move assignment operator is explicitly-defaulted. 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 ...

  15. Understanding Inheritance of const Assignment Operator in C++: A Closer

    Understanding Inheritance, const Assignment Operator, and C++: A Closer Look Inheritance is a fundamental concept in object-oriented programming, allowing the creation of new classes that reuse, extend, and modify the behavior defined in other classes. In C++, inheritance is implemented using the : keyword. When a class inherits from another class, it automatically gains access to all the ...

  16. Assignment operators

    Move assignment replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in move assignment operator. (since C++11)

  17. C++ Class Inheritance and assignment operator

    C++ Class Inheritance and assignment operator Asked 11 years, 1 month ago Modified 4 years, 9 months ago Viewed 377 times

  18. C++ Assignment 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. Assignment operator overloading is binary operator overloading. Overloading assignment operator in C++ copies all values of one object to another object.

  19. operator overloading

    It is not possible to change the precedence, grouping, or number of operands of operators. The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded. The overloads of operators && and || lose short-circuit evaluation.