Constructors in C++
Definition
A constructor is a special member function that is automatically called when an object is created. It initializes the object's data members.
Characteristics of Constructor
✓ Same name as the class ✓ No return type (not even void) ✓ Automatically called on object creation ✓ Can be overloaded
Types of Constructors
| Type | Arguments | Purpose |
|---|---|---|
| Default Constructor | None | Sets default values |
| Parameterized Constructor | One or more | Initializes with specific values |
| Copy Constructor | Reference of same class | Creates copy of existing object |
1. Default Constructor
A constructor with no arguments. Called automatically when object is created without passing values.
#include<iostream>
using namespace std;
class Student{
int roll; string name;
public:
Student(){ // Default Constructor
roll=1; name="Abinaya";
cout<<"Default Constructor Called"<<endl;
}
void display(){
cout<<"Roll No: "<<roll<<endl;
cout<<"Name: "<<name<<endl;
}
};
int main(){
Student s; // Default constructor auto-called
s.display();
return 0;
}
Default Constructor Called
Roll No: 1
Name: Abinaya
2. Parameterized Constructor
A constructor that accepts arguments to initialize an object with specific values when created.
#include<iostream>
using namespace std;
class Student{
private:
int rollNo; string name; float marks;
public:
Student(int r, string n, float m){ // Parameterized Constructor
rollNo=r; name=n; marks=m;
}
void display(){
cout<<"Roll No : "<<rollNo<<endl;
cout<<"Name : "<<name<<endl;
cout<<"Marks : "<<marks<<endl;
}
};
int main(){
Student s1(101,"Arun",88.5); // values passed at creation
s1.display();
return 0;
}
Roll No : 101
Name : Arun
Marks : 88.5
3. Copy Constructor
Creates a new object by copying data from an existing object of the same class. Takes a
const ClassName &obj parameter.
#include<iostream>
using namespace std;
class Student{
int rollNo;
public:
Student(int r){ rollNo=r; } // Parameterized
Student(const Student &s){ // Copy Constructor
rollNo=s.rollNo;
cout<<"Copy Constructor Called"<<endl;
}
void display(){ cout<<"Roll No: "<<rollNo<<endl; }
};
int main(){
Student s1(101); // parameterized constructor
Student s2=s1; // copy constructor called
s1.display();
s2.display();
return 0;
}
Copy Constructor Called
Roll No: 101
Roll No: 101
Student s2 = s1; triggers the copy constructor — s2 gets a copy of s1's
data.const Student &s — const prevents the source object from
being modified; & passes by reference to avoid infinite recursion.Why const & Reference in Copy Constructor?
Deep Explanation
✓ const — prevents the source object from being accidentally modified. It means: "I am only reading, not changing."
✓ & (reference) — if we passed by value, C++ would copy the object to pass it — which would call the copy constructor again — causing infinite recursion. Reference avoids this.
Signature must always be: ClassName(const ClassName &obj)
When is Copy Constructor Called Automatically?
1. Student s2 = s1; → initialization from another object
2. void show(Student s) → object passed by value to a function
3. Student get(){ return s; } → object returned by value from function
Copy Constructor vs Assignment Operator
| Point | Copy Constructor | Assignment Operator |
|---|---|---|
| When | Object is being created from another | Object already exists, copying data |
| Example | Student s2 = s1; (at creation) |
s2 = s1; (after s2 already exists) |
| Calls | Copy constructor | operator= |
Student s2 = s1; calls COPY CONSTRUCTOR (not
assignment). Assignment = is only used when the object already existed before the statement.2-mark: A constructor is a special member function with the same name as the class, no return type, and is automatically called when an object is created.
5-mark: Types — Default (no args, sets defaults), Parameterized (takes args, initializes with specific values), Copy (takes const reference, creates duplicate object). All three have same name as class and no return type.
#include <iostream>
using namespace std;
class BankAccount {
string owner; double balance;
public:
BankAccount(){ owner="Unknown"; balance=0; cout<<"Default constructor called"<<endl; }
BankAccount(string o, double b){ owner=o; balance=b; cout<<"Parameterized: "<<owner<<endl; }
BankAccount(const BankAccount &a){ owner=a.owner; balance=a.balance; cout<<"Copy constructor called"<<endl; }
void display(){ cout<<owner<<" | Balance: "<<balance<<endl; }
};
int main(){
BankAccount a1;
BankAccount a2("Alice", 5000);
BankAccount a3 = a2;
a1.display(); a2.display(); a3.display();
return 0;
}
Default constructor called
Parameterized: Alice
Copy constructor called
Unknown | Balance: 0
Alice | Balance: 5000
Alice | Balance: 5000
BankAccount a1 — no args → default constructor called. Sets
owner='Unknown', balance=0.BankAccount a2('Alice',5000) — two args → parameterized
constructor. Stores Alice and 5000.BankAccount a3=a2 — initializing from existing object → copy
constructor. a3 gets a copy of a2's data.const BankAccount &a in copy constructor: const prevents
modifying source; & avoids infinite recursion.#include <iostream>
using namespace std;
class BankAccount { public: string owner; BankAccount(string n){ owner=n; cout<<"Account created for "<<owner; } };
int main(){ BankAccount acc("Alice"); return 0; }
Account created for Alice
class T { T(){ cout<<"Hi"; } };
Hi
Default=no args | Parameterized=with args | Copy=const Ref&
s2=s1 → triggers copy constructor
Destructor
Definition
A destructor is a special member function that is automatically called when an object goes out of scope or is destroyed. It frees memory and resources used by the object.
Rules of Destructor
✓ Same name as class preceded by tilde (~) ✓ No return type ✓ No parameters ✓ Only ONE destructor per class ✓ Cannot be overloaded
Syntax
// Inside class
~ClassName() { // cleanup code }
// Outside class
ClassName::~ClassName() { // cleanup code }
Complete Program
#include<iostream>
using namespace std;
class Student{
public:
Student(){ cout<<"Constructor called"<<endl; }
~Student(){ cout<<"Destructor called"<<endl; }
};
int main(){
Student s;
cout<<"Inside main function"<<endl;
return 0; // destructor auto-called here
}
Constructor called
Inside main function
Destructor called
Student s; is created.s goes out of scope — destructor auto-called.A destructor is a special member function with the same name as the class preceded by a tilde (~). It has no
return type, no parameters, and cannot be overloaded. It is automatically invoked when the object goes out of
scope. Its main purpose is to free memory/resources allocated by the constructor. Only one destructor per
class is allowed. Syntax: ~ClassName() { }
#include <iostream>
using namespace std;
class FileHandler {
string filename;
public:
FileHandler(string f){ filename=f; cout<<"Opened: "<<filename<<endl; }
~FileHandler(){ cout<<"Closed: "<<filename<<endl; }
};
int main(){
cout<<"--- entering block ---"<<endl;
{
FileHandler f1("data.txt");
FileHandler f2("log.txt");
cout<<"--- files in use ---"<<endl;
} // f2 destroyed first (LIFO), then f1
cout<<"--- block exited ---"<<endl;
return 0;
}
--- entering block ---
Opened: data.txt
Opened: log.txt
--- files in use ---
Closed: log.txt
Closed: data.txt
--- block exited ---
{ } ends, objects go out of scope. Destructors called
automatically.~FileHandler(): same name with tilde, no return type, no
parameters. Cannot be overloaded.#include <iostream>
using namespace std;
class Test { public: Test(){ cout<<"Born"; } ~Test(){ cout<<"Gone"; } };
int main(){ { Test t; } return 0; }
BornGone
class T { ~T(){ cout<<"Bye"; } };
Bye
Auto-called when object dies | Cannot overload | Frees resources
Destructor Call Order — Reverse of Constructor
Destructors are called in reverse order of construction (LIFO — Last In, First Out). The last object created is the first to be destroyed.
#include<iostream>
using namespace std;
class Box{
public:
int id;
Box(int n){ id=n; cout<<"Constructor: Box "<<id<<endl; }
~Box(){ cout<<"Destructor: Box "<<id<<endl; }
};
int main(){
Box b1(1);
Box b2(2);
Box b3(3);
cout<<"--- end of main ---"<<endl;
return 0; // destructors called here in REVERSE
}
Constructor: Box 1
Constructor: Box 2
Constructor: Box 3
--- end of main ---
Destructor: Box 3
Destructor: Box 2
Destructor: Box 1
Constructor Overloading
Definition
Constructor overloading means having more than one constructor in a class with the same name but different parameter lists. The compiler calls the correct constructor based on the arguments passed.
Key Rules
✓ All constructors must have the same name (class name)
✓ Each must differ in number or type of arguments
✓ Compiler selects based on arguments at object creation
Complete Program
#include<iostream>
using namespace std;
class Student{
public:
int roll; string name; float marks;
Student(){ // Default
roll=0; name="Unknown"; marks=0;
cout<<"Default Constructor"<<endl;
}
Student(int r, string n){ // 2-param
roll=r; name=n; marks=0;
cout<<"2-Param Constructor"<<endl;
}
Student(int r, string n, float m){ // 3-param
roll=r; name=n; marks=m;
cout<<"3-Param Constructor"<<endl;
}
void display(){
cout<<"Roll:"<<roll<<" Name:"<<name<<" Marks:"<<marks<<endl;
}
};
int main(){
Student s1; // calls default
Student s2(101,"Arun"); // calls 2-param
Student s3(102,"Priya",91.5); // calls 3-param
s1.display(); s2.display(); s3.display();
return 0;
}
Default Constructor
2-Param Constructor
3-Param Constructor
Roll:0 Name:Unknown Marks:0
Roll:101 Name:Arun Marks:0
Roll:102 Name:Priya Marks:91.5
Constructor overloading is having multiple constructors in the same class with the same name but different parameters. The correct constructor is selected based on arguments passed during object creation. It is a form of compile-time polymorphism.
class Box { public: int s; Box(){ s=0; } Box(int x){ s=x; } };
int main(){ Box b1; Box b2(5); return 0; }
Compiler picks constructor based on arguments at object creation
Constructor Call Order — Multiple Objects
When multiple objects are created, constructors are called in the order the objects are defined.
#include<iostream>
using namespace std;
class Box{
public:
int id;
Box(int n){ id=n; cout<<"Constructor: Box "<<id<<endl; }
};
int main(){
Box b1(1); // constructed 1st
Box b2(2); // constructed 2nd
Box b3(3); // constructed 3rd
cout<<"All objects created"<<endl;
return 0;
}
Constructor: Box 1
Constructor: Box 2
Constructor: Box 3
All objects created
Method (Function) Overloading
Definition
Function overloading allows two or more functions to have the same name but different parameters (type, number, or both). It is a form of compile-time polymorphism.
Key Rules
✓ Same function name
✓ Must differ in parameter type or count
✓ Return type alone is NOT enough to overload
Complete Program
#include<iostream>
using namespace std;
void add(int a, int b){
cout<<"Int sum = "<<(a+b)<<endl;
}
void add(double a, double b){
cout<<"Double sum = "<<(a+b)<<endl;
}
void add(int a, int b, int c){
cout<<"Three sum = "<<(a+b+c)<<endl;
}
int main(){
add(10,2);
add(5.3,6.2);
add(1,2,3);
return 0;
}
Int sum = 12
Double sum = 11.5
Three sum = 6
Quick Check (click to reveal)
Can two functions be overloaded only by changing return type?
Which type of polymorphism is function overloading?
Function overloading is defining multiple functions with the same name but different parameter lists. The compiler selects the correct function at compile time based on the arguments. It is an example of compile-time polymorphism. Key point: return type alone cannot be used to overload — parameters must differ.
#include <iostream>
using namespace std;
class Calculator {
public:
int add(int a, int b){ return a+b; }
double add(double a, double b){ return a+b; }
int add(int a, int b, int c){ return a+b+c; }
string add(string a, string b){ return a+b; }
};
int main(){
Calculator c;
cout<<"Int add: "<<c.add(3,4)<<endl;
cout<<"Double add: "<<c.add(1.5,2.5)<<endl;
cout<<"Triple add: "<<c.add(1,2,3)<<endl;
cout<<"String add: "<<c.add("Hello","World")<<endl;
return 0;
}
Int add: 7
Double add: 4
Triple add: 6
String add: HelloWorld
add. Each has different parameter types or counts.
c.add(3,4) — two ints → compiler selects
int add(int,int).c.add(1.5,2.5) — two doubles → compiler selects
double add(double,double).c.add(1,2,3) — three ints → selects three-param version.c.add('Hello','World') — two strings → string concatenation
version. Return type alone cannot distinguish overloads.class Calc { public: int add(int a, int b){ return a+b; } double add(double a, double b){ return a+b; } };
Return type alone CANNOT distinguish overloaded functions
Operator Overloading
Definition
Operator overloading is a compile-time polymorphism that allows existing C++ operators to be given new meaning for user-defined data types (classes).
Syntax
return_type operator op(argument_list){
// operator logic
}
Operators That CAN be Overloaded
✓ + - * / % == != < > ++ -- << >>
Operators That CANNOT be Overloaded
✗ . (dot) :: (scope resolution) sizeof ?: (ternary) .* (member pointer)
Key Rules
✓ Only existing operators can be overloaded — cannot create new ones
✓ At least one operand must be user-defined type
✓ Cannot change operator precedence or associativity
Complete Program — Overloading ++ (Unary)
#include<iostream>
using namespace std;
class Test{
private:
int num;
public:
Test(){ num=8; }
void operator++(){ // overloading prefix ++
num=num+2;
}
void Print(){ cout<<"The Count is: "<<num<<endl; }
};
int main(){
Test tt;
++tt; // calls operator++() function
tt.Print();
return 0;
}
The Count is: 10
Complete Program — Overloading + (Binary Operator)
Binary operator takes one argument (the right-hand operand). The left-hand object is the
calling object (this).
#include<iostream>
using namespace std;
class Distance{
public:
int metres;
Distance(int m){ metres=m; }
Distance operator+(Distance d2){ // overload binary +
Distance temp(0);
temp.metres = metres + d2.metres;
return temp;
}
void display(){ cout<<"Distance: "<<metres<<" m"<<endl; }
};
int main(){
Distance d1(50), d2(30);
Distance d3 = d1+d2; // calls d1.operator+(d2)
d1.display();
d2.display();
d3.display();
return 0;
}
Distance: 50 m
Distance: 30 m
Distance: 80 m
d1 + d2 is translated by compiler to
d1.operator+(d2). The left object (d1) is the calling object, the right object
(d2) is the argument.Operator overloading allows C++ operators to have new meanings for user-defined types. It is compile-time
polymorphism. Syntax: return_type operator op(args){ }. Operators that cannot be overloaded:
., ::, sizeof, ?:. Rules: Only existing operators can be
overloaded; at least one operand must be user-defined; precedence and associativity cannot change.
#include <iostream>
using namespace std;
class Complex {
public:
double real, imag;
Complex(double r=0, double i=0){ real=r; imag=i; }
Complex operator+(Complex c){
return Complex(real+c.real, imag+c.imag);
}
bool operator==(Complex c){
return (real==c.real && imag==c.imag);
}
void display(){ cout<<real<<"+"<<imag<<"i"<<endl; }
};
int main(){
Complex c1(3,4), c2(1,2);
Complex c3 = c1+c2;
c1.display(); c2.display(); c3.display();
cout<<"Equal? "<<(c1==c2 ? "Yes":"No")<<endl;
return 0;
}
3+4i
1+2i
4+6i
Equal? No
operator+ is a member function. c1+c2 is translated by compiler
to c1.operator+(c2).c.Complex(real+c.real, imag+c.imag) =
Complex(4,6).operator== returns bool. Checks both real and imag parts match.. :: sizeof ?:
— these are fixed by the language.class Complex { public: int r, i; Complex operator+(Complex c){ Complex t; t.r = r+c.r; t.i = i+c.i; return t; } };
CANNOT overload: . :: sizeof ?: .*
Compile-time polymorphism
Function Overriding & Virtual Functions
Function Overriding — Definition
When a derived class defines the same function as in the base class with the same name and signature, it overrides the base class function. Used for run-time polymorphism.
Key Idea
✓ Base class pointer points to derived class object
✓ virtual keyword in base class enables run-time polymorphism
✓ Without virtual, base class version is always called (no override)
Complete Program — Without virtual (NO overriding)
#include<iostream>
using namespace std;
class Animal{
public:
void speak(){ cout<<"Animal speaks"<<endl; }
};
class Dog:public Animal{
public:
void speak(){ cout<<"Dog barks"<<endl; }
};
int main(){
Animal* p = new Dog();
p->speak(); // calls Animal::speak — NOT Dog (no virtual)
return 0;
}
Animal speaks
Complete Program — With virtual (TRUE overriding)
#include<iostream>
using namespace std;
class Animal{
public:
virtual void speak(){ cout<<"Animal speaks"<<endl; }
};
class Dog:public Animal{
public:
void speak(){ cout<<"Dog barks"<<endl; }
};
class Cat:public Animal{
public:
void speak(){ cout<<"Cat meows"<<endl; }
};
int main(){
Animal* p;
Dog d; Cat c;
p=&d; p->speak(); // Dog barks
p=&c; p->speak(); // Cat meows
return 0;
}
Dog barks
Cat meows
virtual in base class tells C++: "when this is called on a base pointer,
look at the actual object's type and call its version."virtual: base version always called (compile-time binding). With
virtual: correct version called based on actual object (run-time binding).Important Terms — Late Binding & Dynamic Binding
Early Binding (Static / Compile-time)
The function to be called is decided at compile time. Happens with normal (non-virtual) functions and function overloading. Also called static binding.
Late Binding (Dynamic / Run-time)
The function to be called is decided at run time, based on the actual type of object the
pointer points to. Happens with virtual functions. Also called dynamic binding
or late binding.
| Term | Meaning | Achieved by |
|---|---|---|
| Early Binding | Function resolved at compile time | Normal functions, overloading |
| Late Binding | Function resolved at run time | virtual keyword |
| Dynamic Binding | Same as Late Binding | virtual keyword |
| Static Binding | Same as Early Binding | Non-virtual function calls |
virtual functions. Early binding = Static binding =
Compile-time binding.Function overriding occurs when a derived class redefines a base class function with the same name and
signature. The base class function must be declared virtual for run-time polymorphism. Without
virtual, the base class version is called even through a derived class pointer. With
virtual, the correct derived class version is called based on the actual object at run-time. This
is called run-time or dynamic polymorphism.
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound(){ cout<<"Some animal sound"<<endl; }
void breathe(){ cout<<"Animal breathes"<<endl; }
};
class Dog : public Animal {
public:
void sound() override { cout<<"Dog: Woof!"<<endl; }
};
class Cat : public Animal {
public:
void sound() override { cout<<"Cat: Meow!"<<endl; }
};
int main(){
Animal* arr[3];
arr[0] = new Animal();
arr[1] = new Dog();
arr[2] = new Cat();
for(int i=0; i<3; i++){
arr[i]->sound(); // runtime polymorphism
arr[i]->breathe(); // not overridden - base version
}
return 0;
}
Some animal sound
Animal breathes
Dog: Woof!
Animal breathes
Cat: Meow!
Animal breathes
virtual void sound() in Animal: marks it overridable. Without virtual, base
version always called via pointer.override keyword in Dog/Cat: tells compiler 'I am intentionally overriding'.
Gives error if signature doesn't match base.Animal* arr[3]: array of base pointers. Can hold Animal, Dog, Cat objects.
arr[i]->sound(): at runtime, C++ checks actual object type via
vptr/vtable and calls correct version.arr[i]->breathe(): NOT virtual, NOT overridden → always calls
Animal::breathe(). Early binding.class Shape { public: virtual void draw(){ cout<<"S"; } };
class Circle : public Shape { public: void draw(){ cout<<"C"; } };
virtual = enables run-time polymorphism
Without virtual = compile-time (wrong function called via base pointer)
UML Sequence Diagram
What is a UML Interaction Diagram?
In UML, Interaction Diagrams show how objects communicate with each other to carry out a specific functionality. They focus on message flow, order of execution, and object collaboration.
Two Types of Interaction Diagrams
1. Sequence Diagram — emphasizes time sequence of messages
2. Collaboration Diagram — emphasizes structural organization of objects
Sequence Diagram — Definition
A Sequence Diagram shows how objects interact in a specific order over time by exchanging messages. It focuses on WHEN and IN WHAT ORDER messages are passed.
Purpose
✓ Represents object interactions in time sequence
✓ Shows order of message flow between objects
✓ Helps understand dynamic behavior of a system
✓ Describes how a use case is executed
✓ Helps in system design, analysis, and debugging
Components (Notations)
| Component | Symbol | Meaning |
|---|---|---|
| Actor | Stick figure | External entity interacting with the system |
| Lifeline | Vertical dashed line below object box | Represents object's existence over time |
| Activation Bar | Thin rectangle on lifeline | Shows when object is active/executing |
| Synchronous Message | Solid arrow → | Sender waits for reply before continuing |
| Asynchronous Message | Open arrow → | Sender does NOT wait for reply |
| Return Message | Dashed arrow <-- | Response returned to the caller |
| Self Message | Arrow looping back to same lifeline | Object calls itself |
| Create Message | Dashed arrow to new object | Creates a new object/lifeline |
| Destroy Message | Arrow with X at end | Destroys an object |
Steps to Create a Sequence Diagram (Exam Guide)
Example — ATM Cash Withdrawal
Scenario: Customer withdraws cash from ATM
Objects Involved: Customer (Actor), ATM, Bank Server
Customer ATM Bank Server
| | |
|--insertCard--->| |
|--enterPIN----->| |
| |---verifyPIN------->|
| |<--PINValid---------|
|--requestCash-->| |
| |---checkBalance---->|
| |<--balanceSufficient|
| |---dispenseCash---->|
|<--receiveCash--| |
| | |
How to Write Sequence Diagram in Exam
Template answer (5 marks): Define → List components/notations (4-5 points) → State purpose → Draw or describe ATM example → Mention benefits vs drawbacks
How to Write Collaboration Diagram in Exam
Template answer (5 marks): Define → Compare with Sequence Diagram → List notations → Describe/draw ATM example → List benefits
Benefits and Drawbacks
| Benefits | Drawbacks |
|---|---|
| Explores real-time application flow | Too many lifelines makes it complex |
| Depicts message flow between objects | Changing message order produces incorrect results |
| Easy to update on system change | Each sequence needs distinct notations |
| Supports forward and reverse engineering | Complexity grows with system size |
A Sequence Diagram is a UML interaction diagram that shows how objects interact with each other in a specific order over time by exchanging messages. It focuses on the time sequence (WHEN and IN WHAT ORDER) of messages. Key notations: Lifeline (vertical dashed line), Actor (stick figure), Activation Bar (rectangle), Synchronous Message (solid arrow), Return Message (dashed arrow). Example: ATM withdrawal scenario shows Customer→ATM→Bank Server message flow. Purpose: to visualize and design dynamic behavior of a system.
class A { public: void callB(B &obj){ obj.hello(); } };
class B { public: void hello(){ cout<<"Hi"; } };
Hi
Lifeline = dashed vertical line | Arrow = message
Emphasizes TIME sequence
Collaboration Diagram
Definition
A Collaboration Diagram (also called Communication Diagram) is a UML interaction diagram that shows how objects interact through messages, emphasizing structural organization and relationships among objects — rather than time sequence.
Purpose
✓ Show object collaboration in a system
✓ Emphasize links/associations between objects
✓ Understand object responsibilities
✓ Represent message flow using numbered arrows
Components (Notations)
| Component | Symbol | Meaning |
|---|---|---|
| Object/Participant | Rectangle with name | An object participating in the interaction |
| Multiple Objects | Stacked rectangles | Multiple instances of same class |
| Actor | Stick figure | External entity involved |
| Message | Numbered arrow between objects | Communication between objects |
| Self Message | Arrow looping to same object | Object calls itself |
| Link | Line connecting objects | Association/relationship between objects |
| Return Message | Dashed arrow | Response sent back to caller |
Steps to Draw Collaboration Diagram
Sequence vs Collaboration Diagram
| Feature | Sequence Diagram | Collaboration Diagram |
|---|---|---|
| Focus | Time sequence / order of messages | Structural organization / object links |
| Layout | Vertical (top to bottom) | Network / graph (objects as nodes) |
| Message numbering | Implied by vertical position | Explicit numbers (1, 2, 3...) |
| Best for | Understanding flow over time | Understanding object relationships |
Example — ATM Balance Enquiry (Collaboration)
[Customer] ---1: insertCard---> [ATM]
[ATM] ---2: requestPIN---> [Customer]
[Customer] ---3: enterPIN-----> [ATM]
[ATM] ---4: verifyPIN----> [BankServer]
[BankServer]---5: sendBalance-> [ATM]
[ATM] ---6: displayBalance->[Customer]
Numbers indicate message order. Objects shown as rectangles, arrows show message direction.
Benefits of Collaboration Diagrams
✓ Simplifies how system components interact
✓ Enhances discussion and decision-making
✓ Helps visualize data and control flow
✓ Aids in debugging by showing interaction sequence and error sources
A Collaboration Diagram (Communication Diagram) is a UML interaction diagram showing how objects are connected and exchange messages, emphasizing structural relationships. Objects are shown as rectangles, links as lines, and messages as numbered arrows. Unlike Sequence Diagram (which focuses on time order), Collaboration Diagram focuses on object structure. Steps: Identify objects → Define interactions → Add numbered messages → Show relationships → Document. Example: ATM Balance Enquiry shows Customer, ATM, and BankServer exchanging numbered messages.
class Printer { public: void print(){ cout<<"Printing"; } };
class User { public: void use(Printer &p){ p.print(); } };
Printing
vs Sequence = time order (top to bottom)
Collaboration emphasizes STRUCTURE | Sequence emphasizes TIME
Input-Based Programs — Methods & Polymorphism
#include <iostream>
using namespace std;
class Employee {
string name;
int id;
public:
Employee(string n, int i) {
name = n;
id = i;
}
void display() {
cout << "Employee: " << name << ", ID: " << id << "\n";
}
};
int main() {
string empName;
int empId;
cout << "Enter Name: ";
cin >> empName;
cout << "Enter ID: ";
cin >> empId;
Employee e1(empName, empId);
e1.display();
return 0;
}
Output Traps — Advanced
What happens when you delete a derived object through a base pointer if the base destructor is NOT virtual?
Only the Base destructor is called. The Derived destructor is skipped, leading to a memory leak!
What gets called when an object is passed by value to a function?
The Copy Constructor is called to create a temporary copy. If not defined, the default shallow copy constructor is used.
Write-From-Scratch Exam Guides
ReturnType operator+(const ClassName& obj)
this->member + obj.member, and return it.main(), test it with C = A + B;