CBSE Computer Science - Revision Tour(Solved) CBSE Guess > eBooks > Class XII > CBSE Computer Science Constructors And Destructors Solved Revision Tour By Mr. Ravi Kiran COMPUTER SCIENCE CONSTRUCTORS AND DESTRUCTORS Constructor: A member function with thesame name as its class is called Constructor and it is used to initialize the objects of that class type with a legal initial value. If a class has a constructor, each object of that class will be initialized before
any use is made of the object. Need for Constructors: A variable, an array or a structure in C++ can be initialized at the time of their declaration. Eg:
But this type of initialization does not work for a class because the class members have their associated access specifiers. They might not be available to the outside world(outside their class). A Constructor is used to initialize the objects of the class being created(automatically called by the compiler). Difference between a constructor and an ordinary member function: Constructor:
Member Function:
Declaration and Definition: A constructor is a member function of a class with the same name as that of its class name. A constructor is defined like other member functions of a class. It can be defined either inside the class definition or outside the class definition. Eg:
This simple constructor (X::X ( ) ) is as an inline member function. Constructors can be written as outline functions also as it is shown below:
Generally constructor will be defined under public section, which can be available to non members also. But it can also be defined under private or protected. A private or protected constructor is not available to the non-member functions. Ie With a private or protected constructor, you cannot create an object of the same class in a non-member function.
CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] ) |
|