Loading lessons...
Specifying a Class & Member Functions
Specifying a Class & Member Functions
The class is the most important feature of C++. It is an extension of the C structure: a user-defined type that binds data and the functions operating on it, and hides the data from the outside. This lesson shows how to specify a class, how to create objects, and the ways member functions can be defined and used.
1. Specifying a Class
A class specification has two parts:
- the class declaration, which describes the type and scope of its members;
- the member function definitions, which describe how the functions are implemented.
class class_name {
private:
// variable declarations; data members
// function declarations; member functions
public:
// variable declarations;
// function declarations;
}; // note the semicolon| Term | Meaning |
|---|---|
| Data members | variables declared inside the class |
| Member functions | functions declared inside the class (also called methods) |
| Class members | data members and member functions together |
private | members accessible only from within the class (and by friends) |
public | members accessible from outside the class too |
protected | like private, but also accessible in derived classes (Unit III) |
The keyword private is optional: class members are private by default. Data is usually private and functions are usually public, so the public functions form the class's interface.
A class: private data hidden behind public member functions
class Item {
int number; // private by default
float cost;
public:
void getData(int a, float b);
void putData();
};2. Creating Objects and Accessing Members
Once a class is declared, objects (also called instances) are created just like variables of a built-in type. Memory for an object's data is allocated when the object is created.
Item x; // one object
Item x, y, z; // three objectsObjects can also be created when the class is declared, by listing names after the closing brace, as with structures: class Item { ... } x, y; (rarely used).
Members are accessed with the dot operator: object.function(arguments).
x.getData(100, 75.5); // OK: getData is public
x.putData(); // OK
// x.number = 100; // error: number is private3. Defining Member Functions
Outside the class definition
The function is declared inside the class and defined outside using the scope resolution operator ::, which tells the compiler which class the function belongs to.
Inside the class definition
The declaration is replaced by the full definition. A function defined inside the class is automatically treated as inline, so only small functions are normally defined this way.
#include <iostream>
using namespace std;
class Item {
int number;
float cost;
public:
void getData(int a, float b); // declared only
void putData() { // defined inside: inline
cout << "Number: " << number << ", Cost: " << cost << endl;
}
};
void Item::getData(int a, float b) { // defined outside with ::
number = a; // members used directly by name
cost = b;
}
int main() {
Item x;
cout << "Object x" << endl;
x.getData(100, 299.95);
x.putData();
Item y;
cout << "Object y" << endl;
y.getData(200, 175.5);
y.putData();
return 0;
}Output:
Object x
Number: 100, Cost: 299.95
Object y
Number: 200, Cost: 175.5Characteristics of member functions
- Several classes can have functions with the same name; the class label (
Item::) resolves which is meant. - Member functions can access the private data of their class; non-members cannot (except friends).
- A member function can call another member function directly, without the dot operator.
- Member functions defined outside the class can be made inline explicitly with
inlinebefore the definition.
| Defined inside the class | Defined outside the class |
|---|---|
| automatically inline | not inline unless inline is written |
no :: needed | needs class-name:: |
| suits short functions | suits longer functions |
| class declaration gets long and harder to read | keeps the class declaration short (the interface is easy to see) |
4. Nesting of Member Functions
A member function can be called by another member function of the same class by name alone, with no object and no dot operator. This is called nesting of member functions.
#include <iostream>
using namespace std;
class Set {
int m, n;
public:
void input(int a, int b) {
m = a;
n = b;
}
int largest();
void display();
};
int Set::largest() {
if (m >= n) {
return m;
}
return n;
}
void Set::display() {
cout << "Largest value = " << largest() << endl; // nested call: no object needed
}
int main() {
Set s;
s.input(25, 18);
s.display();
return 0;
}Output:
Largest value = 255. Private Member Functions
Some functions should only be helpers for other member functions, not part of the public interface. Such functions are placed in the private section. A private member function can be called only by other member functions of its class, not by an object from outside.
#include <iostream>
using namespace std;
class Account {
double balance;
bool valid(double amount) {
return amount > 0;
} // private helper
public:
Account() {
balance = 0;
}
void deposit(double amount) {
if (valid(amount)) { // OK: called from a member
balance = balance + amount;
} else {
cout << "Invalid amount " << amount << endl;
}
}
void show() {
cout << "Balance = " << balance << endl;
}
};
int main() {
Account a;
a.deposit(500);
a.deposit(-50);
// a.valid(10); // error: valid is private
a.show();
return 0;
}Output:
Invalid amount -50
Balance = 5006. Memory Allocation for Objects
Member functions are shared; each object has its own data
- Member functions are created and placed in memory once, when they are defined. All objects of the class share the same copy, because the code is the same for every object.
- Data members get separate memory for each object, because each object holds different values.
So sizeof(Item) is roughly the size of its data members; the functions add nothing to each object.
7. A Complete Example: Array Inside a Class
Arrays can be data members, which makes classes like a shopping list possible.
#include <iostream>
using namespace std;
const int MAX = 10;
class ShoppingList {
int code[MAX];
float price[MAX];
int count;
public:
void init() {
count = 0;
}
void addItem(int c, float p);
float total();
void showAll();
};
void ShoppingList::addItem(int c, float p) {
if (count < MAX) {
code[count] = c;
price[count] = p;
count++;
}
}
float ShoppingList::total() {
float sum = 0;
for (int i = 0; i < count; i++) {
sum = sum + price[i];
}
return sum;
}
void ShoppingList::showAll() {
for (int i = 0; i < count; i++) {
cout << "Item " << code[i] << " : Rs " << price[i] << endl;
}
cout << "Total : Rs " << total() << endl; // nested member call
}
int main() {
ShoppingList order;
order.init();
order.addItem(111, 45.5);
order.addItem(222, 120);
order.addItem(333, 15.25);
order.showAll();
return 0;
}Output:
Item 111 : Rs 45.5
Item 222 : Rs 120
Item 333 : Rs 15.25
Total : Rs 180.758. Class vs Structure in C++
class | struct |
|---|---|
| members private by default | members public by default |
| inheritance is private by default | inheritance is public by default |
| used for objects with behaviour and hidden data | traditionally used for plain data records |
Apart from these defaults, a C++ struct can do everything a class can (member functions, constructors, inheritance). A C struct can only hold data.
Key points to remember
- A class = data members + member functions; members are private by default; end the declaration with
;. - Define members inside the class (automatically inline) or outside with
ClassName::. - A member function can call another member function by name (nesting) and use private data directly.
- Private member functions are helpers callable only by other members.
- Functions are stored once and shared; each object has its own data members.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. How is a class specified in C++? Explain the two ways of defining member functions with a program. (10 Marks)
- Write: the general form, private/public, the
Itemprogram with one function defined inside and one outside, and the inside/outside table. - Q2. What is nesting of member functions? Give an example. (2.5 Marks)
- Q3. What are private member functions? How are they called? (2.5 Marks)
- Q4. Explain how memory is allocated for objects of a class. (5 Marks)
- Write: the diagram; functions shared once, data per object.
- Q5. Differentiate between a class and a structure in C++. (2.5 Marks)