logo

Costruttore C++

In C++, il costruttore è un metodo speciale che viene invocato automaticamente al momento della creazione dell'oggetto. Viene generalmente utilizzato per inizializzare i membri dati del nuovo oggetto. Il costruttore in C++ ha lo stesso nome della classe o della struttura.

In breve, una particolare procedura chiamata costruttore viene chiamata automaticamente quando un oggetto viene creato in C++. In generale, viene utilizzato per creare i dati membri di cose nuove. In C++, il nome della classe o della struttura funge anche da nome del costruttore. Quando un oggetto è completato, viene chiamato il costruttore. Poiché crea i valori o fornisce i dati per l'oggetto, è noto come costruttore.

Il prototipo dei Costruttori si presenta così:

 (list-of-parameters); 

La seguente sintassi viene utilizzata per definire il costruttore della classe:

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

La seguente sintassi viene utilizzata per definire un costruttore all'esterno di una classe:

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

I costruttori non hanno un tipo restituito poiché non hanno un valore restituito.

In C++ possono esserci due tipi di costruttori.

  • Costruttore predefinito
  • Costruttore parametrizzato

Costruttore predefinito C++

Un costruttore che non ha argomenti è noto come costruttore predefinito. Viene invocato al momento della creazione dell'oggetto.

Vediamo il semplice esempio del costruttore predefinito C++.

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

Costruttore con parametri C++

Un costruttore che ha parametri è chiamato costruttore parametrizzato. Viene utilizzato per fornire valori diversi a oggetti distinti.

Vediamo il semplice esempio del costruttore con parametri C++.

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

Cosa distingue i costruttori da una tipica funzione membro?

  1. Il nome del costruttore è lo stesso della classe
  2. Predefinito Non esiste un argomento di input per i costruttori. Tuttavia, gli argomenti di input sono disponibili per i costruttori di copia e con parametri.
  3. Non esiste un tipo restituito per i costruttori.
  4. Il costruttore di un oggetto viene richiamato automaticamente al momento della creazione.
  5. Deve essere esposto nello spazio aperto dell'aula.
  6. Il compilatore C++ crea un costruttore predefinito per l'oggetto se non viene specificato un costruttore (si prevede parametri e ha un corpo vuoto).

Utilizzando un esempio pratico, impariamo a conoscere i vari tipi di costruttori in C++. Immagina di aver visitato un negozio per acquistare un pennarello. Quali sono le tue alternative se desideri acquistare un pennarello? Per il primo, chiedi ad un negozio di darti un pennarello, dato che non hai specificato la marca o il colore del pennarello che volevi, chiedendo semplicemente un importo a richiesta. Quindi, quando abbiamo semplicemente detto: 'Ho solo bisogno di un pennarello', ci dava qualunque fosse il pennarello più popolare sul mercato o nel suo negozio. Il costruttore predefinito è esattamente quello che sembra! Il secondo approccio è entrare in un negozio e specificare che desideri un pennarello rosso del marchio XYZ. Ti darà quel pennarello poiché hai sollevato l'argomento. In questo caso i parametri sono stati impostati così. E un costruttore parametrizzato è esattamente quello che sembra! Il terzo richiede che tu visiti un negozio e dichiari che desideri un pennarello simile a questo (un pennarello fisico sulla tua mano). Il negoziante noterà così quel contrassegno. Ti fornirà un nuovo pennarello quando dirai che va bene. Pertanto, crea una copia di quel segnalino. E questo è ciò che fa un costruttore di copie!

Quali sono le caratteristiche di un costruttore?

  1. Il costruttore ha lo stesso nome della classe a cui appartiene.
  2. Sebbene sia possibile, i costruttori vengono generalmente dichiarati nella sezione pubblica della classe. Tuttavia, questo non è un must.
  3. Poiché i costruttori non restituiscono valori, mancano di un tipo restituito.
  4. Quando creiamo un oggetto classe, il costruttore viene immediatamente invocato.
  5. Sono possibili costruttori sovraccaricati.
  6. Non è consentito dichiarare un costruttore virtuale.
  7. Non è possibile ereditare un costruttore.
  8. Non è possibile fare riferimento agli indirizzi del costruttore.
  9. Durante l'allocazione della memoria, il costruttore effettua chiamate implicite agli operatori new ed delete.

Cos'è un costruttore di copie?

Una funzione membro nota come costruttore di copia inizializza un elemento utilizzando un altro oggetto della stessa classe: una discussione approfondita sui costruttori di copia.

Ogni volta che specifichiamo uno o più costruttori non predefiniti (con parametri) per una classe, dobbiamo includere anche un costruttore predefinito (senza parametri), poiché il compilatore non ne fornirà uno in questa circostanza. La procedura migliore è dichiarare sempre un costruttore predefinito, anche se non è obbligatorio.

Il costruttore della copia richiede un riferimento a un oggetto appartenente alla stessa classe.

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

Cos'è un distruttore in C++?

Una funzione membro speciale equivalente a un costruttore è un distruttore. Il costruttore crea oggetti di classe, che vengono distrutti dal distruttore. La parola 'distruttore', seguita dal simbolo tilde (), è la stessa del nome della classe. Puoi definire un solo distruttore alla volta. Un metodo per distruggere un oggetto creato da un costruttore consiste nell'utilizzare un distruttore. Di conseguenza, i distruttori non possono essere sovraccaricati. I distruttori non accettano argomenti e non restituiscono nulla. Non appena l'elemento esce dall'ambito, viene immediatamente richiamato. I distruttori liberano la memoria utilizzata dagli oggetti generati dal costruttore. Il distruttore inverte il processo di creazione delle cose distruggendole.

Il linguaggio utilizzato per definire il distruttore della classe

 ~ () { } 

Il linguaggio utilizzato per definire il distruttore della classe al di fuori di esso

 : : ~ (){}