Skip to content
CY-305 · Object Oriented Programming & Methodology/Quick Revision Short Notes

Object Oriented Programming & Methodology (CY-305) - Unit 2 Short Notes

How unit 2 is examined

Objects, classes, access modifiers, static members, instances, message passing and constructors; classes, access modifiers and construction carry the marks.

Concept of Objects: State, Behavior & Identity of an object

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Medium weight</span>

Definition. <mark>An object is a run-time instance of a class that bundles its state (data), its behaviour (functions) and its identity (a unique address) into one entity.</mark>

Key points.

  1. State is the attribute values an object holds at a moment, e.g. a Car with speed 40.
  2. Behaviour is what the object can do; it is coded as member functions (methods) that read or change the state.
  3. Identity makes an object distinct even from one with identical state; it is the memory address or reference (&c1 != &c2), and it does not change when the state changes.
  4. In code, a class declares attributes and methods; Car c1; (C++) or Car c1 = new Car(); (Java) creates the object.

Example.

class Car { int speed = 0;             // state; uninitialised it would be undefined behaviour
public:
    void accelerate() { speed += 10; } // behaviour
    int get() { return speed; } };
int main() { Car c1, c2;               // same class, different identity
    c1.accelerate(); cout << c1.get() << " " << c2.get() << " " << (&c1 != &c2); }   // 10 0 1

Answer frame. Definition; state, behaviour, identity with an example each; the code; close "state changes, identity never does".

Asked: [7 marks] (Dec 2024, Jun 2025) Explain the concept of objects with respect to their state, behaviour and identity and how they are represented in code.

Classes: identifying classes and candidates for Classes Attributes and Services

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">High weight</span>

Definition. <mark>A class is a user-defined blueprint that groups attributes (data members) and services (member functions) which describe a set of similar objects; an object is one instance of it.</mark>

Key points.

  1. Candidate classes are the nouns of the problem (Student, Account); attributes are the nouns describing them (roll, balance) and services are the verbs (deposit, display).
  2. A class occupies no memory; memory is allocated when an object is created, Student s;.
  3. Member functions are declared in the class and operate on its data; they are defined inside (implicitly inline) or outside with ::, void Student::show() {...}, and a private one is a helper only other members can call (valid() below).
  4. Every non-static member function gets a hidden this pointer to the calling object, so marks inside it means this->marks.
  5. Access specifiers (private, protected, public) control who uses each member; data is normally private, functions public.
  6. Encapsulation binds data and its functions into one unit (the class) and hides the data; its properties are bundling, data hiding, controlled access and easy maintenance.
  7. Data abstraction shows only the essential features (the public interface) and hides implementation details, as a driver steers without knowing the engine; it uses classes, abstract classes and interfaces.
  8. Abstraction is design level (what an object does), encapsulation implementation level (how data is protected); encapsulation is the mechanism that supports abstraction.
  9. Together they give modular, reusable code: a class changes internally without breaking users, and is reused through inheritance, composition (held as a member) and interfaces.

Encapsulation (the Student program):

#include <iostream>
#include <string>
using namespace std;
class Student { int roll = 0; string name; float marks = 0;    // private data
    bool valid(float m) { return m >= 0 && m <= 100; }        // private helper
public:
    void input() { cout << "Roll, name, marks: "; cin >> roll >> name >> marks;
        if (!valid(marks)) marks = 0; }
    bool setMarks(float m) { if (!valid(m)) return false; marks = m; return true; }
    void display() { cout << roll << " " << name << " " << marks << "\n"; } };
int main() { Student s; s.input();                            // input: 1 Asha 85
    if (!s.setMarks(120)) cout << "Invalid marks\n";
    s.display(); }   // Invalid marks, 1 Asha 85; s.marks = 120 is a compile error

For a "C program", use a struct plus functions; C cannot hide the fields, so any code can write s.marks = 120.

#include <stdio.h>
struct Student { int roll; char name[20]; float marks; };
void input(struct Student* s) { printf("Roll, name, marks: "); scanf("%d %19s %f", &s->roll, s->name, &s->marks); }
void display(const struct Student* s) { printf("%d %s %.1f\n", s->roll, s->name, s->marks); }
int main() { struct Student s; input(&s); display(&s); return 0; }   // 1 Asha 85.0

Abstraction (callers see only area()):

class Shape { public: virtual double area() = 0; virtual ~Shape() {} };   // abstract
class Circle : public Shape { double r; public: Circle(double x) : r(x) {}
    double area() override { return 3.14159 * r * r; } };
class Rect : public Shape { double l, b; public: Rect(double x, double y) : l(x), b(y) {}
    double area() override { return l * b; } };
int main() { Shape* s[] = { new Circle(1), new Rect(2, 3) };
    for (Shape* p : s) { cout << p->area() << "\n"; delete p; } }   // 3.14159, 6
class Distance { int f = 0, i = 0;
public:
    void get(const char* w) { cout << "Feet and inches of " << w << ": "; cin >> f >> i;
        f += i / 12; i %= 12; }                            // normalise: 5'14" -> 6'2"
    void show() { cout << f << "'" << i << "\"\n"; }
    int in() { return f * 12 + i; }                       // total inches
    Distance add(Distance d) { Distance r; int t = in() + d.in(); r.f = t / 12; r.i = t % 12; return r; }
    Distance sub(Distance d) { Distance r; int t = abs(in() - d.in()); r.f = t / 12; r.i = t % 12; return r; }
};
int main() { Distance a, b; int ch;
    do { cout << "1 Add 2 Subtract 3 Exit: "; cin >> ch;
        if (ch == 1 || ch == 2) { a.get("first"); b.get("second"); }
        if (ch == 1) a.add(b).show();
        else if (ch == 2) { if (a.in() < b.in()) cout << "-"; a.sub(b).show(); }   // sign if b > a
        else if (ch != 3) cout << "Invalid choice\n";                              // default branch
    } while (ch != 3); }
// 5'9"+3'7" = 9'4"; 5'9"-3'10" = 1'11"; 3'10"-5'9" = -1'11"

Answer frame. Member functions: define, inside and :: definitions, this, Student example. Attributes and services: define, link to access modifiers and static. Encapsulation and abstraction: define, Student and Shape programs, relationship, close with reuse. Programs: class, private data, public functions, main.

Asked: [7 marks] (Jun 2023, Jun 2024) What are member functions? Explain with example. Asked: [7 marks] (Dec 2024) Discuss attributes and services, including the role of access modifiers and static members in defining class behaviour. Asked: [7 marks] (Jun 2024) Write an interactive program for manipulating objects of a distance class, with member functions to add and subtract distances of two objects. Asked: [7 marks] (Dec 2025) Write a program demonstrating encapsulation by creating a class Student with roll number, name and marks and member functions. Asked: [7 marks] (Dec 2025) Explain classes and objects. Asked: [7 marks] (Dec 2023, Dec 2025) What are the properties of encapsulation and data abstraction? Asked: [7 marks] (Dec 2024) Discuss encapsulation and data abstraction and how they enable modular and reusable code design. Asked: [7 marks] (Dec 2024, Dec 2025) Define encapsulation and data abstraction.

Access modifiers

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">High weight</span>

Definition. <mark>Access modifiers (specifiers) are keywords that set the visibility of class members; C++ has three, private, protected and public, and they implement data hiding.</mark>

Key points.

  1. private members are accessible only inside the class (and friends); it is the class default.
  2. protected members are accessible inside the class and its derived classes, not from outside.
  3. public members are accessible everywhere and form the class interface.
  4. Data hiding keeps data private with controlled access through public getters and setters that validate values.
  5. Java adds a fourth level, default (package) access, between protected and private.
  6. Inheritance mode can only narrow access; a private base member is never accessible in the derived class.
  7. Through a derived object in main, only base public members under public inheritance are reachable.

Inheritance visibility (cell: access in the derived class).

Base member Public inheritance Protected inheritance Private inheritance
public public protected private
protected protected protected private
private not accessible not accessible not accessible
Access Same class Derived class Outside
--- --- --- ---
private yes no no
protected yes yes no
public yes yes yes
class B { int a = 1; protected: int b = 2; public: int c = 3; };
class D : public B { public: void show() { cout << b << c << "\n"; } };   // a here: error
class Q : protected B { public: int get() { return c; } };  // c becomes protected in Q
class V : private B { public: int get() { return b; } };    // b becomes private in V
int main() { D d; d.show(); cout << d.c << Q().get() << V().get();   // 23, then 332
    // d.b, Q().c, V().b in main: errors
}

Answer frame. Open with the definition and "three in C++"; draw both tables; one sentence per modifier; the program; data hiding via getter/setter. Short notes: definition, points, example each.

Abstract base class. ==An abstract base class is a class with at least one pure virtual function, such as virtual void area() = 0;, and it cannot be instantiated.==

  1. Shape s; is a compile error, but pointers and references (Shape* p) to derived objects are allowed.
  2. A derived class must override every pure virtual function, or it is abstract too.
  3. It gives a class family one interface; base-pointer calls bind at run time.
  4. It may have data members and ordinary functions, and should have a virtual destructor so delete through a base pointer calls the derived destructor.
  5. Example: the Shape program under Classes.

Association. <mark>Association is a relationship between two independent classes whose objects use or know each other ("uses-a") without either owning the other, so each can exist alone.</mark>

  1. Multiplicity: one-to-one (Person-Passport), one-to-many (Teacher-Students), many-to-many (Students-Courses).
  2. In a unidirectional association one class holds the link; in a bidirectional one both do.
  3. It is coded as a pointer or reference member (Teacher* t; inside Student), never as an owned member object.
  4. Aggregation is a special weak "has-a" association where the part can outlive the whole (Department-Teacher); composition is a strong "has-a" where the part dies with the whole (House-Room).
  5. UML draws a line between class boxes; aggregation adds a hollow diamond, composition a filled one.

<figure class="ds-fig" style="margin:1.4rem 0;overflow-x:auto"><svg xmlns="http://www.w3.org/2000/svg" id="dsfig-u2-01" viewBox="0 0 338 80" width="338" height="80" role="img" aria-label="Association Teacher (1) teaches Student (many); arrow means one-way"><style>#dsfig-u2-01 .e{stroke:#454C5A;stroke-width:1.4;fill:none}#dsfig-u2-01 .e.hi{stroke:#2340B8;stroke-width:2.6}#dsfig-u2-01 .n{fill:#FFFFFF;stroke:#16181D;stroke-width:1.4}#dsfig-u2-01 .n.hi{fill:#E3E9FC;stroke:#2340B8;stroke-width:2.2}#dsfig-u2-01 .n.rb-b{fill:#16181D;stroke:#16181D}#dsfig-u2-01 .n.rb-r{fill:#BD3227;stroke:#BD3227}#dsfig-u2-01 text{font-family:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace;font-size:13px}#dsfig-u2-01 .t{fill:#16181D;font-weight:500}#dsfig-u2-01 .t.inv{fill:#FFFFFF;font-weight:700}#dsfig-u2-01 .kd{stroke:#16181D;stroke-width:1.2}#dsfig-u2-01 .dot{fill:#16181D}#dsfig-u2-01 .ann{fill:#2340B8;font-size:11px;font-weight:700}#dsfig-u2-01 .lbl{fill:#6F7787;font-family:system-ui,-apple-system,sans-serif;font-size:12px;font-weight:700}#dsfig-u2-01 .ptr{fill:#2340B8;font-size:12px;font-weight:700}#dsfig-u2-01 .ah{fill:#454C5A}#dsfig-u2-01 .ah.hi{fill:#2340B8}#dsfig-u2-01 .wl rect{fill:#FFFFFF;stroke:#DCE0E7}#dsfig-u2-01 .wl .t{font-size:12px;font-weight:700}#dsfig-u2-01 .wl.hi rect{fill:#2340B8;stroke:#2340B8}#dsfig-u2-01 .wl.hi .t{fill:#FFFFFF}html.dark #dsfig-u2-01 .e{stroke:#B1B7C3}html.dark #dsfig-u2-01 .e.hi{stroke:#8FA3FF}html.dark #dsfig-u2-01 .n{fill:#161920;stroke:#E6E8ED}html.dark #dsfig-u2-01 .n.hi{fill:#1E2748;stroke:#8FA3FF}html.dark #dsfig-u2-01 .n.rb-b{fill:#E6E8ED;stroke:#E6E8ED}html.dark #dsfig-u2-01 .n.rb-r{fill:#FF7E71;stroke:#FF7E71}html.dark #dsfig-u2-01 .t{fill:#E6E8ED}html.dark #dsfig-u2-01 .t.inv{fill:#0F1115}html.dark #dsfig-u2-01 .kd{stroke:#E6E8ED}html.dark #dsfig-u2-01 .dot{fill:#E6E8ED}html.dark #dsfig-u2-01 .ann{fill:#8FA3FF}html.dark #dsfig-u2-01 .lbl{fill:#858D9C}html.dark #dsfig-u2-01 .ptr{fill:#8FA3FF}html.dark #dsfig-u2-01 .ah{fill:#B1B7C3}html.dark #dsfig-u2-01 .ah.hi{fill:#8FA3FF}html.dark #dsfig-u2-01 .wl rect{fill:#161920;stroke:#2A2E37}html.dark #dsfig-u2-01 .wl.hi rect{fill:#8FA3FF;stroke:#8FA3FF}html.dark #dsfig-u2-01 .wl.hi .t{fill:#0F1115}</style><defs><marker id="ah5" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah" d="M0,1 L9,5 L0,9 z"/></marker><marker id="ahh5" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah hi" d="M0,1 L9,5 L0,9 z"/></marker></defs><path class="e" d="M59,40 L277,40" marker-end="url(#ah5)"/><g class="wl"><rect x="138.3" y="31" width="61.5" height="18" rx="9"/><text class="t" x="169" y="40" dy=".35em" text-anchor="middle">teaches</text></g><circle class="n" cx="40" cy="40" r="18"/><text class="t" x="40" y="40" dy=".35em" text-anchor="middle">T</text><circle class="n" cx="298" cy="40" r="18"/><text class="t" x="298" y="40" dy=".35em" text-anchor="middle">S</text></svg><figcaption style="font-size:.82em;opacity:.72;margin-top:.45rem">Association Teacher (1) teaches Student (many); arrow means one-way</figcaption></figure>

Pitfall: Writing that a derived class can use the private members of its base; it cannot, whatever the inheritance mode.

Asked: [7 marks] (Nov 2022, Jun 2024) What are access modifiers? How many types in C++? Explain each and their role in data hiding; show visibility when inherited as public, private and protected. Asked: [7 marks] (Dec 2025) Discuss access modifiers, static members and object life cycle. Asked: [14 marks] (Jun 2024) Write short notes on (any two): Access modifiers; Abstract base classes; Association.

Static members of a Class

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Low weight</span>

Definition. <mark>A static member belongs to the class as a whole, not to any object, so all objects share a single copy.</mark>

Key points.

  1. A static data member is stored once per class, declared with static inside the class and defined outside it (int Count::n = 0;).
  2. A static member function has no this pointer, so it uses static members directly and is called as Count::show(); instance members need an object, a.showId().
  3. Static data exists before any object and lives until the program ends.
  4. In Java, static int count; is a class field and static void show() is called as ClassName.show(), e.g. Count.show().
class Count { int id; static int n;                  // instance and static
public: Count() { id = ++n; }
    void showId() { cout << "id " << id << " of " << n << "\n"; }   // uses both
    static void show() { cout << "count " << n << "\n"; } };        // no this, no id
int Count::n = 0;                                    // definition outside the class
int main() { Count a, b, c; a.showId(); b.showId(); c.showId(); Count::show(); }
// id 1 of 3, id 2 of 3, id 3 of 3, count 3
Static member Instance member
One copy per class One copy per object
Called with class name Called with object
Exists before any object Exists only after creation
Static functions have no this pointer; they reach instance data only through an object Can use both

Asked: [7 marks] (Jun 2025) What are static members of a class? How are they different from instance members?

Instances

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Medium weight</span>

Definition. <mark>An instance is a concrete object created from a class, with its own copy of the data members and a share of the class's code.</mark>

Key points.

  1. Instantiation allocates memory for the data members, by declaration (Box b;), dynamically (new Box, freed by delete) or in Java (Box b = new Box();), and the constructor runs at that moment.
  2. Instances of one class share the member functions but each holds its own state.
  3. An empty class has no members, yet an instance of it can be created; its sizeof is 1 byte, not 0, because every object needs a unique address.
  4. Empty classes serve as tag types and bases (0 bytes as bases).
  5. Changing one instance never changes another, except via static members.
class Box { public: int w = 0; Box() { cout << "made "; } };   // constructor runs per instance
class E {};
int main() { Box b1, b2; b1.w = 5; b2.w = 9;        // two instances, separate w
    Box* p = new Box; delete p;                     // heap instance, freed by delete
    E e1, e2; cout << sizeof(E) << (&e1 != &e2); }  // made made made 11

Answer frame. Define instance; show b1, b2; for empty class: "yes, it can be created", sizeof 1, unique-address reason.

Asked: [7 marks] (Nov 2022) What are empty classes? Can an instance of an empty class be created? Give reason. Asked: [7 marks] (Dec 2024) Explain instances in OOP and how they represent individual objects created from a class template.

Message passing

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Medium weight</span>

Definition. <mark>Message passing is the way objects communicate: a sender object requests a service from a receiver object by calling one of its methods with arguments.</mark>

Key points.

  1. A message has three parts: the receiver object, the method name and the arguments.
  2. In Java a message is a method call, receiver.method(arguments), which may return a result.
  3. The sender knows only the method name, not its implementation, so objects stay loosely coupled.
  4. With overriding, the method run is chosen at run time from the receiver's actual class (dynamic binding).

<figure class="ds-fig" style="margin:1.4rem 0;overflow-x:auto"><svg xmlns="http://www.w3.org/2000/svg" id="dsfig-u2-02" viewBox="0 0 338 80" width="338" height="80" role="img" aria-label="Sender S sends a message (method plus arguments) to receiver R, which returns a result"><style>#dsfig-u2-02 .e{stroke:#454C5A;stroke-width:1.4;fill:none}#dsfig-u2-02 .e.hi{stroke:#2340B8;stroke-width:2.6}#dsfig-u2-02 .n{fill:#FFFFFF;stroke:#16181D;stroke-width:1.4}#dsfig-u2-02 .n.hi{fill:#E3E9FC;stroke:#2340B8;stroke-width:2.2}#dsfig-u2-02 .n.rb-b{fill:#16181D;stroke:#16181D}#dsfig-u2-02 .n.rb-r{fill:#BD3227;stroke:#BD3227}#dsfig-u2-02 text{font-family:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace;font-size:13px}#dsfig-u2-02 .t{fill:#16181D;font-weight:500}#dsfig-u2-02 .t.inv{fill:#FFFFFF;font-weight:700}#dsfig-u2-02 .kd{stroke:#16181D;stroke-width:1.2}#dsfig-u2-02 .dot{fill:#16181D}#dsfig-u2-02 .ann{fill:#2340B8;font-size:11px;font-weight:700}#dsfig-u2-02 .lbl{fill:#6F7787;font-family:system-ui,-apple-system,sans-serif;font-size:12px;font-weight:700}#dsfig-u2-02 .ptr{fill:#2340B8;font-size:12px;font-weight:700}#dsfig-u2-02 .ah{fill:#454C5A}#dsfig-u2-02 .ah.hi{fill:#2340B8}#dsfig-u2-02 .wl rect{fill:#FFFFFF;stroke:#DCE0E7}#dsfig-u2-02 .wl .t{font-size:12px;font-weight:700}#dsfig-u2-02 .wl.hi rect{fill:#2340B8;stroke:#2340B8}#dsfig-u2-02 .wl.hi .t{fill:#FFFFFF}html.dark #dsfig-u2-02 .e{stroke:#B1B7C3}html.dark #dsfig-u2-02 .e.hi{stroke:#8FA3FF}html.dark #dsfig-u2-02 .n{fill:#161920;stroke:#E6E8ED}html.dark #dsfig-u2-02 .n.hi{fill:#1E2748;stroke:#8FA3FF}html.dark #dsfig-u2-02 .n.rb-b{fill:#E6E8ED;stroke:#E6E8ED}html.dark #dsfig-u2-02 .n.rb-r{fill:#FF7E71;stroke:#FF7E71}html.dark #dsfig-u2-02 .t{fill:#E6E8ED}html.dark #dsfig-u2-02 .t.inv{fill:#0F1115}html.dark #dsfig-u2-02 .kd{stroke:#E6E8ED}html.dark #dsfig-u2-02 .dot{fill:#E6E8ED}html.dark #dsfig-u2-02 .ann{fill:#8FA3FF}html.dark #dsfig-u2-02 .lbl{fill:#858D9C}html.dark #dsfig-u2-02 .ptr{fill:#8FA3FF}html.dark #dsfig-u2-02 .ah{fill:#B1B7C3}html.dark #dsfig-u2-02 .ah.hi{fill:#8FA3FF}html.dark #dsfig-u2-02 .wl rect{fill:#161920;stroke:#2A2E37}html.dark #dsfig-u2-02 .wl.hi rect{fill:#8FA3FF;stroke:#8FA3FF}html.dark #dsfig-u2-02 .wl.hi .t{fill:#0F1115}</style><defs><marker id="ah6" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah" d="M0,1 L9,5 L0,9 z"/></marker><marker id="ahh6" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah hi" d="M0,1 L9,5 L0,9 z"/></marker></defs><path class="e" d="M58.4,44.6 Q169,72 277.6,45.1" marker-end="url(#ah6)"/><path class="e" d="M279.6,35.4 Q169,8 60.4,34.9" marker-end="url(#ah6)"/><g class="wl"><rect x="137.8" y="49.4" width="61.5" height="18" rx="9"/><text class="t" x="168.5" y="58.4" dy=".35em" text-anchor="middle">message</text></g><g class="wl"><rect x="142.3" y="12.6" width="54.3" height="18" rx="9"/><text class="t" x="169.5" y="21.6" dy=".35em" text-anchor="middle">result</text></g><circle class="n" cx="40" cy="40" r="18"/><text class="t" x="40" y="40" dy=".35em" text-anchor="middle">S</text><circle class="n" cx="298" cy="40" r="18"/><text class="t" x="298" y="40" dy=".35em" text-anchor="middle">R</text></svg><figcaption style="font-size:.82em;opacity:.72;margin-top:.45rem">Sender S sends a message (method plus arguments) to receiver R, which returns a result</figcaption></figure>

class Account { private double bal = 100;
    double deposit(double amt) { bal += amt; return bal; } }
class Savings extends Account {
    double deposit(double amt) { return super.deposit(amt + 1); } }   // bonus 1
public class Bank {
    public static void main(String[] args) {
        Account a = new Account(), s = new Savings();
        System.out.println(a.deposit(50));   // 150.0
        System.out.println(s.deposit(50));   // 151.0: same message, Savings's version (dynamic binding)
    } }

Answer frame. Definition; the diagram; message parts; the Java program; close with loose coupling.

Asked: [7 marks] (Jun 2023, Dec 2024) How is message passing possible in Java? Give example. Describe message passing and its role in communication between objects.

Construction and destruction of Objects

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">High weight</span>

Definition. <mark>A constructor is a special member function that runs automatically when an object is created to initialise it; a destructor runs automatically when the object is destroyed to release its resources.</mark>

Key points.

  1. A constructor has the class name, no return type (not even void), and runs automatically at object creation.
  2. Types: default (no arguments), parameterised (takes values), and copy (X(const X&), builds an object from another); several constructors in one class is constructor overloading, resolved by argument list.
  3. Is it mandatory? No: the compiler supplies a default constructor only when no constructor is declared, and it leaves built-in members uninitialised (reading them is undefined behaviour); once a parameterised constructor is written, T t; fails unless a default one is also written, and a constructor is required when the class has const or reference members.
  4. A destructor is the class name with a ~ prefix, with no arguments or return type, one per class, never overloaded.
  5. It runs automatically at scope end or at delete (a heap object is destroyed only by delete; forgetting it leaks memory), and frees memory and closes files.
  6. Objects are destroyed in reverse order of construction; the base constructor runs first, the derived destructor first.
  7. RAII (Resource Acquisition Is Initialisation) acquires a resource in the constructor, releases it in the destructor.
  8. A copy constructor builds a new object from an existing one (X b = a;, pass by value); the implicit one makes a shallow member-wise copy, so a user-written one is needed for a deep copy when the class owns heap memory.
  9. Java has no destructor; the garbage collector reclaims memory, finalize() is deprecated, and cleanup uses Cleaner or try-with-resources, which calls close() at block end.
class X { int* p;
public:
    X() { p = new int[10]; cout << "acquire\n"; }                                    // RAII acquire
    X(const X& o) { p = new int[10]; copy(o.p, o.p + 10, p); cout << "copy\n"; }   // deep copy
    ~X() { delete[] p; cout << "release\n"; } };                                    // RAII release
int main() { X* h = new X;          // acquire
    delete h;              // release: a heap object's destructor runs only here
    X a; X b = a; }        // acquire, copy; at exit: release, release
class Area { double a;
public:
    Area(double r)     { a = 3.14159 * r * r; }       // circle
    Area(int s)        { a = s * s; }                 // square
    Area(int l, int b) { a = l * b; }                 // rectangle
    void show() { cout << a << "\n"; } };
int main() { Area(2.5).show(); Area(4).show(); Area(5, 3).show(); }   // 19.6349, 16, 15
class P { int x, y;
public: P() : x(0), y(0) {}                           // default
    P(int a, int b) : x(a), y(b) {}                   // parameterised
    P(const P& o) : x(o.x), y(o.y) {}                 // copy
    void show() { cout << x << "," << y << "\n"; } };
int main() { P a, b(3, 4), c = b; a.show(); b.show(); c.show(); }   // 0,0  3,4  3,4
class Cake { float height, weight; string shape, message;
public:
    Cake() : height(10), weight(1), shape("round"), message("None") {}
    Cake(float h, float w, string s, string m) : height(h), weight(w), shape(s), message(m) {}
    void display() { cout << shape << " " << height << "cm " << weight << "kg " << message << "\n"; }
    void grow() { height += 2; weight += 0.5; }
};
int main() { Cake c1, c2(12, 1.5, "square", "Happy");   // default and overloaded
    c1.display(); c2.display(); c2.grow(); c2.display(); }
// round 10cm 1kg None; square 12cm 1.5kg Happy; after grow(): square 14cm 2kg Happy

Object life cycle. An object is created (constructor, by declaration or new), used (member functions called) and destroyed (destructor at scope end or delete), as X shows.

Answer frame. Construction/destruction: define both, characteristics, the X example, close with create, use, destroy. Constructor: define, three types, P example, then point 3. Programs: class, overloaded constructors, display, main.

Pitfall: With Area(float) and Area(int), Area c(2.0); is ambiguous (2.0 is a double); use double as above.

Asked: [7 marks] (Dec 2023, Dec 2024, Jun 2025) What is construction and destruction? Explain with suitable example. Asked: [7 marks] (Jun 2023, Jun 2024) What is a constructor? Is it mandatory to use a constructor in a class? Asked: [7 marks] (Dec 2023) Write a C++/Java program to calculate the area of rectangle, square and circle using constructor overloading. Asked: [7 marks] (Jun 2023) Create a class cake with height, weight, shape and message with a default constructor; overload it with arguments; add methods to display, and to increase height by 2 cm and weight by 0.5 kg; display again.

Last-minute revision

  • An object has state (data), behaviour (methods) and identity (unique address).
  • C++ access modifiers: private (class only), protected (class and derived), public (all).
  • A private base member is never accessible in a derived class.
  • Encapsulation binds and hides data; abstraction shows only essentials; encapsulation supports abstraction.
  • Static members: one copy per class; static functions have no this.
  • An abstract base class has a pure virtual function (= 0) and cannot be instantiated; base pointers are allowed.
  • Constructor: class name, no return type; destructor: ~Name, one per class, no arguments.
  • The compiler gives a default constructor only if none is declared.

Memory hooks

  • State, Behaviour, Identity: SBI.
  • Private is Personal, Protected is Family, Public is Everyone.
  • Constructor builds, destructor (~) cleans.
  • Static means shared: one copy, one class.

Coverage checklist

  • Concept of Objects: State, Behavior & Identity of an object: objects question.
  • Classes: identifying classes and candidates for Classes Attributes and Services: member functions, attributes, Distance, Student, classes, encapsulation and abstraction.
  • Access modifiers: modifiers and visibility, life cycle, short notes.
  • Static members of a Class: static versus instance members.
  • Instances: empty class, instances.
  • Message passing: message passing in Java.
  • Construction and destruction of Objects: construction and destruction, constructor mandatory, area, cake.
Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in