UNIT-2: Classes and Object, Dynamic Constructor & Destructor BCA-2 Sem
UNIT-2: Classes and Object, Dynamic Constructor & Destructor BCA-2 Sem
UNIT-2: Classes and Object, Dynamic Constructor & Destructor BCA-2 Sem
1.Public
2.Private
3.protected
Data member type
#include <iostream>
using namespace std;
class alpha{
private:
int id;
static int count;
public:
alpha(){count++;
id=count;}}
Data member type
void print(){
cout<<"My id is"<<id;
cout<<"countis"<<count;} };
int alpha : :count=0;
void main (){
alpha a1,a2,a3;
a1.print();
a2.print();
a3.print();}
Array of object
class A
{
int* myArray;
A()
{
myArray = 0;
}
A(int size)
{
Array of object
myArray = new int[size];
}
~A()
{
delete [] myArray;
}
}
Returning Objects from Functions
#include <iostream>
class Complex{
private: int real;
int imag;
public: Complex():
real(0), imag(0){ }
void Read() {
// Constructor with two parameters
construct(int a, int b)
{
area = a * b;
}
void disp()
{
cout<< area<< endl;
}
};
Continue…
}
void Display()
{
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
};
int main()
{
Continue…
Complex c1,c2,c3;
c1.Read();
c2.Read();
c3=c1.Add(c2);
c3.Display();
return 0; }
Constructor
• A constructor in C++ is a special method that is
automatically called when an object of a class is
created
2. Dynamic constructor
3. Copy Constructor
4. Default Constructor
1.Overloaded Constructors
• It has no parameters
Parameterized Constructor(with arguments)
float x,y;
int a(10), b(20);
float i(2.5), j(7.8);
Destructor
• The syntax for declaring a destructor is :
-name_of_the_class()
{
}
• It does not take any parameter nor does it return any
value. Overloading a destructor is not possible and
can be explicitly invoked
• In other words, a class can have only one destructor.
A destructor can be defined outside the class
Characteristics of Destructors
• These are called automatically when the objects are
destroyed.
• Syntax:
function_name(object_name);