Sunteți pe pagina 1din 5

CONSTRUCTORS & DESTRUCTORS

• The most important features of OOP are Data


Abstraction, Data Hiding, Inheritance and
Polymorphism. These are all tied together by classes.
•Constructors and destructors are manager functions
of a class.
•A constructor is a member functions of a class that
is automaticaly called when an object of a class is
created. It initialises the class objects and allocate
memory space for it.
•It has the same name as the class name. It initialises
the objects of that class with some legal initial value.
CONSTRUCTORS
• If a class has a constructor each object of that class
will be initialized before any use is made of the object.
Eg. class student
{private: int rno; float marks;
public: student(){rno=0; marks=0.0;}…};
Whenever an object of the student type is created
compiler will automatically call the constructor
student::student() for the newly created object.
Constructors are needed for a class because structure
and array members can be directly initialised. But
private members of a class cannot be initialised. It
could be done only with member function and it
should be invoked in main function with object.
CONSTRUCTORS
Declaration and Definition of a constructor
A constructor is a member function of a class with
the same name of its class name. A constructor is
defined like other member functions of a class. It
can be defined inline or outline.
Eg. class x{int I; public: int j,int k; x(){i=j=k=0;}..};
Here x::x() is an inline member function.
class x{int I; public: int I, int k; x();};
X::x(){i=j=k=0;} Here constructor is defined
outside.
CONSTRUCTORS
• Constructors can be private or protected.
But is not available to non member functions.
For a private and protected constructor ,
objects of the same class cannot be created in
a non-member function.
class x{int i; x(){i=0;j=0;k=0;}
public: int j,k; void getval(){cin>>i>>j>>k;}
void prnval(){cout<<i<<j<<k;}void check()};
void x::check(){x obj1;} void abc(){x ob2;}
void main(){ x ob3;}
Assessment
1.A class has been declared globally but still main() is
unable to create objects of this class type. What is
the reason.
2. Is there any difference between list x and list x()
supposing there exists a class namely list?
3. Is the default constructor of class test always
test::test();
4.Do static data members affect object size?Give
reason
5. Suppose a class B has been defined inside public
section of another class A. Can you define an object
of type B outside the definition of A? Why/why not

S-ar putea să vă placă și