Lesson 13 +30 XP

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:

  1. the class declaration, which describes the type and scope of its members;
  2. the member function definitions, which describe how the functions are implemented.
C++
class class_name {
private:
    // variable declarations;   data members
    // function declarations;   member functions
public:
    // variable declarations;
    // function declarations;
}; // note the semicolon
TermMeaning
Data membersvariables declared inside the class
Member functionsfunctions declared inside the class (also called methods)
Class membersdata members and member functions together
privatemembers accessible only from within the class (and by friends)
publicmembers accessible from outside the class too
protectedlike 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 functionsA class: private data hidden behind public member functions

C++
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.

C++
Item x;       // one object
Item x, y, z; // three objects

Objects 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).

C++
x.getData(100, 75.5); // OK: getData is public
x.putData();          // OK
// x.number = 100;      // error: number is private

3. 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.

return-type class-name :: function-name(arguments) { body }

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.

C++
#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:

OUTPUT
Object x
Number: 100, Cost: 299.95
Object y
Number: 200, Cost: 175.5

Characteristics of member functions

  1. Several classes can have functions with the same name; the class label (Item::) resolves which is meant.
  2. Member functions can access the private data of their class; non-members cannot (except friends).
  3. A member function can call another member function directly, without the dot operator.
  4. Member functions defined outside the class can be made inline explicitly with inline before the definition.
Defined inside the classDefined outside the class
automatically inlinenot inline unless inline is written
no :: neededneeds class-name::
suits short functionssuits longer functions
class declaration gets long and harder to readkeeps 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.

C++
#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:

OUTPUT
Largest value = 25

5. 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.

C++
#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:

OUTPUT
Invalid amount -50
Balance = 500

6. Memory Allocation for Objects

Member functions are shared; each object has its own dataMember 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.

C++
#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:

OUTPUT
Item 111 : Rs 45.5
Item 222 : Rs 120
Item 333 : Rs 15.25
Total : Rs 180.75

8. Class vs Structure in C++

classstruct
members private by defaultmembers public by default
inheritance is private by defaultinheritance is public by default
used for objects with behaviour and hidden datatraditionally 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.

💡 Tip

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.
🎯 END-TERM EXAM PREP

📝 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 Item program 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)