CONSTRUCTOR AND DESTRUCTOR (C++)
CONSTRUCTOR AND DESTRUCTOR (C++)
CONSTRUCTOR AND DESTRUCTOR (C++)
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;
}
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.
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>
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)
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.
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.
Containership:When a class contains objects of other class types as its members, it is called
containership.It is also called containment,composition, aggregation.
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.
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 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 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.
//************************************************************
// 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;
}
dispenserType::dispenserType()
{
numberOfItems = 50;
cost = 50;
}
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;
}
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]
#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();
}
#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();
}
int main ()
{
TEST obj;
obj.SCHDULE();
obj.DISPTEST();
getch();
return 0; }