Loading lessons...
Static Members, Arrays of Objects & Objects as Arguments
Static Members, Arrays of Objects & Objects as Arguments
Normally each object has its own copy of every data member. Sometimes, though, a value belongs to the class as a whole: how many objects exist, a common interest rate, the next free ID number.
C++ provides static data members and static member functions for this. The lesson then covers arrays of objects, objects as function arguments, returning objects and const member functions.
1. Static Data Members
A data member declared with the keyword static is a static data member.
- It is initialised to zero when the first object is created, if no other initial value is given.
- Only one copy of it is created for the entire class and shared by all objects, however many there are.
- It is visible only within the class, but its lifetime is the entire program.
Because it is shared, it must be defined once outside the class, which allocates its storage:
One static member shared by all objects of the class
#include <iostream>
using namespace std;
class Item {
static int count; // declaration: one copy for the class
int number; // one copy per object
public:
void getData(int a) {
number = a;
count++; // every object updates the same count
}
void getCount() {
cout << "count: " << count << endl;
}
};
int Item::count; // definition outside the class (starts at 0)
int main() {
Item a, b, c;
a.getCount();
b.getCount();
c.getCount();
a.getData(100);
b.getData(200);
c.getData(300);
cout << "After reading data" << endl;
a.getCount();
b.getCount();
c.getCount();
return 0;
}Output:
count: 0
count: 0
count: 0
After reading data
count: 3
count: 3
count: 3All three objects report the same count, because there is only one.
Uses: counting objects, a value shared by all objects (a rate, a limit), and generating unique IDs.
2. Static Member Functions
A member function declared static:
- can access only other static members (static data and static functions) of its class;
- has no
thispointer, because it is not called for a particular object; - is called using the class name:
class-name::function-name()(calling it through an object is also allowed); - cannot be
virtualorconst.
#include <iostream>
using namespace std;
class Test {
int code;
static int count; // static data
public:
void setCode() {
code = ++count;
} // unique code from the shared counter
void showCode() {
cout << "object number: " << code << endl;
}
static void showCount() { // static function
cout << "count: " << count << endl;
// cout << code; // error: code is not static
}
};
int Test::count;
int main() {
Test t1, t2;
t1.setCode();
t2.setCode();
Test::showCount(); // called with the class name
Test t3;
t3.setCode();
Test::showCount();
t1.showCode();
t2.showCode();
t3.showCode();
return 0;
}Output:
count: 2
count: 3
object number: 1
object number: 2
object number: 3| Static member function | Non-static (ordinary) member function |
|---|---|
| belongs to the class | belongs to each object |
called as Class::f() (no object needed) | called as obj.f() |
| can use only static members | can use all members |
no this pointer | has a this pointer |
| cannot be virtual | can be virtual |
3. Arrays of Objects
An array can hold objects of a class, just as it holds ints. Each element is an object, and members are reached with array[i].member.
#include <iostream>
using namespace std;
class Employee {
char name[30];
float age;
public:
void setData(const char* n, float a) {
int i = 0;
while (n[i] != '\0' && i < 29) {
name[i] = n[i];
i++;
}
name[i] = '\0';
age = a;
}
void putData() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
const int SIZE = 3;
int main() {
Employee manager[SIZE]; // array of 3 objects
const char* names[SIZE] = {"Arjun", "Meera", "Kabir"};
float ages[SIZE] = {45, 38, 50};
for (int i = 0; i < SIZE; i++) {
manager[i].setData(names[i], ages[i]);
}
for (int i = 0; i < SIZE; i++) {
cout << "Manager " << i + 1 << ": ";
manager[i].putData();
}
return 0;
}Output:
Manager 1: Name: Arjun, Age: 45
Manager 2: Name: Meera, Age: 38
Manager 3: Name: Kabir, Age: 50In memory the objects are stored one after another; only the data members are stored per element, exactly as for a single object.
4. Objects as Function Arguments
An object can be passed to a function in two ways:
| Method | What happens |
|---|---|
| Pass by value | a copy of the whole object is passed; changes inside the function do not affect the original |
| Pass by reference (or by address) | only the address is passed; the function works on the original, which is faster for large objects |
The function receiving the object may be a member function, a friend, or a non-member (which can then use only the public members).
5. Returning Objects
A function can also return an object. The example adds two times: sum receives two Time objects and returns a new Time object.
#include <iostream>
using namespace std;
class Time {
int hours, minutes;
public:
void setTime(int h, int m) {
hours = h;
minutes = m;
}
void show() {
cout << hours << " hours and " << minutes << " minutes" << endl;
}
Time add(Time t); // object as argument, object as result
};
Time Time::add(Time t) {
Time result;
result.minutes = minutes + t.minutes; // own data + argument's data
result.hours = hours + t.hours + result.minutes / 60;
result.minutes = result.minutes % 60;
return result; // returns an object
}
int main() {
Time t1, t2, t3;
t1.setTime(2, 45);
t2.setTime(3, 30);
t3 = t1.add(t2); // t1 calls add with t2 as argument
cout << "T1 = ";
t1.show();
cout << "T2 = ";
t2.show();
cout << "T3 = ";
t3.show();
return 0;
}Output:
T1 = 2 hours and 45 minutes
T2 = 3 hours and 30 minutes
T3 = 6 hours and 15 minutesInside add, minutes means t1.minutes (the object that called the function) and t.minutes means t2.minutes. A member function can access the private members of any object of its own class, not just the calling one.
6. const Member Functions
A member function that does not modify the object should be declared const by writing const after the parameter list. The compiler then reports an error if the function tries to change a data member, and only const member functions can be called on a const object.
#include <iostream>
using namespace std;
class Circle {
double radius;
public:
Circle(double r) {
radius = r;
}
double area() const {
return 3.14159 * radius * radius;
} // read-only
void grow(double d) {
radius = radius + d;
} // modifies
};
int main() {
const Circle c(2); // a constant object
cout << "area = " << c.area() << endl; // OK: area() is const
// c.grow(1); // error: grow() is not const
Circle d(1);
d.grow(1);
cout << "area = " << d.area() << endl;
return 0;
}Output:
area = 12.5664
area = 12.5664A data member declared mutable may be changed even inside a const function (useful for counters or caches).
Key points to remember
- A static data member has one copy for the whole class, starts at 0, and must be defined outside the class:
int Item::count;. - A static member function uses only static members, has no
this, and is called asClass::f(). - Arrays of objects:
Employee m[3]; m[i].putData();. - Objects can be passed by value (a copy) or by reference (the original), and returned from functions.
constmember functions promise not to change the object; only they can be called onconstobjects.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What are static data members and static member functions? Write a program to count the number of objects created. (10 Marks)
- Write: the three properties of static data, the definition outside the class, the four properties of static functions, the
ItemorTestprogram, and the comparison table. - Q2. Write a program to add two time objects by passing objects as arguments and returning an object. (5 Marks)
- Write: the
Timeprogram and its output; explain whoseminutesis whose. - Q3. Explain arrays of objects with an example. (5 Marks)
- Q4. What is a
constmember function? (2.5 Marks) - Q5. Why must a static data member be defined outside the class? (2.5 Marks)