Concept explainers
Operator overloading:
- In C++
programming , operator overloading defines an operators as user defined classes and it performs the operations with one or more variables together. - When an overloaded operator is defined as the user-defined type for executing the operations, it should be defined as a member function. So, it will help to invoke the operands.
- For manipulating data of the primitive data types, the C++ gives many operators.
Overloaded “[]” operator:
Overloaded operator contains many operator, the “[]” operator is the one of the type.
- The Overloaded “[]” operator is used to access the array value.
- It gives the ability to write a class that has an array like format.
Example:
Consider the example of overloaded “[]” operator is as follows:
// Include the header files
#include <iostream>
using namespace std;
// constant array size
const int S = 5;
// Declaration of the "Sample" class
class Sample
{
//access specifier
private:
//declare the variable
int a[S];
//access specifier
public:
//condtructor
Sample()
{
//declare the variable
int i;
//check the condition
for(i = 0; i < S; i++)
{
//set the value
a[i] = i;
}
}
//definition of overloaded "[]" operator
int &operator[](int i)
{
//check the condition
if( i >= S )
{
//display the error message
cout << "Index out of bounds" <<endl;
// return first element.
return a[0];
}
//otherwise
else
{
// return the element.
return a[i];
}
}
};
//main method
int main()
{
//create the object for the "Sample" class
Sample x;
//display the output
cout << "x[2] value is : " << x.operator[](2) <<endl;
cout << "x[5] value is : " << x.operator[](5)<<endl;
//return statement
return 0;
}
Want to see the full answer?
Check out a sample textbook solutionChapter 11 Solutions
STARTING OUT WITH C++ MPL
- PPM (Portable Pixmap) use three integers to represent a pixel – this means we can have images with RGB colors. You will create a Pixel class in C++ which has three attributes: red: int green: int blue: int You will create a default constructor that initializes those values to 255, and an overloaded constructor that takes user input to assign the values. The class will also have the following functions: changeRGB (): Takes in three integers to update the red, green, and blue attributes. Returns nothing. printRGB (): Takes in nothing. Prints the red, green, and blue attributes in order with a single space in-between each value. Returns nothing. You will then recreate the art program from Assignment 5 with the following changes: Instead of a 2D array of integers, you will create a 2D array of Pixel object. Don’t be scared! This is similar to creating a 2D array of strings. You will prompt for three color values instead of one – red, green, and blue. These must be stored in a Pixel…arrow_forwardC++ You may work on a single class. The parameter and return type s of each function and class member function should be decided in advance. The program will be best implemented as a multi-file program, (header file, the main program,..) Design a generic class to hold the following information about a bank account: Balance Number of deposits this month Number of withdrawals Annual Interest Rate Monthly service charges The class should have the following member function: Constructors Accepts arguments for the balance and annual interest rate. deposit a virtual function that accepts an argument for the amount of the deposit. The function should add the argument to the account balance. It should also increment the variable holding the number of deposits. withdraw a virtual function that accepts an argument for the amount of the withdrawal. The function should subtract the argument from the account balance. It should also increment the variable…arrow_forwardGiven the code:class DigitalWallet {private; long *id; // wallet id long *accounts; // dynamic array of account numbers int numAccounts; // number of user accounts in the array}1. Write a function definition for a Constructor to initialize all data members.2. Write a function definition for the Copy Constructor.3. Write a function definition for the Destructor.arrow_forward
- 1 def all_fluffy(s: str) -> bool: 2 """Return True iff every letter in s is fluffy. Fluffy letters are those 3. that appear in the word 'fluffy'. 4 #TODO: Add at least one example to the docstring and complete the body 7 8 9 10 #TODO: Now complete the function bodyarrow_forwardC++: OOP---Please comment the OOP concept. Thank you!arrow_forwardC++ help. In the class definition, initialize the data members, string type and integer age, with the default values "Unstated" and 0, respectively. Ex: If the input is mouse 13, then the output is: Type: Unstated, Age: 0 Type: mouse, Age: 13 Note: The class's print function is called first after the default constructor, then again after the inputs are passed to the setters.''' #include <iostream>#include <string>using namespace std; class Animal { public: void SetType(string animalType); void SetAge(int animalAge); void Print(); private: /* Your code goes here */ }; void Animal::SetType(string animalType) { type = animalType;} void Animal::SetAge(int animalAge) { age = animalAge;} void Animal::Print() { cout << "Type: " << type << ", Age: " << age << endl;} int main() { string newType; int newAge; Animal myAnimal; myAnimal.Print(); cin >> newType; cin >> newAge;…arrow_forward
- 1.Write the function heading of an overloaded * operator that multiplies two objects of the myArray class (the usage would be lhs * rhs) and returns a value of type myArray.arrow_forwardC++arrow_forwardC++ Q2 5 Declare a class named complex with two data members x (int) and y (int). This class contains an operator overloading function to subtract two complex objects.arrow_forward
- C++ codearrow_forwardin c++: Implement the Array class that is defined below and test it in the main program. The main program must test all the member functions including the overloaded operators that are defined in the class: #ifndef array_h #define array_h #include <iostream> using namespace std; class Array { // Class declaration friend const Array operator+(const Array & a1, const Array &a2); friend bool operator==(const Array & a, const Array &b);//Equality test public: Array(int = 10); //Initialize the array with 0 values, default size =10 Array(const Array & a); // copy constructor ~Array();//Destructor int getSize();// return the size of the array. const Array & operator=(const Array & a);//assignement operator Array operator+(int x);//+ operator bool operator!=(const Array & a) const;//Not equal test void read(); void print(); Array operator-();//Negate (unary operation)…arrow_forwardWhat is returned by the function that overloads the operator << for a class?arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education