How should I write a copy constructor for my singleton class to prevent the creation of a new object as I already have one . And what is the best practice to overload = operator for same
#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;
class Rect
{
int length;
int breadth;
static int count;
static int maxcount;
Rect()
{};
Rect(const Rect& abc){};
public :
~Rect();
int area_rect()
{return length*breadth;}
void set_value(int a,int b);
static Rect* instance()
{
Rect* ptr=NULL;
if(count < maxcount)
{
ptr=new Rect ;
count++;
}
return ptr;
}
};
int Rect::count = 0;
int Rect::maxcount = 1;
void Rect::set_value(int a,int b)
{
length=a;
breadth=b;
}
Rect::~Rect()
{
count --;
}
int main()
{
Rect* a= Rect::instance(); //creates first object
// Rect* c= Rect::instance(); //fails to create second object
//as maxcount=1 and returns NULL
a->set_value(10,3);
cout << "area realted to object a : " << a->area_rect() <<"\n";
Rect* b=a;//allows creation of second object which I dont want
b->set_value(10,4);
cout << "area realted to object b : " << b->area_rect() <<"\n";
delete a;
delete b;
getch();
return 0;
}
How to write copy constructor code and overloading equal operator for prevention of creation of further object?