Classes and Objects, Methods and Messages
1. Introduction
Object-Oriented Programming (OOP) is a programming approach in which a program is designed around objects rather than only around functions and procedures. An object represents a real-world entity such as a student, employee, bank account, car, or sensor. Each object contains data representing its state and functions representing its behaviour.
In C++, the fundamental building blocks of object-oriented programming are classes and objects. A class defines the structure and behaviour of objects, while an object is an actual instance of a class. Objects communicate with each other through method calls, commonly described in OOP terminology as message passing.
The relationship can be represented as:
Class → Blueprint/Definition → Objects → Actual entities
For example, Student can be defined as a class. Individual students such as student1 and student2 are objects of the Student class.
2. Class
A class is a user-defined data type that groups related data members and member functions into a single unit.
The data members represent the state of an object, whereas member functions represent its behaviour.
For example, a Student class may contain:
Roll number
Name
Marks
and functions such as:
readData()displayData()calculateGrade()
Thus, a class provides a logical representation of an entity and specifies what data an object will contain and what operations can be performed on that data.
Definition
A class is a user-defined data type that encapsulates data members and member functions into a single unit and serves as a blueprint for creating objects.
3. General Syntax of a Class
class ClassName
{
access_specifier:
data_members;
member_functions;
};For example:
class Student
{
private:
int rollNo;
float marks;
public:
void input();
void display();
};Here:
classis the C++ keyword used to declare a class.Studentis the class name.rollNoandmarksare data members.input()anddisplay()are member functions.privateandpublicare access specifiers.The semicolon after the closing brace is mandatory.
4. Components of a Class
A class generally consists of two major components:
4.1 Data Members
Data members are variables declared inside a class. They represent the properties or state of an object.
Example:
class Student
{
int rollNo;
float marks;
};Here, rollNo and marks are data members.
4.2 Member Functions
Member functions are functions declared inside a class that define the behaviour or operations of its objects.
Example:
class Student
{
int rollNo;
float marks;
public:
void display()
{
cout << rollNo << endl;
cout << marks << endl;
}
};Here, display() is a member function.
5. Access Specifiers
C++ provides three main access specifiers:
| Access Specifier | Accessibility |
|---|---|
private | Accessible only within the class |
public | Accessible from outside the class |
protected | Accessible within the class and derived classes |
The default access specifier of a class in C++ is private.
For example:
class Student
{
int rollNo; // private by default
public:
void display()
{
cout << rollNo;
}
};The variable rollNo cannot normally be accessed directly through an object from outside the class.
6. Object
An object is an instance of a class.
When a class is defined, memory is generally not allocated for its non-static data members merely because the class definition exists. Memory for those data members is associated with objects when objects are created.
For example:
class Student
{
public:
int rollNo;
void display()
{
cout << rollNo;
}
};
int main()
{
Student s1;
Student s2;
return 0;
}Here:
Student→ classs1→ objects2→ object
Both s1 and s2 are objects of the Student class.
Each object has its own copy of the non-static data members.
7. Class and Object Relationship
A class can be considered a blueprint, whereas an object is the actual entity created using that blueprint.
For example, consider a building design.
A building plan describes the structure of a building, but the plan itself is not the physical building. Similarly, a class describes the properties and behaviour of objects, while an object is the actual instance.
For example:
class Car
{
public:
string color;
void start()
{
cout << "Car started";
}
};Objects can then be created:
Car car1;
Car car2;
Car car3;Here, Car defines the common structure and behaviour, while car1, car2, and car3 are individual objects.
8. Creating Objects
Objects can be created using the class name followed by the object name.
Syntax
ClassName objectName;Example:
Student s1;Multiple objects can also be declared:
Student s1, s2, s3;Objects may also be created dynamically using pointers and new, but static/local object creation is sufficient for understanding the basic concept.
9. Accessing Members of an Object
The dot (.) operator is used to access accessible members of an object.
Syntax
objectName.memberName;For example:
class Student
{
public:
int rollNo;
void display()
{
cout << rollNo;
}
};
int main()
{
Student s1;
s1.rollNo = 101;
s1.display();
return 0;
}Output
101Here:
s1.rollNo = 101;assigns a value to the data member of object s1.
Similarly:
s1.display();invokes the display() member function for object s1.
10. Complete Example of Class and Object
Consider the following program:
#include <iostream>
using namespace std;
class Student
{
private:
int rollNo;
float marks;
public:
void setData(int r, float m)
{
rollNo = r;
marks = m;
}
void display()
{
cout << "Roll Number: " << rollNo << endl;
cout << "Marks: " << marks << endl;
}
};
int main()
{
Student s1;
s1.setData(101, 85.5);
s1.display();
return 0;
}Output
Roll Number: 101
Marks: 85.5Explanation
The class Student contains two private data members:
int rollNo;
float marks;Since these members are private, they cannot be directly accessed from main().
The public member function:
setData()is used to assign values to them.
The function:
display()is used to display the values.
The statement:
Student s1;creates an object named s1.
The statement:
s1.setData(101, 85.5);calls the setData() method for object s1.
11. Methods in C++
In general OOP terminology, a method is an operation or function associated with an object or class.
In C++, methods are commonly implemented as member functions.
For example:
class Calculator
{
public:
int add(int a, int b)
{
return a + b;
}
};Here, add() is a member function and can be considered a method of the Calculator class.
An object can invoke the method:
Calculator c;
cout << c.add(10, 20);Output:
3012. Types of Methods
Depending upon their purpose, member functions can perform different operations.
12.1 Accessor Method
An accessor method is used to access or retrieve the value of a data member.
Example:
int getMarks()
{
return marks;
}Such functions are commonly called getter methods.
12.2 Mutator Method
A mutator method modifies or assigns the value of a data member.
Example:
void setMarks(int m)
{
marks = m;
}Such functions are commonly called setter methods.
12.3 Other Behavioural Methods
A class may also contain methods that perform calculations or other operations.
Example:
float calculatePercentage()
{
return totalMarks / 5.0;
}Thus, methods define what an object can do.
13. Defining a Member Function Outside the Class
A member function can be defined outside the class using the scope resolution operator (::).
Example:
#include <iostream>
using namespace std;
class Student
{
private:
int marks;
public:
void setMarks(int m);
void display();
};
void Student::setMarks(int m)
{
marks = m;
}
void Student::display()
{
cout << "Marks: " << marks;
}
int main()
{
Student s1;
s1.setMarks(85);
s1.display();
return 0;
}Here:
Student::setMarks()means that setMarks() belongs to the Student class.
Similarly:
Student::display()defines the display() member function outside the class.
14. Methods and Objects
A method operates in the context of an object.
Consider:
class BankAccount
{
private:
double balance;
public:
void deposit(double amount)
{
balance += amount;
}
void displayBalance()
{
cout << balance;
}
};Suppose two objects are created:
BankAccount account1;
BankAccount account2;When we write:
account1.deposit(5000);the method operates on account1.
When we write:
account2.deposit(3000);the same method operates on account2.
Thus, the same member function can operate on different objects, with each object maintaining its own state.
15. Messages in Object-Oriented Programming
In OOP, objects communicate with one another by sending messages.
A message essentially represents a request to an object to perform a particular operation.
For example:
student.display();can conceptually be viewed as:
Send a
displaymessage to thestudentobject.
Similarly:
account.deposit(5000);can be understood as:
Send a
depositmessage with the value5000to theaccountobject.
In C++, message passing is primarily implemented through member-function calls.
16. Message Structure
A message generally contains:
Receiver object – the object that receives the request.
Method/function name – the operation to be performed.
Arguments – optional information required by the method.
For example:
account.deposit(5000);Here:
| Component | Example |
|---|---|
| Receiver object | account |
| Method | deposit() |
| Argument | 5000 |
Conceptually:
Object → Message → Method Execution → Result/State Change
17. Example of Message Passing
Consider two classes representing a simple interaction:
#include <iostream>
using namespace std;
class Printer
{
public:
void printMessage()
{
cout << "Hello from Printer";
}
};
class Computer
{
public:
void sendToPrinter(Printer &p)
{
p.printMessage();
}
};
int main()
{
Printer p1;
Computer c1;
c1.sendToPrinter(p1);
return 0;
}Output
Hello from PrinterThe important statement is:
p.printMessage();The Computer object invokes a method of the Printer object. From the OOP perspective, the Printer object receives a request to perform the printMessage() operation.
18. Message Passing and Encapsulation
Message passing is closely related to encapsulation.
An object's internal data can be kept private, and other objects interact with it through publicly available methods.
For example:
class BankAccount
{
private:
double balance;
public:
void deposit(double amount)
{
if (amount > 0)
balance += amount;
}
};An external object cannot directly manipulate:
balanceif it is private.
Instead, it communicates through:
account.deposit(5000);This provides controlled access to the object's state.
19. Class, Object, Method and Message
These four concepts are closely related but should not be confused.
| Concept | Meaning | Example |
|---|---|---|
| Class | Blueprint/user-defined type | Student |
| Object | Instance of a class | s1 |
| Method | Operation/member function | display() |
| Message | Request sent to an object to perform an operation | s1.display() |
Consider:
Student s1;
s1.display();Here:
Studentis the class.s1is the object.display()is the method/member function.s1.display()represents the message/request sent tos1.
20. Real-World Analogy
Consider a bank account.
The bank account can be represented as an object.
Its state may include:
Account number
Account holder
Balance
Its behaviour may include:
Deposit
Withdraw
Check balance
For example:
account.deposit(5000);
account.withdraw(1000);
account.checkBalance();Each statement represents an operation requested from the account object.
Thus:
Object: account
Messages/requests:
deposit(5000)
withdraw(1000)
checkBalance()The object internally manages its state while exposing appropriate operations to the outside world.
21. Important Characteristics of Classes and Objects
Class
Provides a blueprint for objects.
Combines data and functions.
Supports encapsulation.
Defines the properties and behaviour common to its objects.
Can contain private, protected and public members.
Object
Is an instance of a class.
Has its own state.
Can invoke accessible methods.
Can interact with other objects.
Occupies memory for its non-static data members.
Methods
Define the behaviour of objects.
Can access members of their class according to access rules.
May accept arguments and return values.
Can be defined inside or outside the class.
Messages
Represent requests between objects.
In C++, commonly implemented through member-function calls.
May contain arguments.
Allow objects to cooperate to perform a larger task.
22. Simple Conceptual View
The overall concept can be understood as:
Class
↓ creates
Objects
↓ communicate through
Messages / Method Calls
↓ execute
Methods
↓ modify or retrieve
Object State
This forms the basic interaction model of object-oriented programming.
23. Key Points to Remember
A class is a user-defined data type and acts as a blueprint for objects.
An object is an instance of a class.
Data members represent the state of an object.
Member functions/methods represent the behaviour of an object.
The dot (
.) operator is generally used to access accessible members through an object.C++ uses the scope resolution operator (
::) to define a member function outside its class.Objects can communicate by sending messages.
In C++, message passing is primarily represented through member-function calls.
Encapsulation protects an object's internal state and provides controlled interaction through methods.
A single class can be used to create multiple objects, each maintaining its own non-static data.
24. Short Example for Examination
#include <iostream>
using namespace std;
class Rectangle
{
private:
int length, breadth;
public:
void setData(int l, int b)
{
length = l;
breadth = b;
}
int area()
{
return length * breadth;
}
};
int main()
{
Rectangle r1;
r1.setData(10, 5);
cout << "Area = " << r1.area();
return 0;
}Output
Area = 50Concept involved
In this example:
Rectangle→ Classr1→ ObjectsetData()→ Methodarea()→ Methodr1.setData(10, 5)→ Message/method callr1.area()→ Message/method calllengthandbreadth→ Data membersprivate→ Provides data protection/encapsulation
This example therefore demonstrates the relationship among classes, objects, methods and messages in C++.
No comments:
Post a Comment