C++ this Pointer Nedir?
C++ this pointer kullanımını öğrenin. Nesnenin kendi örneğine erişim, metot zincirleme ve sınıf tasarımı örneklerle anlatılıyor.
C++’ta her sınıfın üye fonksiyonları (metotları) gizli bir şekilde bir this pointer parametresi alır.
this pointer, fonksiyonun çağrıldığı nesnenin adresini temsil eder.
Yani bir sınıfın metodu içinde this kullanılarak o anda üzerinde işlem yapılan nesneye erişilebilir.
1. this Pointer Nedir?
this, her sınıf metoduna otomatik olarak geçirilen gizli bir pointer’dır. Statik olmayan her üye fonksiyon, çağrıldığı nesnenin adresine bu pointer aracılığıyla erişir.
#include <iostream>
using namespace std;
class Book {
private:
string title;
public:
Book(string t) {
this->title = t; // this kullanımı
}
void Show() {
cout << "Kitap: " << this->title << endl;
}
};
int main() {
Book b("C++ Öğreniyorum");
b.Show();
}
Burada this->title, mevcut nesnenin title üyesine erişir.
Aslında title = t; yazmakla aynı sonucu verir,
ancak özellikle parametre adı ile üye adı çakıştığında kullanışlıdır.
2. Parametre Adı ile Üye Adı Çakışması
Aşağıdaki örnekte constructor parametresi ve sınıf üyesi aynı isme sahiptir.
Bu durumda this kullanmak zorunludur.
class Book {
private:
string title;
double price;
public:
Book(string title, double price) {
this->title = title; // "this" olmasa yerel parametreye atama yapılır
this->price = price;
}
void Show() const {
cout << "Kitap: " << title << " | Fiyat: " << price << " TL" << endl;
}
};
int main() {
Book b("Modern C++", 120.5);
b.Show();
}
this->title ifadesi, sınıfın içindeki title üyesini temsil eder.
Eğer this kullanılmazsa, compiler parametre ile karışıklık yaşayabilir.
3. this Pointer’ın Bellek Adresi
Her nesnenin this adresi farklıdır, çünkü her nesne bellekte farklı bir konumdadır.
#include <iostream>
using namespace std;
class Book {
private:
string title;
public:
Book(string t) : title(t) {}
void PrintAddress() const {
cout << "Nesne adresi (this): " << this << endl;
}
};
int main() {
Book b1("C++ Primer");
Book b2("Effective C++");
b1.PrintAddress();
b2.PrintAddress();
}
Çıktı her iki nesne için farklı olacaktır çünkü this her bir nesnenin kendi adresini tutar.
4. Method Chaining (Zincirleme Metot Çağrısı)
this pointer, metotlardan kendi nesnesini döndürmek için kullanılabilir.
Böylece birden fazla metot çağrısı tek bir ifadede zincirlenebilir.
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
double price;
int pageCount;
public:
Book() : title(""), price(0), pageCount(0) {}
Book* SetTitle(string t) {
this->title = t;
return this; // kendi adresini döndürür
}
Book* SetPrice(double p) {
this->price = p;
return this;
}
Book* SetPageCount(int c) {
this->pageCount = c;
return this;
}
void Show() const {
cout << title << " (" << pageCount << " sayfa) - "
<< price << " TL" << endl;
}
};
int main() {
Book b;
b.SetTitle("C++ ile Nesne Yönelimli Programlama")
->SetPrice(149.90)
->SetPageCount(580)
->Show();
}
Bu teknik, method chaining olarak bilinir ve
genellikle Builder veya Fluent Interface tasarım desenlerinde kullanılır.
5. this Pointer ile Operator Overloading
this pointer, operator overloading işlemlerinde de sıkça kullanılır.
Örneğin iki Book nesnesini fiyat karşılaştırmasıyla toplamak:
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
double price;
public:
Book(string t, double p) : title(t), price(p) {}
// Operator Overloading (+)
Book operator+(const Book &other) const {
double totalPrice = this->price + other.price;
return Book("Paket: " + this->title + " & " + other.title, totalPrice);
}
void Show() const {
cout << title << " - " << price << " TL" << endl;
}
};
int main() {
Book b1("C++ Primer", 180.0);
Book b2("Effective Modern C++", 220.0);
Book combo = b1 + b2;
combo.Show();
}
Burada this->price, işlemin sol tarafındaki nesneye ait fiyatı temsil eder.
Bu, iki nesnenin birleştirilmesi veya karşılaştırılması gereken durumlarda oldukça kullanışlıdır.
6. Constructor ve this Pointer
Constructor içinde this kullanımı, nesne ömrü başlamadan önceki bellek adresini referans almak için geçerlidir.
Genellikle constructor içinde this kullanımı, log veya debug işlemlerinde tercih edilir.
class Book {
public:
Book() {
cout << "Yeni Book nesnesi oluşturuluyor... Adres: " << this << endl;
}
};
Bu, özellikle karmaşık nesne yapılarında (örneğin Book → Author → Publisher zincirlerinde) nesne yaşam döngüsünü izlemek için yararlıdır.
7. Statik Fonksiyonlarda this Kullanılamaz
Statik fonksiyonlar sınıfa aittir, herhangi bir nesneye ait değildir.
Dolayısıyla bu tür fonksiyonlarda this pointer’ı mevcut değildir.
class Book {
public:
static void Info() {
// cout << this; // HATA! Static fonksiyonda this kullanılamaz
cout << "Bu bir statik fonksiyondur." << endl;
}
};
8. TL;DR
thispointer, mevcut nesnenin adresini temsil eder.this->üye→ o nesnenin verisine erişmek için kullanılır.- Parametre adı ile üye adı çakıştığında
thisgereklidir. return this;→ method chaining (zincirleme çağrı) sağlar.this, operator overloading içinde de kullanılabilir.- Statik fonksiyonlarda
thismevcut değildir. - Tüm örnekler Visual Studio 2022 veya GCC 11+ ortamlarında doğrudan çalıştırılabilir.