Operator overloading allows operators like +, -, *, etc. to be redefined to work on user-defined types like classes. This is done by defining member functions for the operators. For example, to overload + to add two Distance objects, a member function Distance operator+(Distance) would be defined. Overloading operators allows user-defined types to be used in expressions like built-in types for a more natural interface. Some common operators that can be overloaded include arithmetic, relational, logical, and assignment operators. There are some restrictions like not changing operator precedence or number of operands.
This document discusses operator overloading in C++. It covers introducing operator overloading, the 'this' pointer, syntax of operator overloading, restrictions on operator overloading, implementing operator overloading as member and non-member functions, overloading unary and binary operators, overloading relational operators, and data conversion. Examples are provided to demonstrate overloading operators like +, -, <, and implementing them as member and non-member functions.
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
This document discusses operator overloading in C++. It begins by defining operator overloading as giving special meanings to operators for user-defined data types. It then covers overloading unary and binary operators using member functions and friend functions. Some key points include: only existing operators can be overloaded, binary operators take operands as arguments, and type conversions between basic and user-defined types require custom conversion routines like constructors or casting functions. The document also provides examples of overloading operators for complex numbers and strings.
The document discusses different types of storage classes in C++ that determine the lifetime and scope of variables:
1. Local variables are defined inside functions and have scope limited to that function. They are destroyed when the function exits.
2. Global variables are defined outside all functions and have scope in the entire program. They are destroyed when the program ends.
3. Static local variables are local variables that retain their value between function calls. Register variables are local variables stored in processor registers for faster access.
4. Thread local storage allows defining variables that are local to each thread and retain their values similar to static variables. The document provides examples to illustrate local, global, and static variables.
The document discusses C++ functions. It defines what functions are and their uses in breaking down problems into smaller tasks. There are two types of functions: standard functions that are part of the C++ language and user-defined functions. A function has a signature defining its return type and parameters. Functions are declared and defined in two steps - declaration and implementation. Data can be shared between functions through parameters, which come in two varieties: value parameters that copy argument values, and reference parameters that can modify the original argument values.
This document discusses operator overloading in C++. It defines operator overloading as polymorphism that gives user-defined meaning to operators when used with custom data types. It provides examples of overloading operators like + for addition of integers and strings. It lists operators that cannot be overloaded and discusses implementing operator overloading using member, non-member, and friend functions. Finally, it provides rules for operator overloading such as preserving precedence and arity of operators.
Operator overloading allows operators like +, -, *, etc. to be redefined to work on user-defined types like classes. This is done by defining member functions for the operators. For example, to overload + to add two Distance objects, a member function Distance operator+(Distance) would be defined. Overloading operators allows user-defined types to be used in expressions like built-in types for a more natural interface. Some common operators that can be overloaded include arithmetic, relational, logical, and assignment operators. There are some restrictions like not changing operator precedence or number of operands.
This document discusses operator overloading in C++. It covers introducing operator overloading, the 'this' pointer, syntax of operator overloading, restrictions on operator overloading, implementing operator overloading as member and non-member functions, overloading unary and binary operators, overloading relational operators, and data conversion. Examples are provided to demonstrate overloading operators like +, -, <, and implementing them as member and non-member functions.
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
This document discusses operator overloading in C++. It begins by defining operator overloading as giving special meanings to operators for user-defined data types. It then covers overloading unary and binary operators using member functions and friend functions. Some key points include: only existing operators can be overloaded, binary operators take operands as arguments, and type conversions between basic and user-defined types require custom conversion routines like constructors or casting functions. The document also provides examples of overloading operators for complex numbers and strings.
The document discusses different types of storage classes in C++ that determine the lifetime and scope of variables:
1. Local variables are defined inside functions and have scope limited to that function. They are destroyed when the function exits.
2. Global variables are defined outside all functions and have scope in the entire program. They are destroyed when the program ends.
3. Static local variables are local variables that retain their value between function calls. Register variables are local variables stored in processor registers for faster access.
4. Thread local storage allows defining variables that are local to each thread and retain their values similar to static variables. The document provides examples to illustrate local, global, and static variables.
The document discusses C++ functions. It defines what functions are and their uses in breaking down problems into smaller tasks. There are two types of functions: standard functions that are part of the C++ language and user-defined functions. A function has a signature defining its return type and parameters. Functions are declared and defined in two steps - declaration and implementation. Data can be shared between functions through parameters, which come in two varieties: value parameters that copy argument values, and reference parameters that can modify the original argument values.
This document discusses operator overloading in C++. It defines operator overloading as polymorphism that gives user-defined meaning to operators when used with custom data types. It provides examples of overloading operators like + for addition of integers and strings. It lists operators that cannot be overloaded and discusses implementing operator overloading using member, non-member, and friend functions. Finally, it provides rules for operator overloading such as preserving precedence and arity of operators.
This document discusses operator overloading in C++. It defines operator overloading as polymorphism that gives user-defined meaning to operators when used with custom data types. Almost any operator can be overloaded except a few like :: and sizeof. Overloaded operators can be implemented as member functions, non-member functions, or friend functions. There are also rules for operator overloading, such as preserving precedence and arity of operators and requiring certain operators like [] and -> to be member functions. The document provides examples of overloading unary and binary operators as member and friend functions.
Operator overloading allows operators like + and << to be used with user-defined types by defining corresponding member functions. For example, the + operator can be overloaded to add two Distance objects by defining the member function operator+. This makes code more readable compared to explicit function calls. Overloading unary operators like ++ requires defining operator++(), while overloading binary operators like + requires defining both operator+() and operator+=(). The return type and arguments of overloaded operators must match the conventional operator.
The document provides information about C++ aptitude and object-oriented programming (OOP) concepts. It contains sample C++ code snippets and questions with explanations to test understanding of topics like classes, inheritance, polymorphism, operator overloading, templates, and more.
This document discusses object-oriented programming concepts in C++ including polymorphism, virtual functions, pure virtual functions, and abstract classes. It covers topics such as function overloading, operator overloading, virtual base classes, virtual functions, and pure virtual functions. It provides examples of overloading unary and binary operators using member functions and friend functions. It also explains the differences between virtual functions and pure virtual functions, and how abstract classes are used with pure virtual functions.
Operator overloading allows operators like + and - to have different implementations depending on the types of their operands. It allows user-defined types to be manipulated using the same syntax as built-in types. The document discusses various aspects of operator overloading like overloading unary, binary, and stream insertion/extraction operators. It also covers type conversions between basic and user-defined types using constructors and conversion functions. Restrictions on which operators can be overloaded and how different conversion scenarios are handled are explained.
The document provides details of programs to be implemented in C++ and Java as part of an Object Oriented Programming lab. The C++ programs include implementations of inline function overloading, complex numbers using operator overloading, friend functions, string concatenation using dynamic memory allocation, type conversion using complex numbers, managing bank accounts using inheritance, and a stack class with exception handling. The Java programs include writing simple programs, palindrome checking using strings, interfaces, inheritance, exception handling, and multithreaded programs.
power point presentation on object oriented programming functions conceptsbhargavi804095
The document discusses C++ functions. It covers the following key points in 3 sentences:
Standard functions that are included with C++ like math functions are discussed as well as how to define user-defined functions. User-defined functions are defined with a function header, parameters, and body. Functions can share data through parameters, either by value or by reference, and variables can have local or global scope.
The document discusses passing objects as arguments to functions in C++. It can be done in two ways - by value using a copy of the object or by reference passing the address. The sample program demonstrates passing two height objects to a sum function that adds their feet and inches values. The function receives the objects by value, performs the calculation, and outputs the total height.
The document discusses operator overloading in C++. It defines operator overloading as giving normal C++ operators like +, -, etc. additional meanings when applied to user-defined data types. It categorizes operators as unary and binary. It lists the operators that can and cannot be overloaded and provides examples of overloading unary, binary, and assignment operators. The document also discusses automatic and user-defined type conversion between basic and user-defined types.
The document discusses C++ functions. It explains that functions allow code to be reused by grouping common operations into reusable blocks of code called functions. Functions have three parts: a prototype that declares the function, a definition that implements it, and calls that execute the function. Functions can take parameters as input and return a value. Grouping common code into well-named functions makes a program more organized and maintainable.
The document discusses functions in C programming. It covers defining and calling functions, passing arguments to functions, return statements, and different types of functions. Some key points include:
- Functions make code modular and reusable. Arguments can be passed by value or reference.
- A function is defined with a return type, name, and parameters. It is called by name with arguments. Return passes data back to the calling function.
- Functions can take arguments and return values, take arguments but not return, return values without arguments, or do neither.
- Arguments are passed right to left in C. Functions can be nested by calling one function from another.
The document discusses C functions. Some key points:
1. Functions allow breaking code into reusable chunks that perform specific tasks. The main() function is required in every C program.
2. Functions are declared with a return type, name, and parameters. Definitions include the function body.
3. Standard library functions like strcat() and memcpy() are pre-defined for common tasks.
4. Functions are called by name and pass arguments by value or reference. Parameters allow customizing a function's behavior.
5. Recursion allows a function to call itself, enabling solutions to problems like factorials and Fibonacci sequences.
The document discusses functions in C++. It defines functions as modules that can be called to perform tasks and structure programs. Functions may take arguments as input and return values. Well-defined functions have a prototype specifying argument and return types. The document provides examples of built-in functions like sqrt() as well as user-defined functions. It discusses function syntax, calling and defining functions, and variable scope within and outside of functions.
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.
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY GOOD WORK NICE FORMULA OR SOMETHING LIKE THAT, BUT ACTULLY HE CAN USE. THANK YOU.
Hartleys Function Code
Contains unread posts
Actions for Hartleys Function Code
Chad Hartley posted Nov 5, 2015 5:10 PM
Subscribe
This program will add an integer number and a decimal number up to 2 decimal places. I have included notes in the code to explain what each thing does. I hope I did this right. It compiles successfully.
PseudoCode
Start
Declare int O1; Stands for Output1
O1=sum; Sum is the functions name
Int sum()
Declare variables
Int num1;
Float num2;
Write “Enter a number.”
Scanf num1
Write”Enter a decimal number.”
Scanf num2
Return num1+num2
end
C Code
#include <stdio.h>
int sum();//prototype
int main()//calling program
{
//Declare a varaiable
int O1;
O1=sum();//main is calling sum one time.
//if I listed this twice it would run the function 'sum' twice.
// Example: if I add a new int (int O1, O2) and declare O2 to
//be O2=sum then the function would run twice.
}
int sum ()//function 'sum'
{
int num1;// Declare intergers/variables
float num2;
printf("Enter a number.\n");
scanf("%d",&num1);// Take first input and assign it to num1
printf("Enter a decimal number.\n");
scanf("%.2f",&num2);
//Can use the printf statement but when you are calling an integer you can use the return.
//printf("The sum of %d, %d, is %d", num1,num2,num1+num2);
return num1+num2;
}
ADD COMMENT HERE
Chaotic Function
Contains unread posts
Actions for Chaotic Function
Joshua Ray posted Nov 5, 2015 2:33 PM
Subscribe
float tmp
int i
function float chaos(float num)
{
for i < 20
num = 3.9*num*(1-num)
print num
}
main
print "Program description"
print "Request input btw 0 and 1"
tmp = input
chaos(tmp)
/*
* File: main.c
* Author: JaiEllRei
*
* Created on November 5, 2015, 2:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
float chaos(float num);
int main(void)
{
float tmp;
printf("This program illustrates a choatic function. \n");
printf("Input a number between 0 and 1: ");
scanf("%f", &tmp);
chaos(tmp);
}
float chaos(float num)
{
for (int i=0; i<20; i++){
/*Chaotic Formula*/
num = 3.9 * num * (1-num);
printf("%.3f \n", num);
}
}
This program illustrates a choatic function.
Input a number between 0 and 1: .2
0.624
0.915
0.303
0.824
0.566
0.958
0.156
0.514
0.974
0.098
0.345
0.881
0.409
0.943
0.210
0.647
0.891
0.379
0.918
0.293
ADD COMMENT HERE
//MPH to KPH Conversion Function
Function KPHConv(value) as float
Set KPHConv = value*1.609344
End Function
Pseudocode for simple conversion program calling function
//Declare function
// MPH to KPH Conversion Function
Functio ...
The document discusses C++ interview questions and answers related to classes, inheritance, pointers, references, and operator overloading. It provides code examples to demonstrate concepts like passing objects by value vs reference, virtual functions, and inheritance. The examples are tested on Turbo C++, Microsoft VC++ compilers under Windows environment on x86 systems.
Functions allow programmers to organize and reuse code. There are two types of functions: library functions provided by C++ and user-defined functions created by the programmer. Functions communicate by passing arguments and returning values. Key concepts for functions include declaration, definition, call, pass by value, pass by reference, and pointers. Virtual functions allow for runtime polymorphism by calling the correct overridden function based on the object's type.
Functions allow programmers to organize C++ code into reusable blocks of statements. There are two types of functions: library functions provided in header files and user-defined functions created by the programmer. Functions communicate by passing arguments, which requires function declaration, definition, and calls. Pointers and references allow functions to modify argument values or share data. Virtual functions enable runtime polymorphism in inheritance hierarchies.
Operator overloading allows programmers to define special member functions to customize the behavior of operators (like +, -, etc.) for user-defined types. It can be implemented through member functions, non-member functions, or friend functions. Inline functions replace function calls with the function code directly, which can improve performance for short functions.
This document discusses operator overloading in C++. It defines operator overloading as polymorphism that gives user-defined meaning to operators when used with custom data types. Almost any operator can be overloaded except a few like :: and sizeof. Overloaded operators can be implemented as member functions, non-member functions, or friend functions. There are also rules for operator overloading, such as preserving precedence and arity of operators and requiring certain operators like [] and -> to be member functions. The document provides examples of overloading unary and binary operators as member and friend functions.
Operator overloading allows operators like + and << to be used with user-defined types by defining corresponding member functions. For example, the + operator can be overloaded to add two Distance objects by defining the member function operator+. This makes code more readable compared to explicit function calls. Overloading unary operators like ++ requires defining operator++(), while overloading binary operators like + requires defining both operator+() and operator+=(). The return type and arguments of overloaded operators must match the conventional operator.
The document provides information about C++ aptitude and object-oriented programming (OOP) concepts. It contains sample C++ code snippets and questions with explanations to test understanding of topics like classes, inheritance, polymorphism, operator overloading, templates, and more.
This document discusses object-oriented programming concepts in C++ including polymorphism, virtual functions, pure virtual functions, and abstract classes. It covers topics such as function overloading, operator overloading, virtual base classes, virtual functions, and pure virtual functions. It provides examples of overloading unary and binary operators using member functions and friend functions. It also explains the differences between virtual functions and pure virtual functions, and how abstract classes are used with pure virtual functions.
Operator overloading allows operators like + and - to have different implementations depending on the types of their operands. It allows user-defined types to be manipulated using the same syntax as built-in types. The document discusses various aspects of operator overloading like overloading unary, binary, and stream insertion/extraction operators. It also covers type conversions between basic and user-defined types using constructors and conversion functions. Restrictions on which operators can be overloaded and how different conversion scenarios are handled are explained.
The document provides details of programs to be implemented in C++ and Java as part of an Object Oriented Programming lab. The C++ programs include implementations of inline function overloading, complex numbers using operator overloading, friend functions, string concatenation using dynamic memory allocation, type conversion using complex numbers, managing bank accounts using inheritance, and a stack class with exception handling. The Java programs include writing simple programs, palindrome checking using strings, interfaces, inheritance, exception handling, and multithreaded programs.
power point presentation on object oriented programming functions conceptsbhargavi804095
The document discusses C++ functions. It covers the following key points in 3 sentences:
Standard functions that are included with C++ like math functions are discussed as well as how to define user-defined functions. User-defined functions are defined with a function header, parameters, and body. Functions can share data through parameters, either by value or by reference, and variables can have local or global scope.
The document discusses passing objects as arguments to functions in C++. It can be done in two ways - by value using a copy of the object or by reference passing the address. The sample program demonstrates passing two height objects to a sum function that adds their feet and inches values. The function receives the objects by value, performs the calculation, and outputs the total height.
The document discusses operator overloading in C++. It defines operator overloading as giving normal C++ operators like +, -, etc. additional meanings when applied to user-defined data types. It categorizes operators as unary and binary. It lists the operators that can and cannot be overloaded and provides examples of overloading unary, binary, and assignment operators. The document also discusses automatic and user-defined type conversion between basic and user-defined types.
The document discusses C++ functions. It explains that functions allow code to be reused by grouping common operations into reusable blocks of code called functions. Functions have three parts: a prototype that declares the function, a definition that implements it, and calls that execute the function. Functions can take parameters as input and return a value. Grouping common code into well-named functions makes a program more organized and maintainable.
The document discusses functions in C programming. It covers defining and calling functions, passing arguments to functions, return statements, and different types of functions. Some key points include:
- Functions make code modular and reusable. Arguments can be passed by value or reference.
- A function is defined with a return type, name, and parameters. It is called by name with arguments. Return passes data back to the calling function.
- Functions can take arguments and return values, take arguments but not return, return values without arguments, or do neither.
- Arguments are passed right to left in C. Functions can be nested by calling one function from another.
The document discusses C functions. Some key points:
1. Functions allow breaking code into reusable chunks that perform specific tasks. The main() function is required in every C program.
2. Functions are declared with a return type, name, and parameters. Definitions include the function body.
3. Standard library functions like strcat() and memcpy() are pre-defined for common tasks.
4. Functions are called by name and pass arguments by value or reference. Parameters allow customizing a function's behavior.
5. Recursion allows a function to call itself, enabling solutions to problems like factorials and Fibonacci sequences.
The document discusses functions in C++. It defines functions as modules that can be called to perform tasks and structure programs. Functions may take arguments as input and return values. Well-defined functions have a prototype specifying argument and return types. The document provides examples of built-in functions like sqrt() as well as user-defined functions. It discusses function syntax, calling and defining functions, and variable scope within and outside of functions.
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.
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY GOOD WORK NICE FORMULA OR SOMETHING LIKE THAT, BUT ACTULLY HE CAN USE. THANK YOU.
Hartleys Function Code
Contains unread posts
Actions for Hartleys Function Code
Chad Hartley posted Nov 5, 2015 5:10 PM
Subscribe
This program will add an integer number and a decimal number up to 2 decimal places. I have included notes in the code to explain what each thing does. I hope I did this right. It compiles successfully.
PseudoCode
Start
Declare int O1; Stands for Output1
O1=sum; Sum is the functions name
Int sum()
Declare variables
Int num1;
Float num2;
Write “Enter a number.”
Scanf num1
Write”Enter a decimal number.”
Scanf num2
Return num1+num2
end
C Code
#include <stdio.h>
int sum();//prototype
int main()//calling program
{
//Declare a varaiable
int O1;
O1=sum();//main is calling sum one time.
//if I listed this twice it would run the function 'sum' twice.
// Example: if I add a new int (int O1, O2) and declare O2 to
//be O2=sum then the function would run twice.
}
int sum ()//function 'sum'
{
int num1;// Declare intergers/variables
float num2;
printf("Enter a number.\n");
scanf("%d",&num1);// Take first input and assign it to num1
printf("Enter a decimal number.\n");
scanf("%.2f",&num2);
//Can use the printf statement but when you are calling an integer you can use the return.
//printf("The sum of %d, %d, is %d", num1,num2,num1+num2);
return num1+num2;
}
ADD COMMENT HERE
Chaotic Function
Contains unread posts
Actions for Chaotic Function
Joshua Ray posted Nov 5, 2015 2:33 PM
Subscribe
float tmp
int i
function float chaos(float num)
{
for i < 20
num = 3.9*num*(1-num)
print num
}
main
print "Program description"
print "Request input btw 0 and 1"
tmp = input
chaos(tmp)
/*
* File: main.c
* Author: JaiEllRei
*
* Created on November 5, 2015, 2:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
float chaos(float num);
int main(void)
{
float tmp;
printf("This program illustrates a choatic function. \n");
printf("Input a number between 0 and 1: ");
scanf("%f", &tmp);
chaos(tmp);
}
float chaos(float num)
{
for (int i=0; i<20; i++){
/*Chaotic Formula*/
num = 3.9 * num * (1-num);
printf("%.3f \n", num);
}
}
This program illustrates a choatic function.
Input a number between 0 and 1: .2
0.624
0.915
0.303
0.824
0.566
0.958
0.156
0.514
0.974
0.098
0.345
0.881
0.409
0.943
0.210
0.647
0.891
0.379
0.918
0.293
ADD COMMENT HERE
//MPH to KPH Conversion Function
Function KPHConv(value) as float
Set KPHConv = value*1.609344
End Function
Pseudocode for simple conversion program calling function
//Declare function
// MPH to KPH Conversion Function
Functio ...
The document discusses C++ interview questions and answers related to classes, inheritance, pointers, references, and operator overloading. It provides code examples to demonstrate concepts like passing objects by value vs reference, virtual functions, and inheritance. The examples are tested on Turbo C++, Microsoft VC++ compilers under Windows environment on x86 systems.
Functions allow programmers to organize and reuse code. There are two types of functions: library functions provided by C++ and user-defined functions created by the programmer. Functions communicate by passing arguments and returning values. Key concepts for functions include declaration, definition, call, pass by value, pass by reference, and pointers. Virtual functions allow for runtime polymorphism by calling the correct overridden function based on the object's type.
Functions allow programmers to organize C++ code into reusable blocks of statements. There are two types of functions: library functions provided in header files and user-defined functions created by the programmer. Functions communicate by passing arguments, which requires function declaration, definition, and calls. Pointers and references allow functions to modify argument values or share data. Virtual functions enable runtime polymorphism in inheritance hierarchies.
Operator overloading allows programmers to define special member functions to customize the behavior of operators (like +, -, etc.) for user-defined types. It can be implemented through member functions, non-member functions, or friend functions. Inline functions replace function calls with the function code directly, which can improve performance for short functions.
Similar to Object Oriented Programming using C++: Ch08 Operator Overloading.pptx (20)
An improved modulation technique suitable for a three level flying capacitor ...IJECEIAES
This research paper introduces an innovative modulation technique for controlling a 3-level flying capacitor multilevel inverter (FCMLI), aiming to streamline the modulation process in contrast to conventional methods. The proposed
simplified modulation technique paves the way for more straightforward and
efficient control of multilevel inverters, enabling their widespread adoption and
integration into modern power electronic systems. Through the amalgamation of
sinusoidal pulse width modulation (SPWM) with a high-frequency square wave
pulse, this controlling technique attains energy equilibrium across the coupling
capacitor. The modulation scheme incorporates a simplified switching pattern
and a decreased count of voltage references, thereby simplifying the control
algorithm.
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...IJECEIAES
Medical image analysis has witnessed significant advancements with deep learning techniques. In the domain of brain tumor segmentation, the ability to
precisely delineate tumor boundaries from magnetic resonance imaging (MRI)
scans holds profound implications for diagnosis. This study presents an ensemble convolutional neural network (CNN) with transfer learning, integrating
the state-of-the-art Deeplabv3+ architecture with the ResNet18 backbone. The
model is rigorously trained and evaluated, exhibiting remarkable performance
metrics, including an impressive global accuracy of 99.286%, a high-class accuracy of 82.191%, a mean intersection over union (IoU) of 79.900%, a weighted
IoU of 98.620%, and a Boundary F1 (BF) score of 83.303%. Notably, a detailed comparative analysis with existing methods showcases the superiority of
our proposed model. These findings underscore the model’s competence in precise brain tumor localization, underscoring its potential to revolutionize medical
image analysis and enhance healthcare outcomes. This research paves the way
for future exploration and optimization of advanced CNN models in medical
imaging, emphasizing addressing false positives and resource efficiency.
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
2. Introduction
Operator Overloading is one of the most exciting features of object oriented
programming.
It can transform complex, obscure program listings into intuitively obvious
ones. For example,
Statements like d3.addobjects(d1, d2); or the similar but equally obscure d3 =
d1.addobjects(d2); can be changed to the much more readable d3 = d1 + d2;
The rather forbidding term operator overloading refers to giving the normal
C++ operators, such as +, *, <=, and +=, additional meanings when they are
applied to user defined data types.
2
3. Introduction
Let’s start off by overloading a unary operator.
Unary operators act on only one operand. (An operand is simply a variable
acted on by an operator.)
Examples are the increment and decrement operators ++ and --, and the unary
minus, as in -33.
In Chapter 6, we created a class Counter to keep track of a count. Objects of
that class were incremented by calling a member function: c1.inc_count();
That did the job, but the listing would have been more readable if we could
have used the increment operator ++ instead: ++c1;
3
5. The operator Keyword
The keyword operator is used to overload the ++ operator in this declarator:
void operator ++ ()
The return type (void in this case) comes first, followed by the keyword
operator, followed by the operator itself (++), and finally the argument list
enclosed in parentheses (which are empty here).
This declarator syntax tells the compiler to call this member function whenever
the ++ operator is encountered, provided the operand (the variable operated
on by the ++) is of type Counter. If the operand is a basic type such as an int, as
in ++intvar; then the compiler will use its built-in routine to increment an int.
5
6. operator Arguments
In main() the ++ operator is applied to a specific object, as in the expression
++c1.
The operator ++() takes no arguments.
It increments the count data in the
object of which it is a member.
Since member functions can
always access the particular
object for which they’ve been
invoked.
6
7. operator Return Values
The operator ++() function in the program has a subtle defect. You will
discover it if you use a statement like this in main(): c1 = ++c2;
The compiler will complain. Because we have defined the ++ operator to have a
return type of void in the operator ++() function.
While in the assignment statement it is being asked to return a variable of type
Counter.
To make it possible to use our homemade operator ++() in assignment
expressions, we must provide a way for it to return a value.
The next program does that.
7
8. Example 2: Returning Values in Operator (1/2)
#include <iostream>
#include <stdlib.h>
using namespace std;
class Counter {
private:
int count; // define count attribute
public:
Counter() : count(0) { // make no argument constructor
}
int get_count() { // return value of count
return count;
}
Counter operator ++ () { // increment count
++count; // increment count
Counter temp; // make a temporary Counter
temp.count = count; // give it same value as this object
return temp; // return the copy
}
}; 8
14. Using Postfix Notation
In the program, We have two different declarations for overloading the ++
operator.
Declaration for prefix notation is Counter operator ++ ()
for postfix notation, is Counter operator ++ (int)
The only difference is the int in the parentheses.
This int isn’t really an argument, and it doesn’t mean integer.
It’s simply a signal to the compiler to create the postfix version of the operator.
14
15. Example 5: Overloading Binary Operators (1/3)
// englplus.cpp overloaded ‘+’ operator adds two Distances
#include <iostream>
#include <stdlib.h>
using namespace std;
class Distance { // English Distance class
private: int feet; float inches;
public:
Distance() : feet(0), inches(0.0) {} // constructor (no args)
Distance(int ft, float in) : feet(ft), inches(in) { } // constructor (two args)
void getdist() { // get length from user
cout << "nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() const { // display distance
cout << feet << "'-" << inches << '"';
}
Distance operator + (Distance) const; // add 2 distances
}; 15
16. Example 5: Overloading Binary Operators (2/3)
Distance Distance::operator + (Distance d2) const { // add this distance to d2 and return sum
int f = feet + d2.feet; // add the feet
float i = inches + d2.inches; // add the inches
if (i >= 12.0) { // if total exceeds 12.0,
i -= 12.0; // then decrease inches by 12.0 and
f++; // increase feet by 1
} // return a temporary Distance
return Distance(f, i); // initialized to sum
}
int main() {
Distance dist1, dist3, dist4; // define distances
dist1.getdist(); // get dist1 from user
Distance dist2(11, 6.25); // define, initialize dist2
dist3 = dist1 + dist2; // single ‘+’ operator
dist4 = dist1 + dist2 + dist3; // multiple ‘+’ operators
cout << "dist1 = "; dist1.showdist(); cout << endl;
cout << "dist2 = "; dist2.showdist(); cout << endl;
cout << "dist3 = "; dist3.showdist(); cout << endl;
cout << "dist4 = "; dist4.showdist(); cout << endl;
system("PAUSE"); return 0;
} 16
17. Overloading Binary Operators
Binary operators ( +, -, *, /, %, =, +=, -=, *=, /=, %=) can be overloaded just as
easily as unary operators.
In class Distance the declaration for the operator+() function looks like this:
Distance operator + ( Distance );
This function has a return type of Distance, and takes one argument of type
Distance.
In expressions like dist3 = dist1 + dist2; The argument on the left side of the
operator (dist1 in this case) is the object of which the operator is a member.
The object on the right side of the operator (dist2) must be furnished as an
argument to the operator.
The operator returns a value, which can be assigned or used in other ways; in
this case it is assigned to dist3.
17
19. Example 6: Concatenating String (1/3)
// strplus.cpp overloaded ‘+’ operator concatenates strings
#include <iostream>
#include <string.h> // for strcpy_s(), strcat()
#include <stdlib.h> // for exit()
using namespace std;
class String { // user-defined string type
private:
enum { SZ = 80 }; // we use enum for integer constants
char str[SZ]; // size of String objects holds a string
public:
String() { // no argument constructor
strcpy_s(str, "");
}
String(const char s[]) { // one argument constructor
strcpy_s(str, s);
}
void display() const { // display the String
cout << str;
} 19
20. Example 6: Concatenating String (2/3)
String operator + (String ss) const { // add Strings
String temp; // make a temporary String
if (strlen(str) + strlen(ss.str) < SZ) {
strcpy_s(temp.str, str); // copy this string to temp
strcat_s(temp.str, ss.str); // add the argument string
}
else {
cout << "n String overflow";
exit(1);
}
return temp; // return temp String
}
};
20
21. Example 6: Concatenating String (3/3)
int main() {
String s1 = "nEid Mubarak! "; // uses one arg. constructor
String s2 = "Happy new year!"; // uses one arg. constructor
String s3; // uses no arg. constructor
s1.display(); cout << endl; // display strings
s2.display(); cout << endl;
s3.display(); cout << endl;
s3 = s1 + s2; // add s2 to s1, then assign it to s3
s3.display(); // display s3
cout << endl;
system("PAUSE");
return 0;
}
21
22. Enumeration
An enumeration, introduced by the keyword enum and followed by a type
name (in our example, Status), is a set of integer constants represented by
identifiers.
The values of these enumeration constants start at 0, unless specified
otherwise, and increment by 1.
In the following example, the constant CONTINUE has the value 0, WON has
the value 1 and LOST has the value 2.
enum Status { CONTINUE, WON, LOST };
Another popular enumeration is
enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC };
22
23. Concatenating String
The + operator cannot be used to concatenate C-strings. That is, you can’t say
str3 = str1 + str2;
The program first displays three strings separately.
The third is empty at this point, so nothing is printed when it displays itself.
Then the first two strings are concatenated and placed in the third, and the
third string is displayed again.
The declarator String operator + (String ss) shows that the + operator takes one
argument of type String and returns an object of the same type.
The concatenation process in operator+() involves creating a temporary
object of type String, copying the string from our own String object into it,
concatenating the argument string using the library function strcat(), and
returning the resulting temporary string.
23
24. Concatenating String
Note that we can’t use the return String(string); approach, where a nameless
temporary String is created,
because we need access to the temporary String not only to initialize it, but
to concatenate the argument string to it.
We must be careful that we don’t overflow the fixed-length strings used in the
String class. To prevent such accidents in the operator+() function, we
check that the combined length of the two strings to be concatenated will not
exceed the maximum string length.
We’ve seen different uses of the + operator: to add English distances and to
concatenate strings. You could put both these classes together in the same
program, and C++ would still know how to interpret the + operator: It selects
the correct function to carry out the “addition” based on the type of operand.
24
25. Example 7: Overloading Comparison (<) Operator (1/2)
// overloaded '<' operator compares two Distances
#include <iostream>
using namespace std;
class Distance { // English Distance class
private:
int feet; float inches;
public:
Distance() : feet(0), inches(0.0) { } // constructor (no args)
Distance(int ft, float in) : feet(ft), inches(in) { } // constructor (two args)
void getdist() { // get length from user
cout << "nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() const { // display distance
cout << feet << "'-" << inches << '"';
}
bool operator < (Distance) const; // compare distances
}; 25
26. Example 7: Overloading Comparison (<) Operator (2/2)
bool Distance::operator < (Distance d2) const {
float bf1 = feet + inches / 12;
float bf2 = d2.feet + d2.inches / 12;
return bf1 < bf2;
}
int main() {
Distance dist1; // define Distance dist1
dist1.getdist(); // get dist1 from user
Distance dist2(6, 2.5); // define and initialize dist2
cout << "ndist1 = "; dist1.showdist(); // display distances
cout << "ndist2 = "; dist2.showdist();
if (dist1 < dist2) // overloaded '<' operator
cout << "ndist1 is less than dist2";
else
cout << "ndist1 is greater than (or equal to) dist2";
cout << endl;
system("PAUSE");
return 0;
}
26
27. Overloading Comparison (<) Operator
The approach used in the operator < () function is similar to overloading the +
operator, except that here the operator < () function has a return type of bool.
The return value is false or true, depending on the comparison of the two distances.
The comparison is made by converting both distances to floating-point feet, and
comparing them using the normal < operator.
Remember that the use of the conditional operator
return (bf1 < bf2) ? true : false;
is the same as
if(bf1 < bf2) return true;
else return false;
27
28. Example 8: Overloading Comparison (==) Operator (1/2)
// overloaded '==' operator compares strings
#include <iostream>
#include <string.h> // for strcmp()
using namespace std;
class String { // user-defined string type
private:
enum { SZ = 80 }; // size of String objects
char str[SZ]; // holds a string
public:
String() { // constructor, no args
strcpy_s(str, "");
}
String(const char *s) { // constructor, one arg
strcpy_s(str, s);
}
void display() const { // display a String
cout << str;
} 28
29. Example 8: Overloading Comparison (==) Operator (2/2)
void getstr() { // read a string
cin.get(str, SZ);
}
bool operator == (String ss) const { // check for equality
return !strcmp(str, ss.str);
}
};
int main() {
String s1 = "yes", s2 = "no", s3;
cout << "nEnter 'yes' or 'no': ";
s3.getstr(); // get String from user
if (s3 == s1) cout << "You typed yesn"; // compare with "yes"
else if (s3 == s2) cout << "You typed non"; // compare with "no"
else cout << "You didn’t follow instructionsn";
system("PAUSE");
return 0;
} 29
31. Example 9: Overloading Comparison (+=) Operator (2/2)
void Distance::operator += (Distance d2) { // add distance to this one
feet += d2.feet; // add the feet
inches += d2.inches; // add the inches
if (inches >= 12.0) { // if total exceeds 12.0,
inches -= 12.0; // then decrease inches by 12.0
feet++; // and increase feet by 1
}
}
int main() {
Distance dist1; // define dist1
dist1.getdist(); // get dist1 from user
cout << "ndist1 = "; dist1.showdist();
Distance dist2(11, 6.25); // define, initialize dist2
cout << "ndist2 = "; dist2.showdist();
dist1 += dist2; // dist1 = dist1 + dist2
cout << "nAfter addition,";
cout << "ndist1 = "; dist1.showdist();
cout << endl;
system("PAUSE"); return 0;
} 31
32. Arithmetic Assignment (+=) Operators
In the operator +=() function in program, the object that takes on the value
of the sum is the object of which the function is a member.
Thus it is feet and inches that are given values, not temporary variables used
only to return an object. The operator+=() function has no return value; it
returns type void.
A return value is not necessary with arithmetic assignment operators such as
+=, because the result of the assignment operator is not assigned to anything.
The operator is used alone, in expressions like the one in the program.
dist1 += dist2;
If you wanted to use this operator in more complex expressions, like
dist3 = dist1 += dist2;
then you would need to provide a return value (i.e. a distance object).
32
33. Example 10: Separate getel() and putel() Functions (1/2)
// creates safe array uses separate put and get functions
#include <iostream>
#include <process.h> // for exit()
using namespace std;
const int LIMIT = 100;
class safearay
{
private:
int arr[LIMIT];
public:
void putel(int n, int elvalue) { // set value of element
if (n < 0 || n >= LIMIT)
{
cout << "nIndex out of bounds";
system("PAUSE");
exit(1);
}
arr[n] = elvalue;
}
33
34. Example 10: Separate getel() and putel() Functions (2/2)
int getel(int n) const { // get value of element
if (n < 0 || n >= LIMIT) {
cout << "nIndex out of bounds";
system("PAUSE");
exit(1);
}
return arr[n];
}
};
int main() {
safearay sa1;
for (int j = 0; j < LIMIT; j++) // insert elements
sa1.putel(j, j * 10);
for (int j = 0; j < LIMIT; j++) { // display elements
int temp = sa1.getel(j);
cout << "Element " << j << " is " << temp << endl;
}
system("PAUSE");
return 0;
} 34
35. Ex 11: Single access() Function Returning by Reference (1/2)
// uses one access() function for both put and get
#include <iostream>
#include <process.h> // for exit()
using namespace std;
const int LIMIT = 100; // array size
class safearay
{
private:
int arr[LIMIT];
public:
int& access(int n) {
if (n < 0 || n >= LIMIT) {
cout << "n Index out of bounds";
system("PAUSE"); exit(1);
}
return arr[n];
}
}; 35
36. Ex 11: Single access() Function Returning by Reference (2/2)
int main()
{
safearay sa1;
for (int j = 0; j < LIMIT; j++) // insert elements
sa1.access(j) = j * 10; // *left* side of equal sign
for (int j = 0; j < LIMIT; j++) { // display elements
int temp = sa1.access(j); //*right* side of equal sign
cout << "Element " << j << " is " << temp << endl;
}
system("PAUSE");
return 0;
}
36
37. Ex 12: Overloaded [] Operator Returning by Reference (1/2)
// creates safe array, uses overloaded [] operator for both put and get
#include <iostream>
#include <process.h> // for exit()
const int LIMIT = 100; // array size
using namespace std;
class safearay
{
private:
int arr[LIMIT];
public:
int& operator [](int n) {
if (n < 0 || n >= LIMIT) {
cout << "n Index out of bounds";
exit(1);
}
return arr[n];
}
};
37
38. Ex 12: Overloaded [] Operator Returning by Reference (2/2)
int main()
{
safearay sa1;
for (int j = 0; j < LIMIT; j++) // insert elements
sa1[j] = j * 10; // *left* side of equal sign
for (int j = 0; j < LIMIT; j++) // display elements
{
int temp = sa1[j]; // *right* side of equal sign
cout << "Element " << j << " is " << temp << endl;
}
system("PAUSE");
return 0;
}
38
39. Ex 13: Conversion Between Objects and Basic Types (1/3)
// conversions: Distance to meters, meters to Distance
#include <iostream>
using namespace std;
class Distance { // English Distance class
private:
const float MTF; // meters to feet
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0), MTF(3.280833F) {
}
// constructor (one arg)
Distance(float meters) : MTF(3.280833F) { // convert meters to Distance
float fltfeet = MTF * meters; // convert to float feet
feet = int(fltfeet); // feet is integer part
inches = 12 * (fltfeet - feet); // inches is what’s left
}
39
41. Ex 13: Conversion Between Objects and Basic Types (3/3)
int main()
{
float mtrs;
Distance dist1 = 2.35F; // uses 1-arg constructor to convert meters to Distance
cout << "ndist1 = ";
dist1.showdist();
mtrs = static_cast<float>(dist1); // uses conversion operator
cout << "ndist1 = " << mtrs << " metersn"; // for Distance to meters
Distance dist2(5, 10.25); // uses 2-arg constructor
mtrs = dist2; // also uses conversion op
cout << "ndist2 = " << mtrs << " metersn";
// dist2 = mtrs; // error, = won’t convert
system("PAUSE");
return 0;
} 41
42. Ex 14: Conversion Between C-String and String Objects (1/2)
// conversion between ordinary strings and class String
#include <iostream>
#include <string.h> // for strcpy_s(), etc.
using namespace std;
class String { // user-defined string type
private:
enum { SZ = 80 }; // size of all String objects
char str[SZ]; // holds a C-string
public:
String() { str[0] = '0'; } // no-arg constructor
String(const char s[]) { // 1-arg constructor converts C-string to String Object
strcpy_s(str, s);
}
void display() const { // display the String
cout << str << endl;
}
operator char* () { // conversion operator converts String to C-string
return str;
}
}; 42
43. Ex 14: Conversion Between C-String and String Objects (2/2)
int main()
{
String s1; // uses no-arg constructor
char xstr[] = "Hello World "; // create and initialize C-string
s1 = xstr; // uses 1-arg constructor to convert C-string to String Object
s1.display(); // display String
String s2 = "Good Morning "; // uses 1-arg constructor to initialize String
cout << static_cast<char*>(s2); // use conversion operator to convert String to C-string
// before sending to << op
cout << endl;
system("PAUSE");
return 0;
}
43
44. Ex 15: Conversions Between Objects of Different Classes (1/3)
// converts from Polar Coordinates to Cartesian Coordinates
// using 1-Arg constructor in the Cartesian Class
#define M_PI 3.14159265358979323846 // value of pi
#include <math.h>
#include <iostream>
#include <string>
using namespace std;
class Polar
{ // for 2D Polar Coordinates
public:
double R; // Radius
double Theta; // Theta in Degrees
Polar() : R(0), Theta(0) { }
Polar(double R, double Theta) : R(R), Theta(Theta) { }
void Show() const {
cout << "R = " << R << ", Theta = " << Theta << " Degrees" << endl;
}
};
44
X
Y
r
θ
y
x
P(x,y) Cartesian
P(r,θ) Polar
45. Ex 15: Conversions Between Objects of Different Classes (2/3)
class Cartesian { // for 2D Cartesian Coordinates
public:
double X, Y;
Cartesian() : X(0), Y(0) { }
Cartesian(double X, double Y) : X(X), Y(Y) { }
Cartesian(Polar P) {
double r, t;
r = P.R; // Get Radius
t = P.Theta; // Get Theta
t *= M_PI / 180; // Convert Degrees to Radians
X = r * cos(t); // Calculate X
Y = r * sin(t); // Calculate Y
}
void Show() const {
cout << "X = " << X << ", Y = " << Y << endl;
}
};
45
X
Y
r
θ
y
x
P(x,y) Cartesian
P(r,θ) Polar
46. Ex 15: Conversions Between Objects of Different Classes (3/3)
int main() {
Polar Pol(5, 53.13); // R = 5, Theta = 53.13 Degrees
Cartesian Cat = Pol; // Convert Polar to Cartesian
Pol.Show(); // Show in Polar
Cat.Show(); // Show in Cartesian
system("PAUSE");
return 0;
}
46
47. Ex 16: Conversions Between Objects of Different Classes (1/3)
// converts from Polar Coordinates to Cartesian Coordinates using Operator Overloading in
// Polar Class
#define M_PI 3.14159265358979323846 //pi
#include <math.h>
#include <iostream>
#include <string>
using namespace std;
class Cartesian // A Class for 2D Cartesian Coordinates
{
public:
double X, Y;
Cartesian() : X(0), Y(0) { }
Cartesian(double X, double Y) : X(X), Y(Y) { }
void Show() const {
cout << "X = " << X << ", Y = " << Y << endl;
}
};
47
48. Ex 16: Conversions Between Objects of Different Classes (2/3)
class Polar { // for 2D Polar Coordinates
public:
double R; // Radius
double Theta; // Theta in Degrees
public:
Polar() : R(0), Theta(0) { }
Polar(double R, double Theta) : R(R), Theta(Theta) { }
void Show() const {
cout << "R = " << R
<< ", Theta = " << Theta << " Degrees" << endl;
}
operator Cartesian() const {
double x, y, t;
t = Theta * M_PI / 180; // Converts Degrees to Radians
x = R * cos(t);
y = R * sin(t);
return Cartesian(x, y);
}
}; 48
X
Y
r
θ
y
x
P(x,y) Cartesian
P(r,θ) Polar
49. Ex 16: Conversions Between Objects of Different Classes (3/3)
int main() {
Polar Pol(5, 53.13); // R = 5, Theta = 53.13 Degrees
Cartesian Cat = Pol; // Convert Polar to Cartesian
Pol.Show();// Show in Polar
Cat.Show();// Show in Cartesian
system("PAUSE");
return 0;
}
49
50. Preventing Conversions with explicit
You can call fancyDist() with arguments Distance variable is no problem.
you can also call fancyDist() with a variable of type float as the argument:
fancyDist(mtrs);
The compiler will realize it’s the wrong type and look for a conversion operator.
Finding a Distance constructor that takes type float as an argument, it will
arrange for this constructor to convert float to Distance and pass the Distance
value to the function.
This is an implicit conversion, one which you may not have intended to make
possible.
However, if we make the constructor explicit, we prevent implicit conversions.
You can check this by removing the comment symbol from the call to
fancyDist() in the program:
50
51. Preventing Conversions with explicit
The compiler will tell you it can’t perform the conversion. Without the explicit
keyword, this call is perfectly legal.
As a side effect of the explicit constructor, note that you can’t use the form of
object initialization that uses an equal sign Distance dist1 = 2.35F;
Whereas the form with parentheses works as it always has: Distance
dist1(2.35F);
Ordinarily, when you create a const object, you want a guarantee that none of
its member data can be changed. However, a situation occasionally arises
where you want to create const objects that have some specific member data
item that needs to be modified despite the object’s constness.
Let’s say we want to be able to create const scrollbars in which attributes
remain unchanged, except for their ownership. That’s where the mutable
keyword comes in. 51
53. Ex 17: Preventing Conversions with explicit (2/2)
int main(){
void fancyDist(Distance); //declaration
Distance dist1(2.35F); //uses 1-arg constructor to convert meters to Distance
// Distance dist1 = 2.35F; // ERROR if constructor is explicit
cout << "ndist1 = "; dist1.showdist();
float mtrs = 3.0F;
// fancyDist(mtrs); // ERROR if constructor is explicit
return 0;
}
void fancyDist(Distance d) {
cout << "(in feet and inches) = ";
d.showdist();
cout << endl;
}
53
54. Ex 18: Changing const Object Data Using mutable (1/2)
#include <iostream>
#include <string>
using namespace std;
class scrollbar {
private:
int size; // related to constness
mutable string owner; // not relevant to constness
public:
scrollbar(int sz, string own) : size(sz), owner(own){
}
void setSize(int sz) : size(sz) { } // changes size
void setOwner(string own) const { // changes owner
owner = own;
}
int getSize() const { // returns size
return size;
}
string getOwner() const { // returns owner
return owner;
}
}; 54
55. Ex 18: Changing const Object Data Using mutable (1/2)
int main()
{
const scrollbar sbar(60, "Window1");
// sbar.setSize(100); // can’t do this to const obj
sbar.setOwner("Window2"); // this is OK
// these are OK too
cout << sbar.getSize() << ", " << sbar.getOwner() << endl;
system("PAUSE");
return 0;
}
55