ctick said:
When defining a clas and no constructor and destructor provided, compiler
generates both.
What're the need for this since they do nothing as to
constructing/destructing an obejct.
What's happening in constructor/destructor if they both are defaulted and
empty?
Thanks!
The answer is that without a constructor and destructor, compiler generated
or not, you can't create and/or destroy an instance of a class. Don't be
fooled by other languages that don't expose the existance of cstors and
d~stors. They certainly need them as well. The difference here is that you
have the option to define how your instance is initialized / constructed and
destroyed.
While the compiler generated constructor might fit the bill, you always have
the option of taking control in the case the default constructor doesn't
fullfill your needs. Consider:
class A
{
int m_number; // private variable
public:
A(n) : m_number(n) { } // cstor
~A() { } // d~stor
};
Note that i can now keep the m_number variable encapsulated without the need
to provide a member function to initialize it. The private variable is
initialized when the cstor is invoked with a default of 5 unless otherwise
specified.
#include <iostream>
class A
{
int m_number;
public:
A(int n = 5) : m_number(n) { }
~A() { }
void display() const { std::cout << "number is " << m_number <<
std::endl; }
};
int main()
{
A a;
a.display();
A aa(10);
aa.display();
return 0;
}
number is 5
number is 10