close
Constructor:
Constructors are typically used to initialize member variables of the class to appropriate default values.
Here is an example of a class that has a default constructor:
(A default constructor means that a constructor has no parameters.)
class
Fraction
{
private
:
int
m_nNumerator;
int
m_nDenominator;
public
:
Fraction()
// default constructor
{
m_nNumerator = 0;
m_nDenominator = 1;
}
int
GetNumerator() {
return
m_nNumerator; }
int
GetDenominator() {
return
m_nDenominator; }
double
GetFraction() {
return
static_cast
<
double
>(m_nNumerator) / m_nDenominator; }
};
Destructor:
Destructor is the counterpart to constructors. When a variable goes out of scope, or a dynamically allocated variable is explicitly deleted using the delete keyword, the class destructor is called (if it exists) to help clean up the class before it is removed from memory.
take a look at a simple string class that uses a destructor:
class
MyString
{
private
:
char
*m_pchString;
int
m_nLength;
public
:
MyString(
const
char
*pchString=
""
)
{
m_nLength =
strlen
(pchString) + 1;
m_pchString =
new
char
[m_nLength];
strncpy
(m_pchString, pchString, m_nLength);
m_pchString[m_nLength-1] =
'\0'
;
}
~MyString()
// destructor
{
// We need to deallocate our buffer
delete
[] m_pchString;
// Set m_pchString to null just in case
m_pchString = 0;
}
char
* GetString() {
return
m_pchString; }
int
GetLength() {
return
m_nLength; }
};
int
main()
{
MyString cMyName(
"Alex"
);
std::cout <<
"My name is: "
<< cMyName.GetString() << std::endl;
return
0;
}
// cMyName destructor called here!
全站熱搜