logo

C++ konstruktori

C++:ssa konstruktori on erityinen menetelmä, jota kutsutaan automaattisesti objektin luonnin yhteydessä. Sitä käytetään yleisesti uuden objektin tietojäsenten alustamiseen. C++:n konstruktorilla on sama nimi kuin luokassa tai rakenteessa.

Lyhyesti sanottuna tietty prosessi, jota kutsutaan konstruktoriksi, kutsutaan automaattisesti, kun objekti luodaan C++:ssa. Yleensä sitä käytetään luomaan uusien asioiden datajäseniä. C++:ssa luokan tai rakenteen nimi toimii myös rakentajan nimenä. Kun objekti on valmis, konstruktori kutsutaan. Koska se luo arvot tai antaa dataa asialle, sitä kutsutaan rakentajaksi.

Constructors-prototyyppi näyttää tältä:

 (list-of-parameters); 

Seuraavaa syntaksia käytetään määrittämään luokan rakentaja:

periytyminen c++:ssa
 (list-of-parameters) { // constructor definition } 

Seuraavaa syntaksia käytetään määrittämään rakentaja luokan ulkopuolella:

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

Rakentajilta puuttuu palautustyyppi, koska niillä ei ole palautusarvoa.

C++:ssa voi olla kahdenlaisia ​​konstruktoreita.

  • Oletuskonstruktori
  • Parametrisoitu rakentaja

C++ oletuskonstruktori

Konstruktori, jolla ei ole argumenttia, tunnetaan oletuskonstruktorina. Sitä kutsutaan objektia luotaessa.

Katsotaanpa yksinkertainen esimerkki C++-oletuskonstruktorista.

 #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++-parametrisoitu konstruktori

Konstruktoria, jolla on parametreja, kutsutaan parametroiduksi konstruktoriksi. Sitä käytetään antamaan eri arvot erillisille objekteille.

Katsotaanpa yksinkertainen esimerkki C++ Parameterized Constructorista.

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

Mikä erottaa konstruktorit tyypillisestä jäsenfunktiosta?

  1. Rakentajan nimi on sama kuin luokan nimi
  2. Oletus Rakentajille ei ole syöttöargumenttia. Syöttöargumentit ovat kuitenkin käytettävissä kopiointi- ja parametroiduille rakentajille.
  3. Rakentajille ei ole palautustyyppiä.
  4. Objektin rakentaja kutsutaan automaattisesti luonnin yhteydessä.
  5. Se on esitettävä luokkahuoneen avoimella alueella.
  6. C++-kääntäjä luo objektille oletuskonstruktorin, jos rakentajaa ei ole määritetty (odottaa parametreja ja siinä on tyhjä runko).

Käytännön esimerkin avulla opitaan C++:n eri konstruktorityypeistä. Kuvittele, että kävit kaupassa ostamassa merkin. Mitä vaihtoehtoja sinulla on, jos haluat ostaa merkin? Ensimmäisessä tapauksessa pyydät kauppaa antamaan sinulle merkin, koska et määrittänyt haluamasi merkin tuotenimeä tai väriä, vaan pyydät vain yhden summan pyyntöön. Joten kun sanoimme vain: 'Tarvitsen vain tussin', hän ojensi meille mitä tahansa suosituinta merkintää markkinoilla tai hänen myymälässään. Oletuskonstruktori on juuri sitä miltä se kuulostaa! Toinen tapa on mennä kauppaan ja ilmoittaa, että haluat punaisen merkin XYZ-brändistä. Hän antaa sinulle tämän merkin, koska olet ottanut asian esille. Parametrit on asetettu tässä tapauksessa näin. Ja parametroitu konstruktori on juuri sitä miltä se kuulostaa! Kolmas vaatii sinua vierailemaan myymälässä ja ilmoittamaan, että haluat tältä näyttävän merkin (fyysisen merkin kädessäsi). Kauppias huomaa siis tämän merkin. Hän antaa sinulle uuden merkin, kun sanot kaikki hyvin. Tee siksi kopio kyseisestä merkistä. Ja niin tekee kopiokonstruktori!

symmetrinen ero

Mitkä ovat rakentajan ominaisuudet?

  1. Rakentajalla on sama nimi kuin luokalla, johon se kuuluu.
  2. Vaikka se on mahdollista, rakentajat ilmoitetaan yleensä luokan julkisessa osiossa. Tämä ei kuitenkaan ole välttämätöntä.
  3. Koska rakentajat eivät palauta arvoja, niiltä puuttuu palautustyyppi.
  4. Kun luomme luokkaobjektin, konstruktori kutsutaan välittömästi.
  5. Ylikuormitetut rakentajat ovat mahdollisia.
  6. Konstruktorin julistaminen virtuaaliseksi ei ole sallittua.
  7. Rakentajaa ei voi periä.
  8. Rakentajaosoitteisiin ei voi viitata.
  9. Muistia varattaessa konstruktori kutsuu implisiittisiä uusia ja poisto-operaattoreita.

Mikä on kopiokonstruktori?

Jäsenfunktio, joka tunnetaan nimellä kopiokonstruktori, alustaa kohteen käyttämällä toista saman luokan objektia - perusteellinen keskustelu kopiokonstruktoreista.

Joka kerta kun määritämme luokalle yhden tai useamman ei-oletuskonstruktorin (parametreineen), meidän on sisällytettävä myös oletuskonstruktori (ilman parametreja), koska kääntäjä ei toimita sellaista tässä tilanteessa. Paras käytäntö on aina ilmoittaa oletuskonstruktori, vaikka sitä ei vaadita.

Kopiokonstruktori vaatii viittauksen samaan luokkaan kuuluvaan objektiin.

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

Mikä on destructor C++:ssa?

Konstruktoria vastaava erikoisjäsenfunktio on destruktori. Konstruktori luo luokkaobjekteja, jotka tuhoaja tuhoaa. Sana 'destructor', jota seuraa tilde () -symboli, on sama kuin luokan nimi. Voit määrittää vain yhden tuhoajan kerrallaan. Yksi tapa tuhota rakentajan tekemä esine on käyttää tuhoajaa. Tämän seurauksena tuhoajia ei voi ylikuormittaa. Tuhoajat eivät ota vastaan ​​argumentteja eivätkä anna mitään takaisin. Heti kun kohde poistuu soveltamisalasta, sitä kutsutaan välittömästi. Destruktorit vapauttavat rakentajan luomien objektien käyttämän muistin. Destructor kääntää asioiden luomisprosessin päinvastaiseksi tuhoamalla ne.

kasa lajitella

Luokan tuhoajan määrittämiseen käytetty kieli

 ~ () { } 

Kieli, jolla määritellään luokan tuhoaja sen ulkopuolella

 : : ~ (){}