OOP Theory - M.Daud Sajid - 028 - BSSE3A
OOP Theory - M.Daud Sajid - 028 - BSSE3A
OOP Theory - M.Daud Sajid - 028 - BSSE3A
Question No 1: Explain the concept of constructor and destructor. Write a program that is
using both as a function and explain the purpose of being used as well.
Ans: Constructor:
Destructor:
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 very useful for
releasing resources before coming out of the program like closing files, releasing memories.
Example of Constructor and destructor in c++:
/* C++ program to Display Student Details using constructor and destructor */
#include<iostream>
using namespace std;
class stu
{
private:
char name[20];
int roll;
public:
stu ();//Constructor
~stu();//Destructor
void read();
void disp();
};
stu :: stu()
{
cout<<"\nThis is Student Details ..........."<<endl;
}
stu :: ~stu()
{
cout<<"\n\nStudent Detail is Closed.............\n";
}
int main()
{
stu s;
s.read ();
s.disp ();
return 0;
}
Constructor and Destructor are the special member functions of the class
which are created by the C++ compiler or can be defined by the user. The
constructor is used to initialize the object of the class while the destructor
is called by the compiler when the object is destroyed.
Question No 2: What is the different between Abstract class and Concrete class
and what is the purpose of Virtual function, explain with examples.
Ans: There are two main types of classes: Abstract Class and Concrete Class.
The main difference between the two arises from the level of implementation of their
method functionalities. Concrete Classes are regular classes, where all methods are
completely implemented.
Virtual Function:
A virtual function is a member function in the base class that we expect to
redefine in derived classes.
Basically, a virtual function is used in the base class in order to ensure that the
function is overridden. This especially applies to cases where a pointer of base
class points to an object of a derived class.
class Base {
public:
};
public:
void print() {
};
int main() {
Derived derived1;
base1->print();
return 0;
}
Thanks !
Muhammad Daud Sajid