Definition of class member functions outside the class definition:
class Rectangle {
public:
int area() const; // member function declaration
private:
int l;
int w;
static int count;
};
int Rectangle::count = 0; // initialization of the static variable
int Rectangle::area() const { // member function definition
return l * w;
}
Can i access private static data count directly in main() function, like Rectangle.count=1 ? If no, should i always declare static data as public?
No and no. Making it accessible from outside the class would be no different from making it a global variable, and if that's what you want, make it a global variable. Otherwise, only let Rectangle objects, static member functions or friends access the static data. You could for example make main() a friend of the class to let it get raw access to the data (both in Rectangle objects and the static data):
class Rectangle {
private:
friend int main();
};
but this should be avoided if you can. It's most often better to create member functions for accessing the raw data - or else you'd suddenly have main() changing the count value which I guess would be a terrible idea in this case.
I know that we define member function using scope operator. but i don't know how to make them private or public.
They are what you declared them to be in your class definition. If they are declared public, they will be public etc.
Example of an instance counter:
class Rectangle {
public:
Rectangle(int L, int W);
Rectangle();
~Rectangle();
int area() const;
static unsigned get_count();
private:
int l;
int w;
static unsigned count;
};
unsigned Rectangle::count = 0;
unsigned Rectangle::get_count() {
return count;
}
Rectangle::Rectangle(int L, int W) : l(L), w(W) {
++count;
}
Rectangle::Rectangle() :
Rectangle(0, 0) // delegate
{}
Rectangle::~Rectangle() {
--count;
}
int Rectangle::area() const {
return l * w;
}
#include <iostream>
int main() {
{
Rectangle r;
std::cout << Rectangle::get_count() << "\n";
}
std::cout << Rectangle::get_count() << "\n";
}
Output:
1
0