top of page

"this" keyword and Operator Overloading

  • koraylimancre
  • 14 Oca 2022
  • 1 dakikada okunur

Güncelleme tarihi: 2 May 2022

"this" keyword is a pointer to the current object. Use cases are shown below. It is widely used in c++. Operator overloading is a way of defining the behaviour of an operator which is not defined. In this example compiler doesn't know what to do with Dog = Snake. So we have to define the behaviour of = operator between Animal objects.

#include<string>
#include <iostream>

class Animal {
public:

	Animal(std::string Name, int Age, bool IsReptile)
	{
		this->Name = Name;
		this->Age = Age;                   ////////////////////////////////////////////
		this->IsReptile = IsReptile;
	}

	const Animal& operator= (const Animal& Rhs)
	{
		Age = Rhs.Age;
		Name = Rhs.Name;
		IsReptile = Rhs.IsReptile;
		std::cout << "Operator= ";
		return *this;   ///////////////////////////////////////////////////////////////
	}

	std::string Name;
	int Age;
	bool IsReptile;
};



int main()
{
	Animal Dog("Max", 4, false);
	Animal Snake("Piton", 5, true);

	Dog = Snake;
	std::cout << Dog.Name << " " << Dog.Age << " " << Dog.IsReptile;
}



Comments


AREmoji_20220114_174931_50[6].gif

                Koray Liman

Cpp Lover, Game/Mobile App Developer

  • Instagram
  • Twitter

Creativity. Productivity. Vision.

Subscribe

Thanks for submitting!

©2023 by Jeff Sherman. Proudly created with Wix.com

bottom of page