Default Constructor etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Default Constructor etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

12 Kasım 2018 Pazartesi

Default Constructor

Giriş
Kullanıcı herhangi bir constructor metodu yazarsa üretilmez. Açıklaması şöyle.
A default constructor is one without any parameters. Normally, it is provided for you. But if you explicitly define any other constructor, then it is not.
Açıklaması şöyle.
If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.
const Alan
default constructor kullanmak için const alanlara değer atamak gerekir. Şu kod derlenmez.
class Bond
{
public:
  Bond(int payments_per_year, int period_lengths_in_months);
  Bond() = default;

private:
  const int payments_per_year;
  const int period_length_in_months;
};

int main()
{
  Bond b; // Error here
}
Şöyle yaparız.
const int payments_per_year = {12};
Defaulted Default Constructor
Örnek
Açıklaması şöyle. Yani sınıfın başka bir constructor'ı varsa ve derleyici halen default constructor üretsin istiyorsak kullanılır.
Dog() = default; is a user declared constructor (not to be confused with a user defined constructor). It is a defaulted default constructor. Typically you would use it when the class has other constructors but you still want the compiler to generate a default constructor (or rather a "defaulted default constructor". This is C++ terminology at its best. Note how the two "default"s have slightly different meaning).
Şöyle yaparız
class Dog
{
private:
    int x;
public:
    Dog()=default;
};