Question 1 14 marks
Procedure-Oriented Programming (POP)
In procedure-oriented programming, a program is viewed as a sequence of tasks. The problem is divided into functions (procedures), and the main focus is on what steps must be performed. Most of the data is kept global and is shared by all functions, so data moves openly from one function to another. Program design follows the top-down approach. Examples: C, Pascal, FORTRAN, COBOL.
Object-Oriented Programming (OOP)
In object-oriented programming, a program is divided into objects. Each object combines data (attributes) and the functions (methods) that work on that data into one unit. Data is hidden from outside functions and can be accessed only through the object's own methods. Program design follows the bottom-up approach. Examples: C++, Java, C#, Python.
Differences between POP and OOP
| Basis | Procedure-Oriented Programming | Object-Oriented Programming |
|---|---|---|
| Basic unit | Program is divided into functions. | Program is divided into objects. |
| Focus | Importance is given to functions (algorithms). | Importance is given to data. |
| Design approach | Top-down approach. | Bottom-up approach. |
| Data security | Data is global and can be changed by any function; less secure. | Data is hidden inside objects (data hiding); more secure. |
| Access specifiers | No access specifiers. | Has private, protected and public. |
| Data movement | Data moves freely from function to function. | Objects communicate through member functions (message passing). |
| Adding new data / functions | Difficult; a change in global data affects many functions. | Easy; new data and functions can be added to a class without disturbing others. |
| Reusability | Limited reusability. | High reusability through inheritance. |
| Polymorphism / overloading | Not supported. | Function and operator overloading, virtual functions are supported. |
| Real-world modelling | Poor; does not map naturally to real-world entities. | Good; objects model real-world entities. |
| Suitable for | Small and simple programs. | Large and complex software. |
| Examples | C, Pascal, FORTRAN, COBOL. | C++, Java, C#, Python. |
Small example
Conclusion: POP concentrates on procedures, whereas OOP concentrates on data and the objects that own it. Because of data hiding, inheritance and polymorphism, OOP is preferred for large, real-world software.
Object Oriented Programming
Object Oriented Programming (OOP) is a programming approach in which a program is organised around objects rather than functions. An object is a unit that contains data and the functions that operate on that data. OOP provides a way of modularising a program by creating separate memory areas for data and functions, which can be used as templates (classes) to create as many copies (objects) as needed.
Characteristics of OOP: emphasis is on data rather than procedure; programs are divided into objects; data is hidden and cannot be accessed by external functions; objects communicate with each other through functions; new data and functions can be easily added; follows the bottom-up approach.
Features of the Object-Oriented Paradigm
1. Class - A class is a user-defined data type that acts as a blueprint for objects. It defines the data members and member functions that its objects will have. Example: class Car { string model; void drive(); };
2. Object - An object is an instance of a class; it is a run-time entity that occupies memory. Every object has state, behaviour and identity. Example: Car c1, c2; creates two objects of class Car.
3. Encapsulation - Wrapping up of data and functions into a single unit (class) is called encapsulation. The data is not accessible to the outside world; only the class functions can access it. This insulation of data is called data hiding. Example: balance is private in class Account and is changed only through deposit() and withdraw().
4. Data Abstraction - Abstraction means representing the essential features without including the background details. A class gives an abstract view: the user knows what an object does, not how it does it. Example: a driver uses the steering and brake without knowing the internal engine mechanism.
5. Inheritance - Inheritance is the process by which objects of one class acquire the properties of another class. It supports reusability and represents an "is-a" relationship. Example: class Car : public Vehicle { }; - a Car is a Vehicle.
6. Polymorphism - Polymorphism means "one name, many forms". The same function or operator behaves differently in different situations. Example: + adds two numbers but joins two strings; area() computes the area of a circle or a rectangle depending on the object.
7. Dynamic Binding - Binding means linking a function call with the code to be executed. In dynamic (late) binding, the code to be executed is decided at run time. It is achieved in C++ through virtual functions.
8. Message Passing - Objects communicate with one another by sending and receiving messages. A message is a request to an object to execute one of its methods. Example: account.withdraw(500); - here account is the receiver, withdraw is the message and 500 is the information passed.
Question 2 14 marks
Encapsulation
Encapsulation is the wrapping up of data and the functions that operate on that data into a single unit called a class. The data is kept private, so it cannot be accessed directly from outside; it can be used only through the public member functions of the class. This protection of data is called data hiding or information hiding. Example: A capsule wraps different medicines inside one cover; similarly a class wraps data and functions.
Data abstraction
Data abstraction is the process of representing only the essential features of an object and hiding the background details (implementation). The user knows what an object does through its public interface but not how it does it. Example: We switch on a TV with a remote without knowing the internal circuit. In C++, abstraction is achieved by classes with public member functions, by header files, and by abstract classes. Classes that use this concept are called Abstract Data Types (ADT).
| Basis | Encapsulation | Data Abstraction |
|---|---|---|
| Meaning | Binding data and functions together and hiding data. | Showing only essential details, hiding implementation. |
| Level | Implementation level - how data is protected. | Design level - what is shown to the user. |
| Achieved by | Class + access specifiers (private, public). | Public interface, abstract classes, header files. |
| Focus | Data protection (data hiding). | Reducing complexity. |
| Example | balance is private in BankAccount. | User calls withdraw() without knowing its checks. |
How these concepts enhance software development
- Security and integrity - data cannot be changed accidentally; every change passes through validated methods.
- Reduced complexity - programmers use objects through simple interfaces without knowing internal details.
- Easy maintenance - the internal code of a class can be changed without affecting the code that uses it.
- Modularity and team work - each class is an independent module that can be developed and tested separately.
- Reusability - well-encapsulated classes can be reused in other programs.
- Loose coupling - modules depend on interfaces, not on implementations, so the system is flexible.
Program demonstrating encapsulation and abstraction
Here holder and balance are encapsulated (private). The user works only with deposit(), withdraw() and getBalance(); the validation done by the private function isValid() is abstracted (hidden).
Scope and lifetime of a variable
- Scope is the region of the program in which a variable is visible and can be used.
- Lifetime is the duration for which the variable exists in memory during execution.
| Variable | Scope | Lifetime |
|---|---|---|
| Local (automatic) | Block / function in which it is declared | Created when the block is entered, destroyed when it ends |
| Static local | Block in which it is declared | Whole program; keeps its value between calls |
| Global | Entire file (from point of declaration) | Whole program |
Dynamic (new) | Through the pointer that holds it | From new until delete |
| Data member | Class scope (accessed through the object) | Same as the lifetime of its object |
Message passing
In OOP, objects communicate with one another by sending and receiving messages. A message is a request to an object to invoke one of its methods. The object that sends the request is the sender and the object that receives it is the receiver. The receiver responds by executing the method and may return a result.
A message has three parts: (1) the receiver object, (2) the name of the method to be invoked and (3) the information (arguments) needed by the method.
Steps in message passing
- Create classes that define objects and their behaviour.
- Create objects from the classes.
- Establish communication: the sender object calls a method of the receiver object.
- The receiver executes the method and returns the response.
How message passing facilitates communication between objects
- Data stays hidden: the sender never touches the receiver's data directly; it only asks the receiver to act, which preserves encapsulation.
- Loose coupling: the sender needs to know only the method name and arguments, not the internal implementation.
- Natural modelling: it mirrors real life - a customer asks the bank to withdraw money.
- Supports polymorphism: the same message (e.g.
draw()) can be sent to different objects, and each responds in its own way. - Modularity: objects can be developed and replaced independently as long as they understand the same messages.
Achieving message passing in C++
In C++, message passing is done by calling member functions of objects using the dot operator (obj.method(args)) or the arrow operator with pointers (ptr->method(args)). Arguments carry the information and the return value carries the reply.
Here the Customer object sends the message withdraw(price) to the Account object; the account decides whether the request is allowed and replies with true or false.
Question 3 14 marks
Association
Association is a relationship between two (or more) classes in which the objects of one class are connected with and use the objects of another class. Both objects have their own independent lifetime; neither owns the other. It is described as a "uses-a" or "knows-a" relationship. Examples: Doctor - Patient, Teacher - Student, Customer - Bank, Driver - Car. In C++, association is implemented by keeping a pointer or reference to the other object, or by passing the object to a member function.
Types of association
(a) Based on multiplicity (number of objects involved)
| Type | Meaning | Example |
|---|---|---|
| One-to-one (1 : 1) | One object is linked with exactly one object. | Person - Passport |
| One-to-many (1 : *) | One object is linked with many objects. | Teacher - Students |
| Many-to-one (* : 1) | Many objects are linked with one object. | Students - College |
| Many-to-many ( : ) | Many objects are linked with many objects. | Students - Courses |
(b) Based on direction
- Unidirectional association - only one class knows the other (a
Customerknows itsOrder, butOrderdoes not keep the customer). - Bidirectional association - both classes know each other (a
Doctorhas a list of patients and eachPatientknows the doctor).
(c) Reflexive (self / unary) association - a class is associated with itself. Example: an Employee is the manager of other employees.
(d) Special forms of association
- Aggregation (weak "has-a"): the part can exist without the whole - Department and Teacher.
- Composition (strong "part-of"): the part cannot exist without the whole - House and Room.
Program: association
The Doctor object uses Patient objects through a reference, but neither creates nor destroys the other - this is a pure association.
Inheritance
Inheritance is the mechanism by which a new class acquires the data members and member functions of an existing class. The existing class is called the base class (parent / super class) and the new class is called the derived class (child / sub class). The derived class can use the inherited members, add its own members and redefine (override) inherited functions. Inheritance represents an "is-a" relationship - a Car is a Vehicle.
Syntax:
Role (purpose) of inheritance
- Code reusability - code written once in the base class is reused by all derived classes.
- Extensibility - new features are added in derived classes without changing tested base code.
- Hierarchical classification - real-world "is-a" hierarchies are represented naturally (Animal → Mammal → Dog).
- Supports polymorphism - a base-class pointer can refer to derived objects and call overridden functions.
- Less redundancy and easier maintenance - common code is kept in one place, so a correction is made only once.
- Saves time and cost of development and testing.
Types of inheritance
1. Single inheritance - one derived class inherits from one base class.
2. Multiple inheritance - one derived class inherits from two or more base classes.
3. Multilevel inheritance - a class is derived from another derived class (a chain).
4. Hierarchical inheritance - many derived classes inherit from one base class.
5. Hybrid inheritance - a combination of two or more types (for example hierarchical + multiple). It may lead to the diamond problem, which is solved with virtual base classes (see the answer on ambiguity in multiple inheritance).
Program: single and multilevel inheritance
ElectricCar uses setWheels() and showWheels() of Vehicle and drive() of Car without rewriting them - this is reusability through inheritance.
Question 4 14 marks
Polymorphism
The word polymorphism comes from Greek: poly = many, morph = forms. In OOP, polymorphism is the ability of one name (function or operator) to take many forms, i.e. the same message produces different behaviour depending on the type of data or object. Real-life example: a person behaves as a student in college, a customer in a shop and a son at home - one person, many roles. Programming example: + adds two integers but joins two strings.
Types of polymorphism
1. Compile-time (static) polymorphism - the function to be called is decided by the compiler from the number and types of arguments (early / static binding). It is implemented by:
- Function overloading - many functions with the same name but different parameter lists.
- Operator overloading - giving an extra meaning to an existing operator for user-defined types.
- Templates - generic functions / classes that work with any data type.
2. Run-time (dynamic) polymorphism - the function to be called is decided at run time according to the actual object pointed to (late / dynamic binding). It is implemented by:
- Function overriding with virtual functions - a derived class redefines a virtual function of its base class, and the call is made through a base-class pointer or reference.
Ways to implement polymorphism in C++ (in brief)
Function / method overloading
When two or more functions in the same scope have the same name but different parameter lists (number, type or order of parameters), it is called function overloading. The compiler selects the right function by matching arguments, so it is compile-time polymorphism. The return type alone cannot distinguish overloaded functions.
Function / method overriding
When a derived class redefines a function of its base class with the same name, same parameters and same return type, it is called function overriding. The derived version replaces the base version for derived objects. If the base function is declared virtual and called through a base pointer/reference, the call is resolved at run time, so it gives run-time polymorphism.
Differences
| Basis | Function overloading | Function overriding |
|---|---|---|
| Definition | Same name, different parameters. | Same name, same parameters, in base and derived class. |
| Scope | Within the same class (or scope). | Across base and derived classes. |
| Inheritance | Not required. | Required. |
| Signature | Must differ. | Must be the same. |
| Return type | Can differ (but not used to overload). | Must be the same (or covariant). |
virtual keyword | Not used. | Used in base class for run-time behaviour. |
| Polymorphism | Compile-time (static). | Run-time (dynamic). |
| Purpose | Same operation on different types of data. | Change / specialise inherited behaviour. |
| Example | area(int), area(float, float) | Animal::sound() and Dog::sound() |
Idea: One function name area() is overloaded three times with different parameter lists: one int for a square, two float values for a rectangle and one double for a circle. The compiler chooses the correct version from the type and number of arguments.
Explanation: s.area(side) matches area(int), s.area(l, b) matches area(float, float) and s.area(r) matches area(double). This selection at compile time is compile-time polymorphism through method overloading.
Question 5 14 marks
Thread and multithreading
A thread is the smallest unit of execution within a process - a single sequential flow of control with its own program counter and stack. Multithreading is the ability of a program (process) to run two or more threads concurrently, so that different parts of the program execute at the same time. All threads of a process share the same memory (code and data), which makes them lightweight compared with separate processes. Example: in a word processor, one thread accepts typing, another checks spelling and a third auto-saves the file.
Multithreading in the object-oriented approach
In OOP, a thread is itself represented as an object. In Java, a thread is created by extending the Thread class or implementing the Runnable interface and overriding run(). In C++11 and later, the std::thread class (header <thread>) creates a thread object that runs a function or a member function of an object; join() waits for it to finish. Shared data is protected with synchronization objects such as std::mutex.
States of a thread: New (created) → Runnable (ready, waiting for CPU) → Running (executing) → Blocked / Waiting (waiting for I/O, lock or sleep) → back to Runnable → Terminated (finished).
Importance and benefits (advantages)
- Better responsiveness - a program remains responsive (a GUI does not freeze) while a long task runs in another thread.
- Better CPU utilisation - on multi-core processors, threads run in parallel and use all cores.
- Resource sharing - threads share memory and files of the process, so communication between them is easy.
- Economy - creating and switching threads is cheaper than creating processes.
- Faster execution - independent tasks are done simultaneously (downloading several files together).
- Simplified modelling - concurrent real-world activities are modelled naturally as concurrent objects.
Problems to handle: race conditions, deadlock and starvation; they are controlled through synchronization (mutex, locks, semaphores).
Applications
Web servers handling many clients at once; GUI applications; games (rendering, sound, input in separate threads); media players and video streaming; downloading managers; banking and ATM servers processing many transactions; real-time and embedded systems; scientific simulations and parallel computing.
Program
One possible output (the order of lines may change on every run because threads run concurrently):
Data collection and collection class
A data collection is an object that groups multiple elements into a single unit so that they can be stored, retrieved and processed easily (for example a list of students or the accounts of a bank). A collection class (container class) is a class whose objects hold other objects and provide operations such as insert, delete, search, sort and traverse. In C++, collection classes are provided by the Standard Template Library (STL) as containers, used together with iterators and algorithms. In Java they are provided by the Collections Framework (ArrayList, LinkedList, HashSet, HashMap).
Types of collections in C++ (STL containers)
1. Sequence containers - store elements in a linear order: array (fixed size), vector (dynamic array), deque (double-ended queue), list (doubly linked list), forward_list (singly linked list).
2. Associative containers - store elements in sorted order using balanced trees: set (unique keys), multiset (duplicate keys), map (unique key-value pairs), multimap.
3. Unordered associative containers - use hash tables: unordered_set, unordered_map, unordered_multiset, unordered_multimap.
4. Container adapters - restricted interfaces built on other containers: stack (LIFO), queue (FIFO), priority_queue (highest priority first).
Library Management System (LMS)
A Library Management System is software that manages the day-to-day work of a library: keeping the record of books and members, issuing and returning books, calculating fines and searching the catalogue.
Functionalities
- Book management - add, update, remove and search books (by title, author, ISBN).
- Member management - register students / faculty, update details, issue library cards.
- Issue and return - issue a book if it is available and the member is within the limit; record due date; accept returns.
- Fine calculation - charge a fine for late return.
- Reservation - reserve a book that is currently issued.
- Reports - list of issued books, overdue books, member history.
- Login and roles - librarian (administrator) and member access.
Architecture (three layers)
- Presentation layer - user interface: menus / screens for the librarian and members.
- Business logic layer - classes
Library,Book,Member,Librarian,Transaction,Finethat implement the rules. - Data layer - files or a database that store books, members and transactions permanently.
Explanation of the diagram
- Library aggregates many Book objects and many Member objects (books and members exist independently of the library software).
- Student and Faculty inherit from Member (is-a); they differ in the maximum number of books allowed.
- Librarian manages the library: adds books, registers members, issues and returns books.
- Each Transaction (issue / return) is associated with one Member and one Book and has a Fine if the book is returned late (composition - the fine has no meaning without the transaction).
Use of strings, exception handling and collections
| Feature | Use in LMS |
|---|---|
| Strings | Book title, author, member name; searching by keyword with find(); formatting reports. |
| Exception handling | Throw exceptions for book not found, book already issued, issue limit exceeded, invalid member id; catch them and show a message without stopping the program. |
| Collections | map<int, Book> - books by id for fast search; map<int, Member> - members; vector<int> - books issued to a member; queue<int> - reservation list; list<Transaction> - transaction log. |
Program (core of LMS)
Question 6 14 marks
Exception
An exception is an unusual condition or run-time error that occurs during the execution of a program and disturbs its normal flow. Examples: division by zero, array index out of range, file not found, insufficient memory, invalid input.
- Synchronous exceptions - caused by the program itself (divide by zero, out-of-range index); C++ exception handling deals with these.
- Asynchronous exceptions - caused by events outside the program (keyboard interrupt, hardware failure).
Logic: If x - y is zero the denominator becomes zero. Before dividing, the program checks the denominator inside a try block; if it is zero it throws the value, which is caught by a catch(float) block. Otherwise R is calculated and printed.
Output (run 1 - valid values):
Output (run 2 - division by zero):
Explanation: For x = 10, y = 5, z = 20 → R = 20 / 5 = 4. For x = 7, y = 7 the denominator is 0, so throw (x - y); transfers control to the catch block; the division statement is skipped and the program ends normally.
When a function is called, the values supplied in the call are called actual arguments and the variables that receive them in the function definition are called formal arguments. C++ provides three methods of passing arguments.
1. Call by value
A copy of the actual argument is passed. Changes made to the formal argument inside the function do not affect the actual argument. It is safe but copying large objects is costly.
2. Call by address (pointer)
The address of the actual argument is passed and received in a pointer. The function works on the original variable through the pointer, so changes are reflected in the caller.
3. Call by reference
A reference (alias) of the actual argument is passed. The formal argument becomes another name for the same memory location, so changes are reflected, and the syntax stays as simple as call by value. Passing objects as const references avoids copying while preventing modification.
Program
Explanation: The call by value swaps only the copies, so x and y remain 10 and 20. The call by address swaps the originals (20, 10). The call by reference swaps them again (10, 20).
| Basis | Call by value | Call by address | Call by reference |
|---|---|---|---|
| What is passed | Copy of value | Address of variable | Alias of variable |
| Formal argument | Ordinary variable | Pointer (int *) | Reference (int &) |
| Effect on actual argument | No change | Changed | Changed |
| Memory | Extra copy made | Pointer only | No copy |
| Call syntax | f(x) | f(&x) | f(x) |
Default arguments: C++ also allows default values, e.g. float interest(float p, float r = 7.5); can be called as interest(1000).
Question 7 14 marks
Logic:
- Define a class
Employeewith the record fields and a fieldnetSalary. - Create
Emp.datin binary mode withofstreamand write each employee object withwrite(). - Re-open the same file with
fstreaminios::in | ios::out | ios::binarymode. - For every record: remember its position with
tellg(),read()the record, calculate Net salary = Salary + Allowances - Deductions, move back withseekp()andwrite()the updated record at the same place. - Read the file again and display the records to verify.
Explanation: seekp(pos) places the put pointer at the beginning of the record just read, so write() overwrites that same record with the calculated net salary. Because the record size is fixed (sizeof(e)), every record can be updated in place without disturbing the others.
File handling
A file is a collection of related data stored permanently on a secondary storage device. File handling is the mechanism of creating, opening, reading, writing and closing files from a program, so that data is not lost when the program ends (persistence). In C++, file I/O is done through stream classes declared in the header <fstream>.
| Class | Purpose |
|---|---|
ifstream | Input file stream; reads data from a file (inherits istream). |
ofstream | Output file stream; writes data to a file (inherits ostream). |
fstream | Both reading and writing (inherits iostream). |
filebuf / fstreambase | Provide the file buffer and common operations such as open() and close(). |
Steps: (1) include <fstream>, (2) create a stream object, (3) open the file, (4) read/write, (5) close the file.
File opening modes: ios::in (read), ios::out (write), ios::app (append at end), ios::ate (go to end on opening), ios::trunc (delete old contents), ios::binary (binary mode). Modes can be combined with |, e.g. fstream f("a.dat", ios::in | ios::out | ios::binary);
Functions supported by file stream classes
| Function | Work |
|---|---|
open() / close() | Opens a file in a given mode / closes it and flushes the buffer. |
is_open() | Returns true if the file was opened successfully. |
put(ch) | Writes a single character to the file. |
get(ch) | Reads a single character from the file. |
getline(stream, str) | Reads a complete line of text. |
write((char*)&obj, size) | Writes a block of binary data (for example a whole object). |
read((char*)&obj, size) | Reads a block of binary data into memory. |
seekg(pos, dir) | Moves the get (read) pointer; dir = ios::beg, ios::cur, ios::end. |
seekp(pos, dir) | Moves the put (write) pointer. |
tellg() / tellp() | Returns the current position of the get / put pointer. |
eof() | Returns true when the end of file is reached. |
fail(), bad(), good(), clear() | Check and reset the error state of the stream. |
<< and >> | Formatted write and read, exactly as with cout and cin. |
Program: using the file stream functions
Question 8 14 marks
Write short notes on (any two):
When does ambiguity arise?
In multiple inheritance a derived class has more than one base class. Ambiguity arises in two situations:
1. Same member name in two base classes - if both base classes have a member with the same name (for example input()), the call obj.input() is ambiguous, because the compiler cannot decide which version to use.
2. Diamond problem (multipath inheritance) - when two base classes are themselves derived from a common grandparent, the derived class receives two copies of the grandparent's members (two name, two age). Any access to them is ambiguous.
How to resolve the ambiguity
- Scope resolution operator (::) - specify the class explicitly:
obj.Student::input(); - Function overriding - define the function again in the derived class; the derived version hides both base versions and can call them explicitly.
- Virtual base class - declare the common base as
virtualin the intermediate classes:class Student : virtual public Person. Then only one shared copy ofPersonis inherited, which removes the diamond problem.
Object Model
The object model is the conceptual framework of object-oriented development. It describes a system as a collection of objects that have state, behaviour and identity, are created from classes, and are connected to one another through relationships (association, aggregation, inheritance). In design methods such as OMT, the object model shows the static structure of the system - classes, their attributes, operations and relationships - drawn as class and object diagrams.
Basic elements of the object model (Grady Booch)
Four major elements (a model without any of these is not object-oriented):
- Abstraction - Focuses on the essential characteristics of an object relative to the viewer and ignores irrelevant details.
- Encapsulation - Hides the internal implementation of an object and exposes only its interface; achieved by classes and access specifiers.
- Modularity - Decomposes the system into a set of cohesive, loosely coupled modules (classes, files, packages).
- Hierarchy - Ranking or ordering of abstractions: "is-a" hierarchy (inheritance) and "part-of" hierarchy (aggregation).
Three minor elements (useful but not essential):
- Typing - Enforcement of the class of an object, so that objects of different types cannot be interchanged freely (strong typing in C++).
- Concurrency - The property that allows several objects to be active at the same time (threads).
- Persistence - The property by which an object continues to exist after its creator stops (data saved in files or databases).
The building blocks used in every object model are classes, objects, attributes, operations (methods), messages and relationships.
Access modifiers
Access modifiers (access specifiers) are keywords that decide which parts of a program can access the members (data and functions) of a class. They are the main tool for implementing data hiding and encapsulation. C++ provides three access modifiers: private, protected and public.
1. private - Members declared private can be accessed only by the member functions (and friends) of the same class. They are not accessible from outside the class or from derived classes. By default, all members of a class are private. Data members are normally made private.
2. protected - Members declared protected are accessible within the class and in its derived classes, but not from outside (for example from main()). It is used when a base class wants to share data only with its children.
3. public - Members declared public are accessible from anywhere in the program through an object. Member functions that form the interface of the class are made public. By default, members of a struct are public.
Comparison of access levels
| Accessible from | private | protected | public |
|---|---|---|---|
| Member functions of the same class | Yes | Yes | Yes |
| Friend functions / classes | Yes | Yes | Yes |
| Member functions of a derived class | No | Yes | Yes |
Outside the class (e.g. main()) through an object | No | No | Yes |
| Typical use | Data members | Data shared with child classes | Interface functions |
Answers are written for 7-mark questions in exam style. Every C++ program was compiled and run; the output shown is the real output.