
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ program to overload extraction operator
Suppose we have a Person class with two attributes first_name and the last_name. It also has two methods called get_first_name() and get_last_name() to retrieve or set first name and last name respectively. We shall have to overload the extraction operator (<<) to print the first name and the last name to print them using cout statement.
So, if the input is like a person object with first name and last name ("Sumit", "Ray"), then the output will be First name − Sumit, Last name − Ray.
To solve this, we will follow these steps −
To overload extraction operator, it should be defined outside the class
The return type will be an ostream reference
The input parameters are an ostream reference variable os, and object reference variable
using os extract all parts of the object in proper order
return os object reference.
Example
Let us see the following implementation to get better understanding −
#include <iostream> using namespace std; class Person { private: string f_name; string l_name; public: Person(string first_name, string last_name) : f_name(first_name), l_name(last_name) {} string& get_first_name() { return f_name; } string& get_last_name() { return l_name; } }; ostream& operator<<(ostream& os, Person& p) { os << "First name: " << p.get_first_name() << ", Last name: " << p.get_last_name(); return os; } int main(){ Person p("Sumit", "Ray"); cout << p << ", he is our member."; }
Input
p("Sumit", "Ray")
Output
First name: Sumit, Last name: Ray, he is our member.
- Related Articles
- C++ program to overload addition operator to add two matrices
- C++ program to overload addition operator to add two complex numbers
- How to overload python ternary operator?
- Overload unary minus operator in C++?
- How do I overload the [] operator in C#?
- How to overload Python comparison operators?
- How to create function overload in TypeScript?
- Java Program to use == operator to compare enums
- Different ways to overload a method in Java
- Python – Ordered tuples extraction
- What is Data Extraction?
- Can we overload Java main method?
- Java program to swap two numbers using XOR operator
- C++ Program to Subtract Complex Number using Operator Overloading
- Java Program to Differentiate String == operator and equals() method
