CONSTRUCTOR AND DESTRUCTOR (C++)

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 24

CONSTRUCTOR AND DESTRUCTOR

CONSTURCTOR
It is a member function having same name as it’s class and which is used to initialize the objects
of that class type with a legal initial value. Constructor is automatically called when object is
created.

Types of Constructor
Default Constructor-: A constructor that accepts no parameters is known as default constructor.
If no constructor is defined then the compiler supplies a default constructor.

student :: student()
{
     rollno=0;
     marks=0.0;
}

Parameterized Constructor -: A constructor that receives arguments/parameters, is called


parameterized constructor.

student :: student(int r)
{
     rollno=r;
}

Copy Constructor-: A constructor that initializes an object using values of another object
passed to it as parameter, is called copy constructor. It creates the copy of the passed object.

student :: student(student &t)


{
     rollno = t.rollno;
}

There can be multiple constructors of the same class, provided they have different signatures.

DESTRUCTOR
A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign
and which is used to destroy the objects that have been created by a constructor. It gets invoked
when an object’s scope is over.
~student() { }

Example : In the following program constructors, destructor and other member functions are
defined inside class definitions. Since we are using multiple constructor in class so this example
also illustrates the concept of constructor overloading

#include<iostream.h>

class student //specify a class


{
  private :
    int rollno; //class data members
    float marks;
  public:
    student() //default constructor
    {
       rollno=0;
       marks=0.0;
    }
    student(int r, int m) //parameterized constructor
    {
       rollno=r;
       marks=m;
    }
    student(student &t) //copy constructor
    {
       rollno=t.rollno;
       marks=t.marks;
    }
    void getdata() //member function to get data from user
    {
       cout<<"Enter Roll Number : ";
       cin>>rollno;
       cout<<"Enter Marks : ";
       cin>>marks;
    }
    void showdata() // member function to show data
    {
       cout<<"\nRoll number: "<<rollno<<"\nMarks: "<<marks;
    }
    ~student() //destructor
    {}
};

int main()
{
    student st1; //defalut constructor invoked
    student st2(5,78); //parmeterized constructor invoked
    student st3(st2); //copy constructor invoked
    st1.showdata(); //display data members of object st1
    st2.showdata(); //display data members of object st2
    st3.showdata(); //display data members of object st3
    return 0;
}
INHERITANCE
Inheritance:It is the capability of one class to inherit properties from another class.

Base Class: It is the class whose properties are inherited by another class. It is also called Super
Class.

Derived Class:It is the class that inherit properties from base class(es).It is also called Sub Class.

FORMS OF INHERITANCE
Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one
base class.

Multiple Inheritance:It is the inheritance hierarchy wherein one derived class inherits from
multiple base class(es)

Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherits


from one base class.

Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for
other classes.

Hybrid Inheritance:The inheritance hierarchy that reflects any legal combination of other four
types of inheritance.

Visibility Mode:It is the keyword that controls the visibility and availability of inherited base
class members in the derived class.It can be either private or protected or public.

Private Inheritance:It is the inheritance facilitated by private visibility mode.In private


inheritance ,the protected and public members of base class become private members of the
derived class.

Public Inheritance:It is the inheritance facilitated by public visibility mode.In public inheritance
,the protected  members of base class become protected members of the derived class and public
members of the base class become public members of derived class.;
Protected Inheritance:It is the inheritance facilitated by protected visibility mode.In protected
inheritance ,the protected and public members of base class become protected members of the derived
class.

Derived class visibility


Base Class
Public Private Protected
Visibility
derivation derivation derivation
Private Not inherited Not inherited Not inherited
Protected Protected Private Protected
Public Public Private Protected

Containership:When a class contains objects of other class types as its members, it is called
containership.It is also called containment,composition, aggregation.

Execution of base class constructor

Method of inheritace Order of execution


class B : public A { }; A(); base constructor
B(); derived constructor
class A : public B, public C B();base (first)
C();base (second)
A();derived constructor

When both derived and base class contains constructors, the base constructor is executed first
and then the constructor in the derived class is executed.  In case of multiple inheritances, the
base classes are constructed in the order in which they appear in the declaration of the derived
class.

Overriding of method(function) in inheritance


We may face a problem in multiple inheritance, when a function with the same name appears in
more than one base class. Compiler shows ambiguous error when derived class inherited by
these classes uses this function.     

We can solve this problem, by defining a named instance within the derived class, using the class
resolution operator with the function as below :

class P : public M, public N        //multiple inheritance


{
 public :
   void display()  //overrides display() of M and N
   {
      M::display()
   }
};
we can now used the derived class as follows :
 void main()
{
  P obj;
  obj.display();
}

Virtual Base Class


Multipath inheritance may lead to duplication of inherited members from a grandparent base
class. This may be avoided by making the common base class a virtual base class. When a class
is made a virtual base class, C++ takes necessary care to see that only one copy of that class is
inherited.

class A
{
 ....
 ....
};

class B1 : virtual public A

{
 ....
 ....
};
class B2 : virtual public A
{
 ....
 ....
};
class C : public B1, public B2
{
 ....   // only one copy of A
 ....   // will be inherited
};
Constructor and Destructor
[SET – 1]

Question 1 Answer the questions (i) and (ii) after going through the following class:
class Seminar
{
            int Time;
public:
            Seminar()                                           //Function 1
            {
                        Time=30; cout<<”Seminar starts now”<<endl;
            }
            void Lecture()                                     //Function 2
            {
                       cout<<”Lectures in the seminar on”<<endl;
            }
            Seminar(int Duration)                         //Function 3
            {
                       Time=Duration; cout<<”Seminar starts now”<<endl;
            }
            ~Seminar()                                        //Function 4
            {
                        cout<<”Vote of thanks”<<endl;
            }
};
i) In Object Oriented Programming, what is Function 4 referred as and when does it
get invoked/called?
ii) In Object Oriented Programming, which concept is illustrated by Function 1 and
Function 3 together? Write an example illustrating the calls for these functions.
Question 2 Answer the questions (i) and (ii) after going through the following class :

class Exam
{
            int Marks;
            char Subject[20];
public:
            Exam ()                                    //Function 1
            {
                        Marks = 0;
                        strcpy (Subject,”Computer”);
            }
            Exam(char S[])                        //Function 2
            {
                        Marks = 0;
                       strcpy(Subject,S);
            }
            Exam(int M)                             //Function 3
            {
                        Marks = M;
                        strcpy(Subject,”Computer”);
            }
            Exam(char S[], int M)               //Function 4
            {
                        Marks = M;
                        strcpy (Subject,S);
            }
};

(i) Write statements in C++ that would execute Function 3 and Function 4 of class
Exam.
(ii) Which feature of Object Oriented Programming is demonstrated using Function
1, Function 2, Function 3 and Function 4 in the above class Exam ?
Question 3 Answer the questions (i) and (ii) after going through the following program:  

class Match
{
            int Time;
public:
            Match()                                   //Function 1
            {
                        Time=0;
                        cout<<”Match commences”<<endl;
            }
            void Details()                          //Function 2
            {
                        cout<<”Inter Section Basketball Match”<<end1;
            }
            Match(int Duration)                //Function 3
            {
                         Time=Duration;
                        cout<<”Another Match begins now”<<endl;
            }
            Match(Match &M)                  //Function 4
            {
                        Time=M.Duration;
                        cout<<”Like Previous Match ”<<endl;
            }
};
i) Which category of constructor - Function 4 belongs to and what is the purpose of
using it?
ii) Write statements that would call the member Functions 1 and 3

Question 4 Define a class TravelPlan in C++ with the following descriptions :


Private Members:
PlanCode of type long
Place of type character array (string)
Number_of_travellers of type integer
Number_of_buses of type integer
Public Members:
A constructor to assign initial values of Plan Code as 1001, Place as “Agra”,
Number_of_travellers as 5, Number_of_buses as 1
A function NewPlan( ) which allows user to enter PlanCode, Place and
Number_of_travellers. Also, assign the value of Number_of_buses as per the
following conditions :
Number_of_travellers                                   Number_of_buses
Less than 20                                                       1
Equal to or more than 20 and less than 40             2
Equal to 40 or more than 40                                 3
A function ShowPlan( ) to display the content of all the data members on screen.

Constructor and Destructor


[SET –2]

Question A common place to buy candy is from a machine. The machine sells candies, chips,
1 gum, and cookies. You have been asked to write a program for this candy machine.
The program should do the following:
1. Show the customer the different products sold by the candy machine.
2. Let the customer make the selection.
3. Show the customer the cost of the item selected.
4. Accept money from the customer.
5. Release the item.

The machine has two main components: a built-in cash register and several dispensers
to hold and release the products.

Define class cashRegister in C++ with the following descriptions :


Private Members:
cashOnHand of type integer
Public Members:
A default constructor cashRegister() sets the cash in the register to 500.
A constructor cashRegister(int) sets the cash in the register to a specific amount.
A function getCurrentBalance() which returns value of cashOnHand
A function acceptAmount(int) to receive the amount deposited by the customer and
update the amount in the register

Define class dispenserType in C++ with the following descriptions :


Private Members:
numberOfItems of type integer
cost of type integer
Public Members:
A default constructor dispenserType () sets the cost and number of items in the
dispenser to 50 each.
A constructor dispenserType (int,int) sets the cost and number of items in the
dispenser to the values specified by the user.
A function getNoOfItems() to return the value of numberOfItems.
A function getCost() to return the value of cost.
A function makeSale() to reduce the number of items by 1.

When the program executes, it must do the following:


1. Show the different products sold by the candy machine.
2. Show how to select a particular product.
Once the user has made the appropriate selection, the candy machine must act
accordingly. If the user has opted to buy a product and that product is available, the
candy machine should show the cost of the product and ask the user to deposit the
money. If the amount deposited is at least the cost of the item, the candy machine
should sell the item and display an appropriate message.
Divide this program into three functions: showSelection, sellProduct, and main.
The function sellProduct must have access to the dispenser holding the product (to
decrement the number of items in the dispenser by 1 and to show the cost of the item)
as well as the cash register (to update the cash). Therefore, this function has two
parameters: one corresponding to the dispenser and the other corresponding to the
cash register.
solution of question 1
[SET –2]
A common place to buy candy is from a machine. The machine sells candies, chips,
gum, and cookies. You have been asked to write a program for this candy machine.
The program should do the following:
1. Show the customer the different products sold by the candy machine.
2. Let the customer make the selection.
3. Show the customer the cost of the item selected.
4. Accept money from the customer.
5. Release the item.

//************************************************************
// class cashRegister
// This class specifies the members to implement a cash register.
//************************************************************

class cashRegister
{
private:
int cashOnHand;
public:
cashRegister(); //Constructor Sets the cash in the register
to a default amount.
cashRegister(int cashIn); //Constructor Sets the cash in the
register to a specific amount.
int getCurrentBalance(); //The value of cashOnHand is
returned.
void acceptAmount(int amountIn);//Function to receive the
amount deposited by the customer
//and update amount in the
register.
};

//************************************************************
// class dispenserType
// This class specifies the members to implement a dispenser.
//************************************************************

class dispenserType
{
private:
int numberOfItems; //variable to store the number of items in
the dispenser
int cost; //variable to store the cost of an item
public:
dispenserType(); //Constructor Sets the cost and number of
items in the dispenser to the default
dispenserType(int setNoOfItems, int setCost); //Constructor
Sets to the values specified
int getNoOfItems(); //The value of numberOfItems is
returned.
int getCost(); //Function to show the cost of the item. The
value of cost is returned.
void makeSale(); //Function to reduce the number of items by
1.
};

cashRegister::cashRegister()
{
cashOnHand = 500;
}

cashRegister::cashRegister(int cashIn)
{
cashOnHand = cashIn;
}

int cashRegister::getCurrentBalance()
{
return cashOnHand;
}

void cashRegister::acceptAmount(int amountIn)


{

cashOnHand = cashOnHand + amountIn;


}

dispenserType::dispenserType()
{
numberOfItems = 50;
cost = 50;
}

dispenserType::dispenserType(int setNoOfItems, int setCost)


{
numberOfItems = setNoOfItems;
cost = setCost;
}

int dispenserType::getNoOfItems()
{
return numberOfItems;
}

int dispenserType::getCost()
{
return cost;
}

void dispenserType::makeSale()
{
numberOfItems--;
}
//*****************************************************
// This program uses the classes cashRegister and
// dispenserType to implement a candy machine.
// ****************************************************

#include <iostream.h>

void showSelection();
void sellProduct(dispenserType& product, cashRegister& pCounter);
int main()
{
cashRegister counter;
dispenserType candy(100, 50);
dispenserType chips(100, 65);
dispenserType gum(75, 45);
dispenserType cookies(50, 85);
int choice;
showSelection();
cin >> choice;
while (choice != 5)
{
switch (choice)
{
case 1:
sellProduct(candy, counter);
break;
case 2:
sellProduct(chips, counter);
break;
case 3:
sellProduct(gum, counter);
break;
case 4:
sellProduct(cookies, counter);
break;
default:
cout << "Invalid selection." << endl;
}
showSelection();
cin >> choice;
}
return 0;
}

void showSelection()
{
cout << "*** Welcome to Candy Shop ***" << endl;
cout << "To select an item, enter " << endl;
cout << "1 for Candy" << endl;
cout << "2 for Chips" << endl;
cout << "3 for Gum" << endl;
cout << "4 for Cookies" << endl;
cout << "5 to exit" << endl;
}
void sellProduct(dispenserType& product, cashRegister& pCounter)
{
int amount; //variable to hold the amount entered
int amount2; //variable to hold the extra amount needed
if (product.getNoOfItems() > 0) //if the dispenser is not
empty
{
cout << "Please deposit " << product.getCost() << "
cents" << endl;
cin >> amount;
if (amount < product.getCost())
{
cout << "Please deposit another " <<
product.getCost()- amount << " cents" << endl;
cin >> amount2;
amount = amount + amount2;
}

if (amount >= product.getCost())


{
pCounter.acceptAmount(amount);
product.makeSale();
cout << "Collect your item at the bottom and "
<< "enjoy." << endl;
}

else
cout << "The amount is not enough. " <<
"Collect what you deposited." << endl;
cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" <<
endl << endl;
}
else
cout << "Sorry, this item is sold out." << endl;
}
Inheritance
[SET – 1]

Question Consider the following declaration and answer the questions given below :
1 class PPP
{
            int H:
            protected :
                        int S;
            public :
                        void INPUT (int);
                        void OUT();
};
class QQQ : private PPP
{
            int T;
            protected :
                        int U;
            public :
                        void INDATA(int, int);
                        void OUTDATA();
};
class RRR : public QQQ
{
            int M;
            public :
                        void DISP( void );
};
(i) Name the base class and derived class of the class QQQ.
(ii) Name the data member(s) that can be accessed from function DISP().
(iii) Name the member function(s), which can be accessed from the objects of class
RRR.
(iv)Is the member function OUT() accessible by the object of the class QQQ?
Question Answer the questions (i) to (iv) based on the following:
2 class PUBLISHER
{
            char Pub[12];
            double Turnover;
protected:
            void Register();
public:
            PUBLISHER();
            void Enter();
            void Display();
};
class BRANCH
{
            char CITY[20];
protected:
            float Employees;
public:
            BRANCH();
            void Haveit();
            void Giveit();
};
class AUTHOR : private BRANCH, public PUBLISHER
{
            int Acode;
            char Aname[20];
            float Amount;
public:
            AUTHOR();
            void Start();
            void Show();
};

i) Write the names of data members, which are accessible from objects belonging to
class AUTHOR.
ii) Write the names of all the member functions which are accessible from objects
belonging to class BRANCH.
iii) Write the names of all the members which are accessible from member functions
of class AUTHOR.
iv) How many bytes will be required by an object belonging to class AUTHOR?
Question Consider the following declarations and answer the question given below :
3 class vehicle
{
private:
            int wheels;
protected :
            int passenger:
public :
            void inputdata (int, int);
            void outputdata();
};
class heavyvehicle : protected vehicle
{
            int diesel_petrol;
protected :
            int load;
public:
            void readdata(int, int);
            void writedata();
};
class bus : private heavyvehicle
{
            char make[20];
public :
            void fetchdata(char);
            void displaydata();
};
(i) Name the base class and derived class of the class heavy_vehicle.
(ii) Name the data member(s) that can be accessed from function displaydata().
(iii) Name the data member's that can be accessed by an object of bus class.
(iv) Is the member function outputdata() accessible to the objects of heavy_vehicle
class.
Question Answer the questions (i) to (iv) based on the following code :
4 class Drug
{
            char Category[10];
            char Date_of_manufacture[10];
            char Company[20];
public:
            Drug();
            void enterdrugdetails();
            void showdrugdetails();
};
class Tablet : public Drug
{
            protected:
            char tablet_name[30];
            char Volume_label[20];
public:
            float Price;
            Tablet();
            void entertabletdetails();
            void showtabletdetails ();
};
class PainReliever : public Tablet
{
            int Dosage_units;
            char Side_effects[20];
            int Use_within_days;
public:
            PainReliever();
            void enterdetails();
            void showdetails();
};
(i) How many bytes will be required by an object of class Drug and an object of class
PainReliever respectively ?
(ii) Write names of all the data members which are accessible from the object of class
PainReliever.
(iii) Write names of all the members accessible from member functions of class
Tablet.
(iv) Write names of all the member functions which are accessible from objects of
class PainReliever.
Class and Object
[SET – 1]

Question 1 Define a class student with the following specification


Private members of class student
admno                        integer
sname                        20 character
eng. math, science       float
total                            float
ctotal()                        a function to calculate eng + math + science with float return
type.
Public member function of class student
Takedata()                   Function to accept values for admno, sname, eng, science and
invoke ctotal() to                                    calculate total.
Showdata()                   Function to display all the data members on the screen.
Question 2  Define a class batsman with the following specifications:
Private members:
bcode                            4 digits code number
bname                           20 characters
innings, notout, runs        integer type
batavg                           it is calculated according to the formula –
                                     batavg =runs/(innings-notout)
calcavg()                        Function to compute batavg
Public members:
readdata()                      Function to accept value from bcode, name, innings, notout
and invoke the function                                       calcavg()
displaydata()                   Function to display the data members on the screen.

Question 3 Define a class TEST in C++ with following description:


Private Members
TestCode of type integer
Description of type string
NoCandidate of type integer
CenterReqd (number of centers required) of type integer
A member function CALCNTR() to calculate and return the number of centers as
(NoCandidates/100+1)
Public Members
-  A function SCHEDULE() to allow user to enter values for TestCode, Description,
NoCandidate & call function CALCNTR() to calculate the number of Centres
- A function DISPTEST() to allow user to view the content of all the data members
Question 4  Define a class in C++ with following description:
Private Members
A data member Flight number of type integer
A data member Destination of type string
A data member Distance of type float
A data member Fuel of type float
A member function CALFUEL() to calculate the value of Fuel as per the following
criteria
            Distance                                                          Fuel
            <=1000                                                           500
            more than 1000  and <=2000                          1100
            more than 2000                                              2200
Public Members
A function FEEDINFO() to allow user to enter values for Flight Number,
Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel
A function SHOWINFO() to allow user to view the content of all the data member
Question 5 Define a class BOOK with the following specifications :
Private members of the class BOOK are
BOOK NO                integer type
BOOKTITLE             20 characters
PRICE                     float (price per copy)
TOTAL_COST()        A function to calculate the total cost for N number of copies
where N is passed to the                               function as argument.
Public members of the class BOOK are
INPUT()                   function to read BOOK_NO. BOOKTITLE, PRICE
PURCHASE()            function to ask the user to input the number of copies to be
purchased. It invokes                               TOTAL_COST() and prints the total cost to
be paid by the user.
Note : You are also required to give detailed function definitions.
Question 6 Define a class REPORT with the following specification:
Private members :
adno                         4 digit admission number
name                        20 characters
marks                       an array of 5 floating point values
average                    average marks obtained
GETAVG()                 a function to compute the average obtained in five subject
Public members:
READINFO()              function to accept values for adno, name, marks. Invoke the
function GETAVG()            
DISPLAYINFO()          function to display all data members of report on the screen.
You should give function definitions.
solution of question 1
[SET – 1]
C++ Program to Define a Class Student and accessing member function using its object

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class student
{
private:
int admno;
char sname[20];
float eng,math,science;
float total;
float ctotal()
{
return eng+math+science;
}
public:
void Takedata()
{
cout<<"Enter admission number ";
cin>> admno;
cout<<"Enter student name " ;
gets(sname);
cout<< "Enter marks in english, math, science ";
cin>>eng>>math>>science;
total=ctotal();
}
void Showdata()
{
cout<<"Admission number "<<admno<<"\nStudent name
"<<sname<<"\nEnglish "
<<eng<<"\nMath "<<math<<"\nScience "<<science<<"\nTotal
"<<total;
}
};

int main ()
{
clrscr();
student obj ;
obj.Takedata();
obj.Showdata();
getch();
return 0; }
solution of question 2
[SET – 1]
C++ Program to Define a Class Batsman and accessing member function using its object

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class batsman
{
int bcode;
char bname[20];
int innings,notout,runs;
int batavg;
void calcavg()
{
batavg=runs/(innings-notout);
}

public :
void readdata ();
void displaydata();
};

void batsman::readdata ()
{
cout<<"Enter batsman code ";
cin>> bcode;
cout<<"Enter batsman name ";
gets(bname);
cout<<"enter innings,notout and runs ";
cin>>innings>>notout>>runs;
calcavg();
}

void batsman::displaydata()
{
cout<<"Batsman code "<<bcode<<"\nBatsman name "<<bname<<"\nInnings
"<<innings
<<"\nNot out "<<notout<<"\nRuns "<<runs<<"\nBatting Average "<<batavg;
}

int main()
{
batsman obj;
obj.readdata();
obj.displaydata();
getch();
return 0;
}
solution of question 3
[SET – 1]
C++ Program to Define a Class Test and accessing member function using its object

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class TEST
{
private:
int TestCode;
char Description[30];
int NoCandidate;
int CenterReqd;
int CALCNTR()
{
return NoCandidate/100+1;
}
public:
void SCHDULE();
void DISPTEST();
};
void TEST::SCHDULE()
{
cout<<"Enter Test code ";
cin>> TestCode;
cout<<"Enter description ";
gets(Description);
cout<< "Enter no of candidates ";
cin>>NoCandidate;
CenterReqd=CALCNTR();
}

void TEST :: DISPTEST()


{
cout<<"Test code "<<TestCode<<"\nDescripton "<<Description<<"\nNo of
candidate "
<<NoCandidate<<"\nCenter required "<<CenterReqd;
}
int main ()
{
TEST obj;
obj.SCHDULE();
obj.DISPTEST();
getch(); return 0; }
solution of question 4
[SET – 1]
C++ Program to Define a Class FLIGHT and accessing member function using its object

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class TEST
{
private:
int TestCode;
char Description[30];
int NoCandidate;
int CenterReqd;
int CALCNTR()
{
return NoCandidate/100+1;
}
public:
void SCHDULE();
void DISPTEST();
};

void TEST::SCHDULE()
{
cout<<"Enter Test code ";
cin>> TestCode;
cout<<"Enter description ";
gets(Description);
cout<< "Enter no of candidates ";
cin>>NoCandidate;
CenterReqd=CALCNTR();
}

void TEST :: DISPTEST()


{
cout<<"Test code "<<TestCode<<"\nDescripton "<<Description<<"\nNo of
candidate "
<<NoCandidate<<"\nCenter required "<<CenterReqd;
}

int main ()
{
TEST obj;
obj.SCHDULE();
obj.DISPTEST();
getch();
return 0; }

You might also like