CPP 052 – Const Objects

Initialize edildikten sonra bir daha değer ataması yapılamayan sabit değişkenler oluşturmak için kullanıyoruz:

	const int a = 5; 
	a = 6; // HATA 

Yani kısacası ömrü boyunca aynı değeri taşır.

Herhangi bir sınıfa ait constant bir nesne oluşturabiliriz:

// main.cpp
#include <iostream>
using namespace std;

class Player {
	string name; 
	int health; 

public:
	Player(string name, int health) : name{ name }, health{ health } {}

	void set_name(string name) {
		this->name = name; 
	}
	string get_name() {
		return name; 
	}
};


int main() {
	const Player p1("ahmet", 100);

	p1.set_name("mehmet"); // HATA
	cout << p1.get_name(); // HATA
}

Bu kodda Player sınıfına ait constant bir nesne oluşturduk. 24. satırdaki set_name() metoduna yaptığımız çağrı bize hata verecektir. Çünkü sabit bir nesne adı üstüne değiştirilemez. Peki neden bir sonraki satırdaki get_name metodu bize hata verdi?

Constant objeler sadece constant metodları çağırır.

Declaring a member function with the const keyword specifies that the function is a “read-only” function that doesn’t modify the object for which it’s called.

https://learn.microsoft.com/en-us/cpp/cpp/const-cpp?view=msvc-170#const-member-functions

class Player {
	string name; 
	int health; 

public:
	Player(string name, int health) : name{ name }, health{ health } {}

	void set_name(string name) {
		this->name = name; 
	}
	string get_name() const{
		return name; 
	}
};


int main() {
	const Player p1("ahmet", 100);

	//p1.set_name("mehmet"); // HATA
	cout << p1.get_name(); // OK
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *