Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well documented example taken and explained better from <a href="http://www.java-samples.com/showtutorial.php?tutorialid=313" rel="noreferrer">Constructors and Destructors in C++</a>: </p> <pre><code>#include &lt;iostream&gt; // for cout and cin class Cat // begin declaration of the class { public: // begin public section Cat(int initialAge); // constructor Cat(const Cat&amp; copy_from); //copy constructor Cat&amp; operator=(const Cat&amp; copy_from); //copy assignment ~Cat(); // destructor int GetAge() const; // accessor function void SetAge(int age); // accessor function void Meow(); private: // begin private section int itsAge; // member variable char * string; }; // constructor of Cat, Cat::Cat(int initialAge) { itsAge = initialAge; string = new char[10](); } //copy constructor for making a new copy of a Cat Cat::Cat(const Cat&amp; copy_from) { itsAge = copy_from.itsAge; string = new char[10](); std::copy(copy_from.string+0, copy_from.string+10, string); } //copy assignment for assigning a value from one Cat to another Cat&amp; Cat::operator=(const Cat&amp; copy_from) { itsAge = copy_from.itsAge; std::copy(copy_from.string+0, copy_from.string+10, string); } // destructor, just an example Cat::~Cat() { delete[] string; } // GetAge, Public accessor function // returns value of itsAge member int Cat::GetAge() const { return itsAge; } // Definition of SetAge, public // accessor function void Cat::SetAge(int age) { // set member variable its age to // value passed in by parameter age itsAge = age; } // definition of Meow method // returns: void // parameters: None // action: Prints "meow" to screen void Cat::Meow() { cout &lt;&lt; "Meow.\n"; } // create a cat, set its age, have it // meow, tell us its age, then meow again. int main() { int Age; cout&lt;&lt;"How old is Frisky? "; cin&gt;&gt;Age; Cat Frisky(Age); Frisky.Meow(); cout &lt;&lt; "Frisky is a cat who is " ; cout &lt;&lt; Frisky.GetAge() &lt;&lt; " years old.\n"; Frisky.Meow(); Age++; Frisky.SetAge(Age); cout &lt;&lt; "Now Frisky is " ; cout &lt;&lt; Frisky.GetAge() &lt;&lt; " years old.\n"; return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload