Hello geovoulg,
I can see why you are having problems. You code is hard to read and is missing some key parts like the include files and "main".
Without the rest of the code what you have posted does not compile and is full of errors.
Also I have no idea what you are doing in "main" or how you are dealing with the class.
1. My first problem is how to create a constructor which will increase the number of objects by one (1)
2. and will print a message that a new object is created,
3. and a destructor which will reduce the number of objects by one (1).
I wrote the destructor as well as the constructor but I guess the constructor is not right.
|
For point 1 just doing something that will call the ctor will increase the number of objects by 1. Using the ctor to create a new object of the class makes me thing of an endless loop with no way out. How would you know when to stop? That is if it would even work in the first place.
Point 2 is easy that is just a "cout" statement in the ctor.
Since your code is hard to read I off this suggestion:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
using namespace std;
class integer
{
int x{};
public:
int objnum{};
integer() {};
integer(int a) : x(a) {}
void set_x(int a) { x = a; }
int get_x() { return x; }
void display() { cout << "X is :" << x; }
int sgobjnum(int b) { objnum = b; return objnum; }
void show() { cout << "Number of objects is : " << objnum; }
integer(integer& obj)
{ // The constructor in question
if (obj += 1)
{
objnum++;
cout << "New object created" << endl;
}
}
~integer()
{
objnum--;
cout << "New object deleted" << endl;
}
friend int doublevalue(integer& obj);
friend int returnobj(int k);
};
int doublevalue(integer& obj)
{
int doublev;
doublev = (obj.x) * 2;
return doublev;
}
int returnobj(int k)
{ //The function in question
integer obj;
return obj.x = k;
}
|
Seeing the code in this way I noticed
int doublev;
. After a while it did make sense because you are multiplying by 2, but at first it is misleading. I would just use "v", but I would give it a better name then "v". Something to think about.
In your problem function try this:
1 2 3 4 5 6 7 8
|
interger returnobj(int k)
{ //The function in question
integer obj;
obj.set_x = k;
return obj;
}
|
Just a thought. Your code looks more like you are setting the value of "x" = "k" and then returning the new variable and not the whole object.
But without the missing code that is just a guess for now.
Andy