This set of slides introduces the reader to the concept of operator overloading for user-defined types in C++ (with elements of C++11 and C++14). The exemplary case of the complex class is introduced. It follows a discussion on how to implement mixed-mode arithmetic, which requires mixing member and non-member operator functions. Moreover, the technical tool of friend functions and access functions is discussed.
Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed.
In computer programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.
↓↓↓↓ Read More:
@ Kindly Follow my Instagram Page to discuss about your mental health problems-
-----> https://instagram.com/mentality_streak?utm_medium=copy_link
@ Appreciate my work:
-----> behance.net/burhanahmed1
Thank-you !
This presentation includes 7 programs, in which 5 are basic arithmatic (binary) operator overloading and 2 are the unary operators( increment and decrement) overloading.
Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed.
In computer programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.
↓↓↓↓ Read More:
@ Kindly Follow my Instagram Page to discuss about your mental health problems-
-----> https://instagram.com/mentality_streak?utm_medium=copy_link
@ Appreciate my work:
-----> behance.net/burhanahmed1
Thank-you !
This presentation includes 7 programs, in which 5 are basic arithmatic (binary) operator overloading and 2 are the unary operators( increment and decrement) overloading.
This set of slides introduces the reader to the concept of arrays in C++ (with elements of C++11 and C++14). After presenting the array data type, the concept of array-to-pointer decay is introduced. The presentation proceeds with a discussion on how to pass arrays to functions. To this extent, the reader is guided to the use of bounded ranges as the first step towards the use of the Standard Template Library (STL).
This set of slides introduces the reader to the concept of resource wrappers, i.e., classes that are responsible for the correct handling of resources of some kind (e.g., memory). In particular, the presentation discusses the design and implementation of a simplified version of std::vector for the specific case of integer elements. In this regard, we first discuss the fundamental role of destructors as a deterministic, general-purpose undo mechanism. Second, we notice that providing an explicit destructor entails the need of a consequent explicit implementation for the copy constructor and copy assignment operator. We conclude with the formulation of the so-called "rule of three".
Operator Overloading and Scope of VariableMOHIT DADU
This slide is completely based on the Operator Overloading and the Scope of Variable. The example given to explain are based on C/C++ programming language.
This set of slides introduces the reader to the concept of regular types, i.e., user-defined types whose semantics closely resembles that of built-in types. The notion of regular types proved crucial for the development of the C++ Standard Template Library, and it is currently employed in next-gen C++ libraries such as Eric Niebler's range-v3. The presentation serves as a gentle introduction to the topic, and discusses which requirements must be satisfied for a type to be regular. In particular, the concept of equality-preserving copy and assignment is presented, as well as how to define ordering relations that satisfy the requirements of strictness, transitivity and comparability (i.e., that adhere to the trichotomy law).
This set of slides introduces the reader to a subset of the C++ Standard Library called the Standard Template Library (STL). The STL provides a collection of parameterized containers and algorithms, and it is the most successful example of an approach to programming called generic programming. In this presentation, we aim at studying the ideals and concepts of the STL by re-implementing small parts of the library. Specifically, we first show how we can discover requirements on types in order to devise generic algorithms. Then, we focus on how to make algorithms independent of containers through the pivotal abstraction of iterators. To this end, we replicate the standard algorithm for finding the minimum in a sequence (min_element), which we subsequently match with a custom forward iterator over intrusive linked lists of integers. Finally, we see how function objects can be used to customize containers and algorithms alike. This allows us to deepen our understanding of ordering relations, and, in particular, to introduce the concept of strict weak orderings.
View study notes of Function overloading .you can also visit Tutorialfocus.net to get complete description step wise of the concerned topic.Other topics and notes of C++ are also explained.
The term overloading means ‘providing multiple definitions of’. Overloading of functions involves defining distinct functions which share the same name, each of which has a unique signature. Function overloading is appropriate for:
Defining functions which essentially do the same thing, but operate on different data types.
Providing alternate interfaces to the same function.
Function overloading is purely a programming convenience.
Operators are similar to functions in that they take operands (arguments) and return a value. Most of the built-in C++ operators are already overloaded. For example, the + operator can be used to add two integers, two reals, or two addresses. Therefore, it has multiple definitions. The built-in definitions of the operators are restricted to built-in types. Additional definitions can be provided by the programmer so that they can also operate on user-defined types. Each additional definition is implemented by a function.
This set of slides introduces the reader to the basics of memory management in C++ (with elements of C++11 and C++14). Specifically, after presenting the essential idea of memory segmentation, the presentation contrasts automatic and dynamic objects. To this extent the critical issue of memory leaks is introduced. It follows a discussion on the more advanced topics, such as owning and non-owning (i.e., observer) pointers, as well as dynamic arrays and structures.
This set of slides introduces the reader to the concept of multidimensional arrays in C++ (with elements of C++11 and C++14). The true nature of multidimensional arrays is discussed by means of an intermediate type alias. The pheonomenon of array-to-pointer decay and pointer arithmetic is then generalized to arrays of arrays. The presentation proceeds with a discussion on how to pass multidimensional arrays to functions.
An introduction to pointers and references in C++ (with elements of C++11 and C++14). The presentation introduces the readers to the concepts of pointers and references through the pragmatic need of writing a swap function between integers. Generic programming notions (e.g., type constructors) are adopted when useful for the explanation.
Spring MVC - Wiring the different layersIlio Catallo
The presentation focuses on the problem of wiring the different layers of a Spring MVC Web application. More precisely, the presentation explains how to wire the presentation layer (made of Spring MVC controllers) with the service and persistence objects. To this end, the slides first explain how to create the so called back-end (a.k.a. root) container, which will host the persistence and the service objects. Second, the @Repository and @Service annotations are introduced, which permit the framework to auto-discover the application beans. Finally, it is discussed how to wire such beans, through the usage of either the Spring-specific @Autowired annotation or the JEE @Inject annotation.
This set of slides introduces the basic concepts of Java development. First, the difference between Java as the programming language and Java as a platform is stated. Then, the different Java platforms are presented, with a particular interest in Java Standard Edition and Java Enterprise Edition. With respect to the latter, the roles and differences between the many JEE containers are discussed.
How to process request parameters with the Spring MVC framework. Namely, the presentation tackles the three primary concerns when dealing with request parameters: data binding, data buffering and data validation. To this end, the Bean Validation API (JSR-303) is discussed, and the concept of MessageSource for localized error messages is introduced. Moreover, The Post/Redirect/Get (PRG) pattern is presented along with a possible implementation strategy.
An introduction to the basics of the Spring MVC Web framework. The concepts of front controller, controller (handler), model and view are introduced. The whole processing pipeline is discussed, with an in-depth description of the HandlerMapping and ViewResolver strategy interfaces. The alternative representations of the Model (Map, Model and ModelMap) are presented.
This set of slides deals with the problem of building robust Web applications by isolating different areas of concern into different layers. The typical four-layer architecture is presented (consisting of the presentation, service and persistence layer, as well as of the domain model) along with an in-depth discussion on the role and responsibilities of each single layer.
Introduzione al concetto di oggetto nel modello della memoria del C++ e ai suoi possibile tempi di vita (temporaneo, automatico, dinamico, ...). Relazione tra il tempo di vita e la visibilità (scope) di un oggetto. Gestione degli oggetti dinamici per tipi primitivi, strutture e array mediante l'utilizzo di puntatori (raw pointers).
Introduzione agli Array in C++. Argomenti trattati: decadimento a puntatore di un array; conseguenze del meccanismo di decadimento sul passaggio di array a funzioni; array multidimensionali e il concetto di puntatore ad array; come passare array multidimensionali a funzioni; gli iteratori come generalizzazione di un puntatore ad elemento di un array ed una breve scorsa di come usare gli iteratori con gli algoritmi standard (e.g., std::copy) del C++.
Introduzione ai puntatori e ai riferimenti in C++. Viene presentato il problema dello swap, come esempio motivante per l'introduzione della semantica di riferimento. Si procede con l'introduzione del concetto di puntatore, a cui segue una spiegazione dei basilare operatori di referenziazione e dereferenziazione. Il problema dello swap viene risolto mediante puntatori. Si procede con l'introduzione dei riferimenti, come alias di variabili esistenti. Il problema dello swap viene in ultimo risolto mediante riferimenti.
An introduction to the Java Persistence API 2.x (JPA). Namely, this set of slides first introduces the problem of impedance mismatch between the object model and the relation model. Then, the EntityManager's public interface is discussed, together with the parallelism between a persistence context and a L1 cache. The issue of encapsulating the different application's use cases (which are exposed by the service objects) is solved by means of the @Transactional annotation, which provides a declarative way of demarcating the application's transactional boundaries. It follows an in-depth explanation on how to integrate a local, container-managed EntityManager within an existing Spring MVC application, so as to correctly support the propagation of the persistence context throughout the different beans involved in the same transaction. We then turn our attention to the problem of mapping relationships, thus introducing the @OneToMany, @ManyToMany and @OneToOne annotations. The additional topics of how to cascade operations and how to support lazy loading are covered as well. The presentation concludes with a discussion on how to use both the Criteria and Query API (and JPQL) to query the underlying database.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Welocme to ViralQR, your best QR code generator.ViralQR
Welcome to ViralQR, your best QR code generator available on the market!
At ViralQR, we design static and dynamic QR codes. Our mission is to make business operations easier and customer engagement more powerful through the use of QR technology. Be it a small-scale business or a huge enterprise, our easy-to-use platform provides multiple choices that can be tailored according to your company's branding and marketing strategies.
Our Vision
We are here to make the process of creating QR codes easy and smooth, thus enhancing customer interaction and making business more fluid. We very strongly believe in the ability of QR codes to change the world for businesses in their interaction with customers and are set on making that technology accessible and usable far and wide.
Our Achievements
Ever since its inception, we have successfully served many clients by offering QR codes in their marketing, service delivery, and collection of feedback across various industries. Our platform has been recognized for its ease of use and amazing features, which helped a business to make QR codes.
Our Services
At ViralQR, here is a comprehensive suite of services that caters to your very needs:
Static QR Codes: Create free static QR codes. These QR codes are able to store significant information such as URLs, vCards, plain text, emails and SMS, Wi-Fi credentials, and Bitcoin addresses.
Dynamic QR codes: These also have all the advanced features but are subscription-based. They can directly link to PDF files, images, micro-landing pages, social accounts, review forms, business pages, and applications. In addition, they can be branded with CTAs, frames, patterns, colors, and logos to enhance your branding.
Pricing and Packages
Additionally, there is a 14-day free offer to ViralQR, which is an exceptional opportunity for new users to take a feel of this platform. One can easily subscribe from there and experience the full dynamic of using QR codes. The subscription plans are not only meant for business; they are priced very flexibly so that literally every business could afford to benefit from our service.
Why choose us?
ViralQR will provide services for marketing, advertising, catering, retail, and the like. The QR codes can be posted on fliers, packaging, merchandise, and banners, as well as to substitute for cash and cards in a restaurant or coffee shop. With QR codes integrated into your business, improve customer engagement and streamline operations.
Comprehensive Analytics
Subscribers of ViralQR receive detailed analytics and tracking tools in light of having a view of the core values of QR code performance. Our analytics dashboard shows aggregate views and unique views, as well as detailed information about each impression, including time, device, browser, and estimated location by city and country.
So, thank you for choosing ViralQR; we have an offer of nothing but the best in terms of QR code services to meet business diversity!
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
5. A class for complex numbers
Let us now assume that we need to perform some arithme2c on
complex numbers
6. A class for complex numbers
Since there is no built-in types modeling the concept of complex
numbers, we decide to introduce a new class1
1
In fairness, there already exists in the Standard Library the class std::complex
7. The complex type
class complex {
public:
complex(double re,
double im): re(re), im(im) {}
private:
double re;
double im;
};
8. The complex type
We can now define values of of type complex:
complex a(3, 5);
complex b(7, 1);
10. Suppor&ng addi&on
It seems reasonable to add a member func*on named plus
class complex {
public:
... plus (...);
};
11. Suppor&ng addi&on
From mathema*cs, we know that adding two complex values x
and y results in a new complex value z
class complex {
public:
complex plus(...);
};
12. Suppor&ng addi&on
Moreover, adding two complex values x and y does not require
any change in either x or y
class complex {
public:
complex plus(complex const& y);
};
14. Suppor&ng addi&on
We can now add together two complex values
complex a(3, 5);
complex b(7, 1);
complex c = a.plus(b);
15. Syntac'c noise
Although the above solu.on works, highly-nested expressions
might be difficult to parse due to syntac'c noise
a.plus(b.plus(c)).plus(d);
19. Conven&onal nota&on
A"er all, such an expression is the result of hundreds of years of
experience with mathema/cal nota/on
(a + (b + c)) + d;
20. Operators on built-in types
This is why C++ supports a set of operators for its built-in types
float a = 2, b = 3,
c = 1, d = 10;
(a + (b + c)) + d;
21. Operators on UDTs
However, most concepts for which operators are conven3onally
used are not built-in types
22. Operators on UDTs
Just to name a few, the primary way of interac4ng with matrices
and complex numbers is through the use of operators on them
26. Language of the problem domain
Users of our class can then program in the language of the problem
domain, rather than in the language of the machine
complex a(3, 5);
complex b(7, 1);
complex c = a + b; // a.plus(b);
28. Defining operator+
Hence, we can overload operator + as follows:
class complex {
...
complex operator+(complex const& y);
};
29. Defining operator+
From an implementa-on viewpoint, operator+ does not differ
from our previous plus func-on
complex operator+(complex const& y) {
return complex(re + y.re,
im + y.im);
}
30. Operator func-ons
An operator func-on can be called like any other func-on2
complex c = a + b; // shorthand
complex c = a.operator+(b); // explicit call
2
However, note that only operators on user-defined types can be explicitly invoked. That is, we cannot do
int a = 3; int b = a.operator+(5);
31. The complex type
class complex {
public:
complex(double re,
double im): re(re), im(im) {}
complex operator+(complex const& y) {...}
private:
double re;
double im;
};
33. Adding complexes and doubles
What happens when we try to do the following?
complex a(3, 5);
complex c = a + 2.3;
34. Adding complexes and doubles
We incur in a compile-)me error
complex a(3, 5);
// error: no match for 'operator+'
// (operand types are 'complex' and 'double')
complex c = a + 2.3;
35. Mixed-mode addi+on
We never defined addi+on between complex and double values
// error: no match for 'operator+'
complex c = a + 2.3;
36. An overload for doubles
We introduce an addi-onal overload for the specific case of right-
hand side operands of type double3
complex operator+(double const& y);
3
Here, we decided to use a pass-by-const-reference approach to stress the fact that addi7on is a non-muta7ng
opera7ons for both the operands. However, pass-by-value would have been an equally acceptable solu7on
37. An overload for doubles
We introduce an addi-onal overload for the specific case of right-
hand side operands of type double3
complex operator+(double const& y) {
return complex(re + y, im);
}
3
Here, we decided to use a pass-by-const-reference approach to stress the fact that addi7on is a non-muta7ng
opera7ons for both the operands. However, pass-by-value would have been an equally acceptable solu7on
38. An overload for doubles
Apparently, we can now perform mixed-mode arithme6c
complex a(3, 5);
complex c = a + 2.3; // it now compiles!
39. Commuta'vity of addi'on
However, users of our class expect addi4on to be commuta've
complex a(3, 5);
(a + 2.3) == (2.3 + a); // true!
40. Adding doubles and complexes
What happens if we do the following?
complex a(3, 5);
complex c = 2.3 + a;
41. Adding doubles and complexes
complex a(3, 5);
// error: no match for 'operator+'
// (operand types are 'double' and 'complex')
complex c = 2.3 + a;
42. Adding doubles and complexes
If double were a class, we could write a version of operator+
tailored for right-hand side operands of type complex
struct double {
...
complex operator+(complex const& y);
};
43. Non-member operator func0ons
Given that double is in fact a built-in type, we need an alterna4ve
way of defining addi4on with complex values
44. Non-member operator func0ons
For any binary operator ~, a~b can be interpreted as either
• a.operator~(b), or
• operator~(a, b)4
4
With the no*ceably excep*on, as we will see, of the assignment operator
45. Non-member operator func0ons
That is, a binary operator can be defined by either
• a member func*on taking one argument, or
• a non-member func1on taking two arguments
46. Adding doubles and complexes
The resul)ng non-member operator func)on is as follows:
complex operator+(double const& x, complex const& y);
48. Non-member operator func0ons
Intui&vely, we would like to write the following
complex operator+(double const& x, complex const& y) {
return complex(y.re + x, y.im);
}
49. Non-member operator func0ons
Since we are wri*ng a non-member func*on, we cannot directly
access the private members y.re and y.im
complex operator+(double const& x, complex const& y) {
return complex(y.re + x, y.im);
}
50. Non-member operator func0ons
Two solu(ons to this problem:
• Declare the non-member operator as a friend of the class
• Provide complex with access func9ons
51. Declaring func-ons as friends
The friend declara*on grants a func*on access to private
members of the class in which such a friend declara*on appears
56. Non-member operator func0on
How to use our new access func.ons in order to implement
operator+?
complex operator+(double const& x, complex const& y);
57. Non-member operator func0on
How to use our new access func.ons in order to implement
operator+?
complex operator+(double const& x, complex const& y) {
return complex(x + y.real(), y.imag());
}
58. Non-member operator func0on
Unfortunately, our solu/on does not compile
// error: member function 'real' not viable:
// 'this' argument has type 'const complex',
// but function is not marked const
59. Const-correctness
Since we know that addi.on is a non-muta.ng opera.ons, we
correctly marked x and y as const
complex operator+(double const& x, complex const& y) {
return complex(x + y.real(), y.imag());
}
60. Const-correctness
However, we did not inform the compiler that the access func6ons
real() and imag() will not modify either y.re or y.im
61. Const-correctness
Hence, we cannot invoke either real() or imag() on a const
complex value
complex const a(3, 5);
std::cout << a.real(); // compile-time error!
std::cout << a.imag(); // compile-time error!
62. Const access func,ons
In order to do so, we mark as const both real() and imag()
class complex {
public:
...
double real() const { return re; }
double imag() const { return im; }
};
63. Constant operator func.ons
Moreover, we no*ce that we can do the same for the two member
variants of operator+
class complex {
public:
...
complex operator+(complex const& y) const {...}
complex operator+(double const& y) const {...}
};
64. Constant operator func.ons
This allows us to enforce that addi2on is a non-muta(ng
opera2ons for both the operands
class complex {
public:
...
complex operator+(complex const& y) const {...}
complex operator+(double const& y) const {...}
};
69. Equality
We get yet another compile-)me error
complex a(3, 5);
// error: invalid operands to binary expression
// ('complex' and 'complex')
(a + 2.3) == (2.3 + a);
70. Equality
This is because we never defined equality between complex
values
complex a(3, 5);
a == a;
72. Overloading operator==
Specifically, we opt for the non-member version of operator== in
order to enforce the symmetry of equality
bool operator==(complex const& x, complex const& y);
73. Overloading operator==
Fortunately, the implementa1on of operator== is straigh5orward
bool operator==(complex const& x, complex const& y) {
return x.real() == y.real() &&
x.imag() == y.imag();
}
75. Inequality
Therefore, it is not sufficient to overload equality. We must
overload inequality as well
bool operator!=(complex const& x, complex const& y);
76. Inequality
Therefore, it is not sufficient to overload equality. We must
overload inequality as well
bool operator!=(complex const& x, complex const& y) {
return !(x == y);
}
81. I/O operators
Besides the I/O of built-in types and std::strings, iostream
allows programmers to define I/O for their own types
complex a(3, 5);
std::cout << a;
82. I/O operators
I/O on user-defined types is possible by overloading, respec9vely,
operator<< and operator>>
83. Output operator
Let us focus on the output operator operator<<
complex a(3, 5);
std::cout << a;
85. Non-member output operator
Since our type appears as the right-hand side operands, we need
to specify a non-member operator func4on
void operator<<(..., complex const& x);
86. Non-member output operator
Given that std::cout is a global object of type std::ostream,
and that outpu2ng is a muta-ng opera5on, we obtain
void operator<<(std::ostream& os, complex const& x);
87. Non-member output operator
Apparently, the following suffices
void operator<<(std::ostream& os, complex const& x) {
os << x.real() << " + "
<< x.imag() << "i";
}
94. User-defined literals
In addi'on, with C++11 and above we can define literals for user-
defined types
// 3.5i is a user-defined literal
complex a = 3.5i;
97. Literal operators
The literal operator is a non-member func4on named operator""
followed by the suffix5
complex operator"" i(long double x) {
return complex(0, x);
}
5
Note that, C++14 introduced the i literal suffix to match the std::complex type. Therefore, in real code we
should not overload it manually
98. Language of the problem domain
We can now write
complex a = 7.1 + 3.5i;
std::cout << a;
99. Language of the problem domain
For the case of complex values, our new user-defined literal helps
us ge8ng even closer to the language of the problem domain
complex a = 7.1 + 3.5i;
std::cout << a;
101. Bibliography
• B. Stroustrup, The C++ Programming Language (4th
ed.)
• B, Stroustrup, Programming: Principles and Prac@ce
Using C++ (2nd
ed.)
• C++ Reference, Operator overloading
• ISO C++, C++ FAQ