logo

C++ konstruktorius

C++ kalboje konstruktorius yra specialus metodas, kuris automatiškai iškviečiamas kuriant objektą. Jis paprastai naudojamas naujo objekto duomenų nariams inicijuoti. C++ konstruktorius turi tą patį pavadinimą kaip klasė arba struktūra.

Trumpai tariant, tam tikra procedūra, vadinama konstruktoriumi, iškviečiama automatiškai, kai objektas sukuriamas C++. Paprastai jis naudojamas naujų dalykų duomenų nariams kurti. C++ kalboje klasės arba struktūros pavadinimas taip pat naudojamas kaip konstruktoriaus pavadinimas. Užbaigus objektą, iškviečiamas konstruktorius. Kadangi jis sukuria vertes arba pateikia daikto duomenis, jis žinomas kaip konstruktorius.

Konstruktorių prototipas atrodo taip:

 (list-of-parameters); 

Klasės konstruktoriui apibrėžti naudojama ši sintaksė:

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

Ši sintaksė naudojama apibrėžti konstruktorių už klasės ribų:

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

Konstruktoriams trūksta grąžinimo tipo, nes jie neturi grąžinimo vertės.

C++ kalboje gali būti dviejų tipų konstruktoriai.

  • Numatytasis konstruktorius
  • Parametrizuotas konstruktorius

C++ numatytasis konstruktorius

Konstruktorius, neturintis argumentų, yra žinomas kaip numatytasis konstruktorius. Jis iškviečiamas kuriant objektą.

Pažiūrėkime paprastą C++ numatytojo konstruktoriaus pavyzdį.

 #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++ parametrizuotas konstruktorius

Konstruktorius, turintis parametrus, vadinamas parametruotu konstruktoriumi. Jis naudojamas norint pateikti skirtingas reikšmes skirtingiems objektams.

Pažiūrėkime paprastą C++ Parameterized Constructor pavyzdį.

 #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<<\'>

Kuo konstruktoriai skiriasi nuo tipinės nario funkcijos?

  1. Konstruktoriaus pavadinimas yra toks pat kaip ir klasės
  2. Numatytasis Konstruktoriams nėra įvesties argumento. Tačiau kopijavimo ir parametruotų konstruktorių įvesties argumentai yra prieinami.
  3. Konstruktoriams grąžinimo tipo nėra.
  4. Kuriant objektą, automatiškai iškviečiamas konstruktorius.
  5. Jis turi būti rodomas atviroje klasėje.
  6. C++ kompiliatorius sukuria numatytąjį objekto konstruktorių, jei konstruktorius nenurodytas (laukia jokių parametrų ir turi tuščią turinį).

Naudodami praktinį pavyzdį, sužinokime apie įvairius C++ konstruktorių tipus. Įsivaizduokite, kad apsilankėte parduotuvėje norėdami įsigyti žymeklio. Kokios yra jūsų alternatyvos, jei norite nusipirkti žymeklį? Pirmuoju atveju prašote parduotuvės duoti jums žymeklį, nes nenurodėte norimo žymeklio prekės ženklo ar spalvos, o užklausai tiesiog prašote vienos sumos. Taigi, kai mes ką tik pasakėme: „Man reikia tik žymeklio“, jis pateikdavo mums bet kokį populiariausią žymeklį turguje ar jo parduotuvėje. Numatytasis konstruktorius yra būtent toks, kaip skamba! Antrasis būdas yra nueiti į parduotuvę ir nurodyti, kad norite raudono XYZ prekės ženklo žymeklio. Jis jums duos tą žymeklį, nes jūs iškėlėte temą. Šiuo atveju parametrai buvo nustatyti taip. O parametrizuotas konstruktorius yra būtent toks, kaip skamba! Trečiasis reikalauja, kad apsilankytumėte parduotuvėje ir pareikštumėte, kad norite taip atrodančio žymeklio (fizinio žymeklio ant rankos). Taigi parduotuvės savininkas pastebės tą žymeklį. Jis suteiks jums naują žymeklį, kai pasakysite, kad viskas gerai. Todėl pasidarykite to žymeklio kopiją. Ir tai daro kopijavimo konstruktorius!

apvalaus turnyro tvarkaraštis

Kokios yra konstruktoriaus savybės?

  1. Konstruktorius turi tą patį pavadinimą kaip ir klasė, kuriai jis priklauso.
  2. Nors tai įmanoma, konstruktoriai paprastai deklaruojami klasės viešajame skyriuje. Tačiau tai nėra būtina.
  3. Kadangi konstruktoriai nepateikia verčių, jiems trūksta grąžinimo tipo.
  4. Kai sukuriame klasės objektą, iš karto iškviečiamas konstruktorius.
  5. Galimi perkrauti konstruktoriai.
  6. Skelbti konstruktorių virtualiu neleidžiama.
  7. Negalima paveldėti konstruktoriaus.
  8. Konstruktorių adresai negali būti nurodyti.
  9. Skirdamas atmintį, konstruktorius netiesiogiai iškviečia naujus ir ištrina operatorius.

Kas yra kopijavimo konstruktorius?

Nario funkcija, žinoma kaip kopijavimo konstruktorius, inicijuoja elementą naudodama kitą objektą iš tos pačios klasės – nuodugni diskusija apie Copy Constructors.

Kiekvieną kartą, kai nurodome vieną ar daugiau nenumatytųjų klasės konstruktorių (su parametrais), taip pat turime įtraukti numatytąjį konstruktorių (be parametrų), nes tokiu atveju kompiliatorius jo nepateiks. Geriausia praktika yra visada deklaruoti numatytąjį konstruktorių, net jei to nereikia.

Nuorodos į objektą, priklausantį tai pačiai klasei, reikalauja kopijavimo konstruktorius.

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

Kas yra destruktorius C++?

Konstruktoriui lygiavertė specialioji nario funkcija yra destruktorius. Konstruktorius sukuria klasės objektus, kuriuos naikintojas sunaikina. Žodis „naikintojas“, po kurio yra tildės () simbolis, yra toks pat kaip klasės pavadinimas. Vienu metu galite apibrėžti tik vieną naikintoją. Vienas iš konstruktoriaus sukurto objekto sunaikinimo būdų yra naudoti naikintuvą. Dėl to naikintuvai negali būti perkrauti. Destruktoriai nepriima jokių argumentų ir nieko negrąžina. Kai tik daiktas palieka taikymo sritį, jis iš karto iškviečiamas. Destruktoriai atlaisvina atmintį, kurią naudoja konstruktoriaus sugeneruoti objektai. Destruktorius apverčia daiktų kūrimo procesą juos sunaikindamas.

Kalba, naudojama klasės naikintojui apibrėžti

 ~ () { } 

Kalba, naudojama klasės naikintojui apibrėžti už jos ribų

 : : ~ (){}