logo

C++ Oluşturucusu

C++'da yapıcı, nesne yaratılırken otomatik olarak çağrılan özel bir yöntemdir. Genel olarak yeni nesnenin veri üyelerini başlatmak için kullanılır. C++'daki yapıcı, sınıf veya yapı ile aynı ada sahiptir.

Kısaca, C++'ta bir nesne oluşturulduğunda yapıcı adı verilen özel bir prosedür otomatik olarak çağrılır. Genel olarak yeni şeylerin veri üyelerini oluşturmak için kullanılır. C++'da sınıf veya yapı adı aynı zamanda yapıcı adı olarak da işlev görür. Bir nesne tamamlandığında yapıcı çağrılır. Bir şeyin değerlerini yarattığı veya veri verdiği için yapıcı olarak bilinir.

Constructors prototipi şuna benzer:

 (list-of-parameters); 

Sınıfın yapıcısını tanımlamak için aşağıdaki sözdizimi kullanılır:

 (list-of-parameters) { // constructor definition } 

Bir sınıfın dışındaki bir kurucuyu tanımlamak için aşağıdaki sözdizimi kullanılır:

 : : (list-of-parameters){ // constructor definition} 

Yapıcılar bir dönüş değerine sahip olmadıkları için dönüş tipinden yoksundurlar.

C++'da iki tür yapıcı olabilir.

  • Varsayılan kurucu
  • Parametreli yapıcı

C++ Varsayılan Yapıcı

Argümanı olmayan bir kurucuya varsayılan kurucu denir. Nesne oluşturulurken çağrılır.

C++ varsayılan Oluşturucusunun basit örneğini görelim.

 #include using namespace std; class Employee { public: Employee() { cout&lt;<'default constructor invoked'<<endl; } }; int main(void) { employee e1; creating an object of e2; return 0; < pre> <p> <strong>Output:</strong> </p> <pre>Default Constructor Invoked Default Constructor Invoked </pre> <h2>C++ Parameterized Constructor</h2> <p>A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.</p> <p>Let&apos;s see the simple example of C++ Parameterized Constructor.</p> <pre> #include using namespace std; class Employee { public: int id;//data member (also instance variable) string name;//data member(also instance variable) float salary; Employee(int i, string n, float s) { id = i; name = n; salary = s; } void display() { cout&lt; <id<<' '<<name<<' '<<salary<<endl; } }; int main(void) { employee e1="Employee(101," 'sonoo', 890000); creating an object of e2="Employee(102," 'nakul', 59000); e1.display(); e2.display(); return 0; < pre> <p> <strong>Output:</strong> </p> <pre>101 Sonoo 890000 102 Nakul 59000 </pre> <h2>What distinguishes constructors from a typical member function?</h2> <ol class="points"> <li>Constructor&apos;s name is the same as the class&apos;s</li> <li>Default There isn&apos;t an input argument for constructors. However, input arguments are available for copy and parameterized constructors.</li> <li>There is no return type for constructors.</li> <li>An object&apos;s constructor is invoked automatically upon creation.</li> <li>It must be shown in the classroom&apos;s open area.</li> <li>The C++ compiler creates a default constructor for the object if a constructor is not specified (expects any parameters and has an empty body).</li> </ol> <p>By using a practical example, let&apos;s learn about the various constructor types in C++. Imagine you visited a store to purchase a marker. What are your alternatives if you want to buy a marker? For the first one, you ask a store to give you a marker, given that you didn&apos;t specify the brand name or colour of the marker you wanted, simply asking for one amount to a request. So, when we just said, &apos;I just need a marker,&apos; he would hand us whatever the most popular marker was in the market or his store. The default constructor is exactly what it sounds like! The second approach is to go into a store and specify that you want a red marker of the XYZ brand. He will give you that marker since you have brought up the subject. The parameters have been set in this instance thus. And a parameterized constructor is exactly what it sounds like! The third one requires you to visit a store and declare that you want a marker that looks like this (a physical marker on your hand). The shopkeeper will thus notice that marker. He will provide you with a new marker when you say all right. Therefore, make a copy of that marker. And that is what a copy constructor does!</p> <h2>What are the characteristics of a constructor?</h2> <ol class="points"> <li>The constructor has the same name as the class it belongs to.</li> <li>Although it is possible, constructors are typically declared in the class&apos;s public section. However, this is not a must.</li> <li>Because constructors don&apos;t return values, they lack a return type.</li> <li>When we create a class object, the constructor is immediately invoked.</li> <li>Overloaded constructors are possible.</li> <li>Declaring a constructor virtual is not permitted.</li> <li>One cannot inherit a constructor.</li> <li>Constructor addresses cannot be referenced to.</li> <li>When allocating memory, the constructor makes implicit calls to the new and delete operators.</li> </ol> <h2>What is a copy constructor?</h2> <p>A member function known as a copy constructor initializes an item using another object from the same class-an in-depth discussion on Copy Constructors.</p> <p>Every time we specify one or more non-default constructors (with parameters) for a class, we also need to include a default constructor (without parameters), as the compiler won&apos;t supply one in this circumstance. The best practice is to always declare a default constructor, even though it is not required.</p> <p>A reference to an object belonging to the same class is required by the copy constructor.</p> <pre> Sample(Sample &amp;t) { id=t.id; } </pre> <h2>What is a destructor in C++?</h2> <p>An equivalent special member function to a constructor is a destructor. The constructor creates class objects, which are destroyed by the destructor. The word &apos;destructor,&apos; followed by the tilde () symbol, is the same as the class name. You can only define one destructor at a time. One method of destroying an object made by a constructor is to use a destructor. Destructors cannot be overloaded as a result. Destructors don&apos;t take any arguments and don&apos;t give anything back. As soon as the item leaves the scope, it is immediately called. Destructors free up the memory used by the objects the constructor generated. Destructor reverses the process of creating things by destroying them.</p> <p>The language used to define the class&apos;s destructor</p> <pre> ~ () { } </pre> <p>The language used to define the class&apos;s destructor outside of it</p> <pre> : : ~ (){} </pre> <hr></id<<'></pre></'default>

C++ Parametreli Oluşturucu

Parametreleri olan bir kurucuya parametreli kurucu denir. Farklı nesnelere farklı değerler sağlamak için kullanılır.

C++ Parameterized Constructor'ın basit örneğini görelim.

 #include using namespace std; class Employee { public: int id;//data member (also instance variable) string name;//data member(also instance variable) float salary; Employee(int i, string n, float s) { id = i; name = n; salary = s; } void display() { cout&lt; <id<<\' \'<<name<<\' \'<<salary<<endl; } }; int main(void) { employee e1="Employee(101," \'sonoo\', 890000); creating an object of e2="Employee(102," \'nakul\', 59000); e1.display(); e2.display(); return 0; < pre> <p> <strong>Output:</strong> </p> <pre>101 Sonoo 890000 102 Nakul 59000 </pre> <h2>What distinguishes constructors from a typical member function?</h2> <ol class="points"> <li>Constructor&apos;s name is the same as the class&apos;s</li> <li>Default There isn&apos;t an input argument for constructors. However, input arguments are available for copy and parameterized constructors.</li> <li>There is no return type for constructors.</li> <li>An object&apos;s constructor is invoked automatically upon creation.</li> <li>It must be shown in the classroom&apos;s open area.</li> <li>The C++ compiler creates a default constructor for the object if a constructor is not specified (expects any parameters and has an empty body).</li> </ol> <p>By using a practical example, let&apos;s learn about the various constructor types in C++. Imagine you visited a store to purchase a marker. What are your alternatives if you want to buy a marker? For the first one, you ask a store to give you a marker, given that you didn&apos;t specify the brand name or colour of the marker you wanted, simply asking for one amount to a request. So, when we just said, &apos;I just need a marker,&apos; he would hand us whatever the most popular marker was in the market or his store. The default constructor is exactly what it sounds like! The second approach is to go into a store and specify that you want a red marker of the XYZ brand. He will give you that marker since you have brought up the subject. The parameters have been set in this instance thus. And a parameterized constructor is exactly what it sounds like! The third one requires you to visit a store and declare that you want a marker that looks like this (a physical marker on your hand). The shopkeeper will thus notice that marker. He will provide you with a new marker when you say all right. Therefore, make a copy of that marker. And that is what a copy constructor does!</p> <h2>What are the characteristics of a constructor?</h2> <ol class="points"> <li>The constructor has the same name as the class it belongs to.</li> <li>Although it is possible, constructors are typically declared in the class&apos;s public section. However, this is not a must.</li> <li>Because constructors don&apos;t return values, they lack a return type.</li> <li>When we create a class object, the constructor is immediately invoked.</li> <li>Overloaded constructors are possible.</li> <li>Declaring a constructor virtual is not permitted.</li> <li>One cannot inherit a constructor.</li> <li>Constructor addresses cannot be referenced to.</li> <li>When allocating memory, the constructor makes implicit calls to the new and delete operators.</li> </ol> <h2>What is a copy constructor?</h2> <p>A member function known as a copy constructor initializes an item using another object from the same class-an in-depth discussion on Copy Constructors.</p> <p>Every time we specify one or more non-default constructors (with parameters) for a class, we also need to include a default constructor (without parameters), as the compiler won&apos;t supply one in this circumstance. The best practice is to always declare a default constructor, even though it is not required.</p> <p>A reference to an object belonging to the same class is required by the copy constructor.</p> <pre> Sample(Sample &amp;t) { id=t.id; } </pre> <h2>What is a destructor in C++?</h2> <p>An equivalent special member function to a constructor is a destructor. The constructor creates class objects, which are destroyed by the destructor. The word &apos;destructor,&apos; followed by the tilde () symbol, is the same as the class name. You can only define one destructor at a time. One method of destroying an object made by a constructor is to use a destructor. Destructors cannot be overloaded as a result. Destructors don&apos;t take any arguments and don&apos;t give anything back. As soon as the item leaves the scope, it is immediately called. Destructors free up the memory used by the objects the constructor generated. Destructor reverses the process of creating things by destroying them.</p> <p>The language used to define the class&apos;s destructor</p> <pre> ~ () { } </pre> <p>The language used to define the class&apos;s destructor outside of it</p> <pre> : : ~ (){} </pre> <hr></id<<\'>

Yapıcıları tipik bir üye işlevinden ayıran şey nedir?

  1. Yapıcının adı sınıfın adı ile aynıdır
  2. Varsayılan Yapıcılar için bir giriş argümanı yoktur. Ancak, kopya ve parametreli kurucular için giriş argümanları mevcuttur.
  3. Yapıcılar için dönüş türü yoktur.
  4. Bir nesnenin yapıcısı, oluşturulduktan sonra otomatik olarak çağrılır.
  5. Sınıfın açık alanında sergilenmelidir.
  6. C++ derleyicisi, bir kurucu belirtilmemişse (herhangi bir parametre bekliyorsa ve boş bir gövdeye sahipse) nesne için varsayılan bir kurucu oluşturur.

Pratik bir örnek kullanarak C++'daki çeşitli kurucu türlerini öğrenelim. Bir kalem satın almak için bir mağazayı ziyaret ettiğinizi düşünün. Markör satın almak istiyorsanız alternatifleriniz nelerdir? İlki, istediğiniz kalemin markasını veya rengini belirtmediğiniz için bir mağazadan size bir kalem vermesini istersiniz, sadece talep karşılığında bir miktar talep edersiniz. Yani, 'Sadece bir kaleme ihtiyacım var' dediğimizde, pazarda veya mağazasında en popüler kalem hangisiyse onu bize verirdi. Varsayılan kurucu tam olarak göründüğü gibidir! İkinci yaklaşım ise bir mağazaya gidip XYZ markasının kırmızı işaretleyicisini istediğinizi belirtmektir. Konuyu açtığınız için size o kalemi verecek. Bu örnekte parametreler bu şekilde ayarlanmıştır. Ve parametreli bir kurucu tam olarak kulağa nasıl geliyorsa öyledir! Üçüncüsü, bir mağazayı ziyaret etmenizi ve buna benzer bir kalem (elinizde bulunan fiziksel bir kalem) istediğinizi beyan etmenizi gerektirir. Böylece esnaf bu işareti fark edecektir. Tamam dediğinizde size yeni bir kalem verecek. Bu nedenle, o işaretçinin bir kopyasını alın. Ve bir kopya kurucunun yaptığı da budur!

Bir yapıcının özellikleri nelerdir?

  1. Yapıcı ait olduğu sınıfla aynı adı taşır.
  2. Her ne kadar mümkün olsa da, yapıcılar genellikle sınıfın public bölümünde bildirilir. Ancak bu bir zorunluluk değildir.
  3. Yapıcılar değer döndürmediklerinden bir dönüş türüne sahip değillerdir.
  4. Bir sınıf nesnesi oluşturduğumuzda yapıcı hemen çağrılır.
  5. Aşırı yüklenmiş yapıcılar mümkündür.
  6. Bir kurucunun sanal olarak bildirilmesine izin verilmez.
  7. Bir kurucuyu miras alamazsınız.
  8. Yapıcı adreslerine başvurulamaz.
  9. Bellek tahsis edilirken yapıcı, new ve delete operatörlerine örtülü çağrılar yapar.

Kopya oluşturucu nedir?

Kopya oluşturucu olarak bilinen bir üye işlevi, aynı sınıftan başka bir nesneyi kullanarak bir öğeyi başlatır; Kopya Oluşturucular hakkında ayrıntılı bir tartışma.

Bir sınıf için bir veya daha fazla varsayılan olmayan kurucuyu (parametreli) her belirttiğimizde, derleyici bu durumda bir tane sağlayamayacağından, aynı zamanda bir varsayılan kurucuyu da (parametresiz) eklememiz gerekir. En iyi uygulama, zorunlu olmasa bile her zaman varsayılan bir kurucu bildirmektir.

Kopya yapıcısı aynı sınıfa ait bir nesneye referans gerektirir.

 Sample(Sample &amp;t) { id=t.id; } 

C++'da yıkıcı nedir?

Bir yapıcıya eşdeğer özel üye işlevi bir yıkıcıdır. Yapıcı, yıkıcı tarafından yok edilen sınıf nesneleri yaratır. 'Yıkıcı' kelimesi ve ardından tilde () simgesi, sınıf adıyla aynıdır. Aynı anda yalnızca bir yıkıcı tanımlayabilirsiniz. Bir kurucu tarafından yapılan bir nesneyi yok etmenin bir yöntemi, bir yıkıcı kullanmaktır. Sonuç olarak yıkıcılar aşırı yüklenemez. Yıkıcılar hiçbir tartışmayı kabul etmez ve hiçbir şeyi geri vermezler. Öğe kapsamdan çıkar çıkmaz hemen çağrılır. Yıkıcılar, yapıcının oluşturduğu nesneler tarafından kullanılan belleği serbest bırakır. Yıkıcı, bir şeyleri yok ederek yaratma sürecini tersine çevirir.

Sınıfın yıkıcısını tanımlamak için kullanılan dil

 ~ () { } 

Sınıfın onun dışındaki yıkıcısını tanımlamak için kullanılan dil

 : : ~ (){}