A constructor is a special member function of a class that is executed whenever we create new objects of a class. A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be useful for setting initial values for certain member variables.
A destructor is a special member function of a class that is executed whenever an object of it’s class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be useful for releasing resources before coming out of the program.
Scope resolution operator (::) is used to define a function outside a class or when we want to use a global variable but also has a local variable with same name.
C++ program to implement constructor, destructor and scope resolution operator
#include<iostream.h> #include<conio.h> class stu { private: char name[20],add[20]; int roll,zip; public: stu ( );//Constructor ~stu( );//Destructor void read( ); void disp( ); }; stu :: stu( ) { cout<<”This is Student Details”<<endl; } void stu :: read( ) { cout<<”Enter the student Name”; cin>>name; cout<<”Enter the student roll no “; cin>>roll; cout<<”Enter the student address”; cin>>add; cout<<”Enter the Zipcode”; cin>>zip; } void stu :: disp( ) { cout<<”Student Name :”<<name<<endl; cout<<”Roll no is :”<<roll<<endl; cout<<”Address is :”<<add<<endl; cout<<”Zipcode is :”<<zip; } stu : : ~stu( ) { cout<<”Student Detail is Closed”; } void main( ) { stu s; clrscr( ); s.read ( ); s.disp ( ); getch( ); }
Check out – All CSE Basic Practicals
Thanks for visiting us. Do share us among your friends.