C++ provides a special member function called the constructor which enables an object to initialize itself when it is created. This is known as automatic initialization of objects.
Similarly, it also provides another
member function called the destructor that destroys the objects when
they are not required.
CONSTRUCTOR
A constructor is a special member
function of a class, which constructs an object.
A constructor must be declared in
public specifier of a class. It is mainly used to initialize the data members
of a class.
A constructor name is as same name
as the class name. The constructors should not have any return type
The constructors are defined with
or without arguments
A constructor is an automatically
executed member function of a class. A constructor is invoked when the class
object is instantiated (created).
A constructor is invoked once for
each object.
A constructor is also defined
inside/outside of a class.
Syntax
public:
classname ( [parameter_list] )
{
Statement block;
}
Example:
class sample
{
private:
int n;
public:
sample()
{
n=0;
}
sample(int k) {
n=k;
}
};
0 comments:
Post a Comment