This seems like bad coding practice, but it was the guidelines given to me. I want to preface by saying I have no idea how this will actually be implemented in the main, Im just writing the class.
class Example
{
private:
static int total;
public:
void initalizeTotal();
}
Example::initalizeTotal()
{
total = 0;
}
total will (I guess) be used to count the number of objects of that class. This is basically what I'm getting at. The problem is how I figure out how to actually call the function. I can't just call it in the constructor, sense that would reset total each time. And I've tried and failed "check" if the variable has a value yet and if not, call the function.
Is there any advice anyone can give?
EDIT: I forgot to include that total is static. And that i MUST have a function that initializes total. Thats a requirement of the assignment.
Since total
should be the same variable for every object, you should make it static
:
class Example {
private:
static int total;
}
To initialize a static variable, you can place this line in a .cpp file:
int Example::total = 0;
You do not need to call any function to do this initialization.
You can make total
variable static:
class Example
{
private:
void addObject();
public:
static int total;
Example();
}
Example::Example()
{
addObject();
}
void Example::addObject()
{
total++;
}
So that it will not belong to any specific object. If you then increase it's value in addObject()
method which will be called in a constructor, you will get objects count.
To access it, you will not be using any Example
object, but instead you may use it like this:
std::cout << "Objects count:" << Example::total;
If you want to initialize it, you do it same way somewhere in your code:
Example::total = 0;
You have to use 'total'
field as static
variable in order to share with all created objects of type Example
. And any time instantating a new object increase the total
field. Hope this help
Try the following:
#include <iostream>
class Example {
static int total;
public:
Example() { total++; }
static int getTotal() { return total; }
};
int Example::total = 0;
int main() {
Example a, b, c, d;
std::cout << Example::getTotal(); // 4
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.